From 5fd205f77d37e4a2097f5a69e5d3f867cd94fcde Mon Sep 17 00:00:00 2001 From: oSumAtrIX Date: Sun, 26 Nov 2023 05:56:31 +0100 Subject: [PATCH] chore: Lint code --- .../cli/command/ListPatchesCommand.kt | 121 +++++++------ .../app/revanced/cli/command/MainCommand.kt | 27 +-- .../revanced/cli/command/OptionsCommand.kt | 33 ++-- .../app/revanced/cli/command/PatchCommand.kt | 166 ++++++++++-------- .../cli/command/utility/InstallCommand.kt | 11 +- .../cli/command/utility/UninstallCommand.kt | 22 +-- .../cli/command/utility/UtilityCommand.kt | 2 +- 7 files changed, 202 insertions(+), 180 deletions(-) diff --git a/src/main/kotlin/app/revanced/cli/command/ListPatchesCommand.kt b/src/main/kotlin/app/revanced/cli/command/ListPatchesCommand.kt index 92f4d37..1886613 100644 --- a/src/main/kotlin/app/revanced/cli/command/ListPatchesCommand.kt +++ b/src/main/kotlin/app/revanced/cli/command/ListPatchesCommand.kt @@ -8,119 +8,126 @@ import picocli.CommandLine.Help.Visibility.ALWAYS import java.io.File import java.util.logging.Logger - @Command( name = "list-patches", - description = ["List patches from supplied patch bundles."] + description = ["List patches from supplied patch bundles."], ) internal object ListPatchesCommand : Runnable { private val logger = Logger.getLogger(ListPatchesCommand::class.java.name) @Parameters( description = ["Paths to patch bundles."], - arity = "1..*" + arity = "1..*", ) private lateinit var patchBundles: Array @Option( names = ["-d", "--with-descriptions"], description = ["List their descriptions."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var withDescriptions: Boolean = true @Option( names = ["-p", "--with-packages"], description = ["List the packages the patches are compatible with."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var withPackages: Boolean = false @Option( names = ["-v", "--with-versions"], description = ["List the versions of the apps the patches are compatible with."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var withVersions: Boolean = false @Option( names = ["-o", "--with-options"], description = ["List the options of the patches."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var withOptions: Boolean = false @Option( names = ["-u", "--with-universal-patches"], description = ["List patches which are compatible with any app."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var withUniversalPatches: Boolean = true @Option( names = ["-i", "--index"], description = ["List the index of each patch in relation to the supplied patch bundles."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var withIndex: Boolean = true @Option( names = ["-f", "--filter-package-name"], - description = ["Filter patches by package name."] + description = ["Filter patches by package name."], ) private var packageName: String? = null override fun run() { - fun Patch.CompatiblePackage.buildString() = buildString { - if (withVersions && versions != null) { - appendLine("Package name: $name") - appendLine("Compatible versions:") - append(versions!!.joinToString("\n") { version -> version }.prependIndent("\t")) - } else append("Package name: $name") - } - - fun PatchOption<*>.buildString() = buildString { - appendLine("Title: $title") - description?.let { appendLine("Description: $it") } - default?.let { - appendLine("Key: $key") - append("Default: $it") - } ?: append("Key: $key") - - values?.let { values -> - appendLine("\nValid values:") - append(values.map { "${it.value} (${it.key})" }.joinToString("\n").prependIndent("\t")) - } - } - - fun IndexedValue>.buildString() = let { (index, patch) -> + fun Patch.CompatiblePackage.buildString() = buildString { - if (withIndex) appendLine("Index: $index") - - append("Name: ${patch.name}") - - if (withDescriptions) append("\nDescription: ${patch.description}") - - if (withOptions && patch.options.isNotEmpty()) { - appendLine("\nOptions:") - append( - patch.options.values.joinToString("\n\n") { option -> - option.buildString() - }.prependIndent("\t") - ) - } - - if (withPackages && patch.compatiblePackages != null) { - appendLine("\nCompatible packages:") - append(patch.compatiblePackages!!.joinToString("\n") { - it.buildString() - }.prependIndent("\t")) + if (withVersions && versions != null) { + appendLine("Package name: $name") + appendLine("Compatible versions:") + append(versions!!.joinToString("\n") { version -> version }.prependIndent("\t")) + } else { + append("Package name: $name") } } - } - fun Patch<*>.filterCompatiblePackages(name: String) = compatiblePackages?.any { it.name == name } - ?: withUniversalPatches + fun PatchOption<*>.buildString() = + buildString { + appendLine("Title: $title") + description?.let { appendLine("Description: $it") } + default?.let { + appendLine("Key: $key") + append("Default: $it") + } ?: append("Key: $key") + + values?.let { values -> + appendLine("\nValid values:") + append(values.map { "${it.value} (${it.key})" }.joinToString("\n").prependIndent("\t")) + } + } + + fun IndexedValue>.buildString() = + let { (index, patch) -> + buildString { + if (withIndex) appendLine("Index: $index") + + append("Name: ${patch.name}") + + if (withDescriptions) append("\nDescription: ${patch.description}") + + if (withOptions && patch.options.isNotEmpty()) { + appendLine("\nOptions:") + append( + patch.options.values.joinToString("\n\n") { option -> + option.buildString() + }.prependIndent("\t"), + ) + } + + if (withPackages && patch.compatiblePackages != null) { + appendLine("\nCompatible packages:") + append( + patch.compatiblePackages!!.joinToString("\n") { + it.buildString() + }.prependIndent("\t"), + ) + } + } + } + + fun Patch<*>.filterCompatiblePackages(name: String) = + compatiblePackages?.any { it.name == name } + ?: withUniversalPatches val patches = PatchBundleLoader.Jar(*patchBundles).withIndex().toList() @@ -129,4 +136,4 @@ internal object ListPatchesCommand : Runnable { if (filtered.isNotEmpty()) logger.info(filtered.joinToString("\n\n") { it.buildString() }) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/app/revanced/cli/command/MainCommand.kt b/src/main/kotlin/app/revanced/cli/command/MainCommand.kt index 49de701..7a76097 100644 --- a/src/main/kotlin/app/revanced/cli/command/MainCommand.kt +++ b/src/main/kotlin/app/revanced/cli/command/MainCommand.kt @@ -7,23 +7,24 @@ import picocli.CommandLine.Command import picocli.CommandLine.IVersionProvider import java.util.* - fun main(args: Array) { Logger.setDefault() CommandLine(MainCommand).execute(*args).let(System::exit) } private object CLIVersionProvider : IVersionProvider { - override fun getVersion() = arrayOf( - MainCommand::class.java.getResourceAsStream( - "/app/revanced/cli/version.properties" - )?.use { stream -> - Properties().apply { - load(stream) - }.let { - "ReVanced CLI v${it.getProperty("version")}" - } - } ?: "ReVanced CLI") + override fun getVersion() = + arrayOf( + MainCommand::class.java.getResourceAsStream( + "/app/revanced/cli/version.properties", + )?.use { stream -> + Properties().apply { + load(stream) + }.let { + "ReVanced CLI v${it.getProperty("version")}" + } + } ?: "ReVanced CLI", + ) } @Command( @@ -36,6 +37,6 @@ private object CLIVersionProvider : IVersionProvider { PatchCommand::class, OptionsCommand::class, UtilityCommand::class, - ] + ], ) -private object MainCommand \ No newline at end of file +private object MainCommand diff --git a/src/main/kotlin/app/revanced/cli/command/OptionsCommand.kt b/src/main/kotlin/app/revanced/cli/command/OptionsCommand.kt index cd7fef1..72d4240 100644 --- a/src/main/kotlin/app/revanced/cli/command/OptionsCommand.kt +++ b/src/main/kotlin/app/revanced/cli/command/OptionsCommand.kt @@ -17,43 +17,46 @@ internal object OptionsCommand : Runnable { @CommandLine.Parameters( description = ["Paths to patch bundles."], - arity = "1..*" + arity = "1..*", ) private lateinit var patchBundles: Array @CommandLine.Option( names = ["-p", "--path"], description = ["Path to patch options JSON file."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var filePath: File = File("options.json") @CommandLine.Option( names = ["-o", "--overwrite"], description = ["Overwrite existing options file."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var overwrite: Boolean = false @CommandLine.Option( names = ["-u", "--update"], description = ["Update existing options by adding missing and removing non-existent options."], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var update: Boolean = false - override fun run() = try { - PatchBundleLoader.Jar(*patchBundles).let { patches -> - val exists = filePath.exists() - if (!exists || overwrite) { - if (exists && update) patches.setOptions(filePath) + override fun run() = + try { + PatchBundleLoader.Jar(*patchBundles).let { patches -> + val exists = filePath.exists() + if (!exists || overwrite) { + if (exists && update) patches.setOptions(filePath) - Options.serialize(patches, prettyPrint = true).let(filePath::writeText) - } else throw OptionsFileAlreadyExistsException() + Options.serialize(patches, prettyPrint = true).let(filePath::writeText) + } else { + throw OptionsFileAlreadyExistsException() + } + } + } catch (ex: OptionsFileAlreadyExistsException) { + logger.severe("Options file already exists, use --overwrite to override it") } - } catch (ex: OptionsFileAlreadyExistsException) { - logger.severe("Options file already exists, use --overwrite to override it") - } class OptionsFileAlreadyExistsException : Exception() -} \ No newline at end of file +} diff --git a/src/main/kotlin/app/revanced/cli/command/PatchCommand.kt b/src/main/kotlin/app/revanced/cli/command/PatchCommand.kt index b319dfa..410c94a 100644 --- a/src/main/kotlin/app/revanced/cli/command/PatchCommand.kt +++ b/src/main/kotlin/app/revanced/cli/command/PatchCommand.kt @@ -219,20 +219,24 @@ internal object PatchCommand : Runnable { override fun run() { // region Setup - val outputFilePath = outputFilePath ?: File("").absoluteFile.resolve( - "${apk.nameWithoutExtension}-patched.${apk.extension}", - ) + val outputFilePath = + outputFilePath ?: File("").absoluteFile.resolve( + "${apk.nameWithoutExtension}-patched.${apk.extension}", + ) - val resourceCachePath = resourceCachePath ?: outputFilePath.parentFile.resolve( - "${outputFilePath.nameWithoutExtension}-resource-cache", - ) + val resourceCachePath = + resourceCachePath ?: outputFilePath.parentFile.resolve( + "${outputFilePath.nameWithoutExtension}-resource-cache", + ) - val optionsFile = optionsFile ?: outputFilePath.parentFile.resolve( - "${outputFilePath.nameWithoutExtension}-options.json", - ) + val optionsFile = + optionsFile ?: outputFilePath.parentFile.resolve( + "${outputFilePath.nameWithoutExtension}-options.json", + ) - val keystoreFilePath = keystoreFilePath ?: outputFilePath.parentFile - .resolve("${outputFilePath.nameWithoutExtension}.keystore") + val keystoreFilePath = + keystoreFilePath ?: outputFilePath.parentFile + .resolve("${outputFilePath.nameWithoutExtension}.keystore") // endregion @@ -265,42 +269,45 @@ internal object PatchCommand : Runnable { true, ), ).use { patcher -> - val filteredPatches = patcher.filterPatchSelection(patches).also { patches -> - logger.info("Setting patch options") + val filteredPatches = + patcher.filterPatchSelection(patches).also { patches -> + logger.info("Setting patch options") - if (optionsFile.exists()) { - patches.setOptions(optionsFile) - } else { - Options.serialize(patches, prettyPrint = true).let(optionsFile::writeText) + if (optionsFile.exists()) { + patches.setOptions(optionsFile) + } else { + Options.serialize(patches, prettyPrint = true).let(optionsFile::writeText) + } } - } // region Patch - val patcherResult = patcher.apply { - acceptIntegrations(integrations) - acceptPatches(filteredPatches.toList()) + val patcherResult = + patcher.apply { + acceptIntegrations(integrations) + acceptPatches(filteredPatches.toList()) - // Execute patches. - runBlocking { - apply(false).collect { patchResult -> - patchResult.exception?.let { - StringWriter().use { writer -> - it.printStackTrace(PrintWriter(writer)) - logger.severe("${patchResult.patch.name} failed:\n$writer") - } - } ?: logger.info("${patchResult.patch.name} succeeded") + // Execute patches. + runBlocking { + apply(false).collect { patchResult -> + patchResult.exception?.let { + StringWriter().use { writer -> + it.printStackTrace(PrintWriter(writer)) + logger.severe("${patchResult.patch.name} failed:\n$writer") + } + } ?: logger.info("${patchResult.patch.name} succeeded") + } } - } - }.get() + }.get() // endregion // region Save - val alignedFile = resourceCachePath.resolve(apk.name).apply { - ApkUtils.copyAligned(apk, this, patcherResult) - } + val alignedFile = + resourceCachePath.resolve(apk.name).apply { + ApkUtils.copyAligned(apk, this, patcherResult) + } if (!mount) { ApkUtils.sign( @@ -341,61 +348,64 @@ internal object PatchCommand : Runnable { * @param patches The patches to filter. * @return The filtered patches. */ - private fun Patcher.filterPatchSelection(patches: PatchSet): PatchSet = buildSet { - val packageName = context.packageMetadata.packageName - val packageVersion = context.packageMetadata.packageVersion + private fun Patcher.filterPatchSelection(patches: PatchSet): PatchSet = + buildSet { + val packageName = context.packageMetadata.packageName + val packageVersion = context.packageMetadata.packageVersion - patches.withIndex().forEach patch@{ (i, patch) -> - val patchName = patch.name!! + patches.withIndex().forEach patch@{ (i, patch) -> + val patchName = patch.name!! - val explicitlyExcluded = excludedPatches.contains(patchName) || excludedPatchesByIndex.contains(i) - if (explicitlyExcluded) return@patch logger.info("Excluding $patchName") + val explicitlyExcluded = excludedPatches.contains(patchName) || excludedPatchesByIndex.contains(i) + if (explicitlyExcluded) return@patch logger.info("Excluding $patchName") - // Make sure the patch is compatible with the supplied APK files package name and version. - patch.compatiblePackages?.let { packages -> - packages.singleOrNull { it.name == packageName }?.let { `package` -> - val matchesVersion = force || `package`.versions?.let { - it.any { version -> version == packageVersion } - } ?: true + // Make sure the patch is compatible with the supplied APK files package name and version. + patch.compatiblePackages?.let { packages -> + packages.singleOrNull { it.name == packageName }?.let { `package` -> + val matchesVersion = + force || `package`.versions?.let { + it.any { version -> version == packageVersion } + } ?: true - if (!matchesVersion) { - return@patch logger.warning( - "$patchName is incompatible with version $packageVersion. " + - "This patch is only compatible with version " + - packages.joinToString(";") { pkg -> - pkg.versions!!.joinToString(", ") - }, - ) - } - } ?: return@patch logger.fine( - "$patchName is incompatible with $packageName. " + - "This patch is only compatible with " + - packages.joinToString(", ") { `package` -> `package`.name }, - ) + if (!matchesVersion) { + return@patch logger.warning( + "$patchName is incompatible with version $packageVersion. " + + "This patch is only compatible with version " + + packages.joinToString(";") { pkg -> + pkg.versions!!.joinToString(", ") + }, + ) + } + } ?: return@patch logger.fine( + "$patchName is incompatible with $packageName. " + + "This patch is only compatible with " + + packages.joinToString(", ") { `package` -> `package`.name }, + ) - return@let - } ?: logger.fine("$patchName has no constraint on packages.") + return@let + } ?: logger.fine("$patchName has no constraint on packages.") - // If the patch is implicitly used, it will be only included if [exclusive] is false. - val implicitlyIncluded = !exclusive && patch.use - // If the patch is explicitly used, it will be included even if [exclusive] is false. - val explicitlyIncluded = includedPatches.contains(patchName) || includedPatchesByIndex.contains(i) + // If the patch is implicitly used, it will be only included if [exclusive] is false. + val implicitlyIncluded = !exclusive && patch.use + // If the patch is explicitly used, it will be included even if [exclusive] is false. + val explicitlyIncluded = includedPatches.contains(patchName) || includedPatchesByIndex.contains(i) - val included = implicitlyIncluded || explicitlyIncluded - if (!included) return@patch logger.info("$patchName excluded") // Case 1. + val included = implicitlyIncluded || explicitlyIncluded + if (!included) return@patch logger.info("$patchName excluded") // Case 1. - logger.fine("Adding $patchName") + logger.fine("Adding $patchName") - add(patch) + add(patch) + } } - } private fun purge(resourceCachePath: File) { - val result = if (resourceCachePath.deleteRecursively()) { - "Purged resource cache directory" - } else { - "Failed to purge resource cache directory" - } + val result = + if (resourceCachePath.deleteRecursively()) { + "Purged resource cache directory" + } else { + "Failed to purge resource cache directory" + } logger.info(result) } } diff --git a/src/main/kotlin/app/revanced/cli/command/utility/InstallCommand.kt b/src/main/kotlin/app/revanced/cli/command/utility/InstallCommand.kt index 85be022..508bf1c 100644 --- a/src/main/kotlin/app/revanced/cli/command/utility/InstallCommand.kt +++ b/src/main/kotlin/app/revanced/cli/command/utility/InstallCommand.kt @@ -32,11 +32,12 @@ internal object InstallCommand : Runnable { private var packageName: String? = null override fun run() { - fun install(deviceSerial: String? = null) = try { - AdbManager.getAdbManager(deviceSerial, packageName != null).install(AdbManager.Apk(apk, packageName)) - } catch (e: AdbManager.DeviceNotFoundException) { - logger.severe(e.toString()) - } + fun install(deviceSerial: String? = null) = + try { + AdbManager.getAdbManager(deviceSerial, packageName != null).install(AdbManager.Apk(apk, packageName)) + } catch (e: AdbManager.DeviceNotFoundException) { + logger.severe(e.toString()) + } deviceSerials?.forEach(::install) ?: install() } diff --git a/src/main/kotlin/app/revanced/cli/command/utility/UninstallCommand.kt b/src/main/kotlin/app/revanced/cli/command/utility/UninstallCommand.kt index e69c46b..49a36f2 100644 --- a/src/main/kotlin/app/revanced/cli/command/utility/UninstallCommand.kt +++ b/src/main/kotlin/app/revanced/cli/command/utility/UninstallCommand.kt @@ -5,41 +5,41 @@ import picocli.CommandLine.* import picocli.CommandLine.Help.Visibility.ALWAYS import java.util.logging.Logger - @Command( name = "uninstall", - description = ["Uninstall a patched app from the devices with the supplied ADB device serials"] + description = ["Uninstall a patched app from the devices with the supplied ADB device serials"], ) internal object UninstallCommand : Runnable { private val logger = Logger.getLogger(UninstallCommand::class.java.name) @Parameters( description = ["ADB device serials. If not supplied, the first connected device will be used."], - arity = "0..*" + arity = "0..*", ) private var deviceSerials: Array? = null @Option( names = ["-p", "--package-name"], description = ["Package name of the app to uninstall"], - required = true + required = true, ) private lateinit var packageName: String @Option( names = ["-u", "--unmount"], description = ["Uninstall by unmounting the patched APK file"], - showDefaultValue = ALWAYS + showDefaultValue = ALWAYS, ) private var unmount: Boolean = false override fun run() { - fun uninstall(deviceSerial: String? = null) = try { - AdbManager.getAdbManager(deviceSerial, unmount).uninstall(packageName) - } catch (e: AdbManager.DeviceNotFoundException) { - logger.severe(e.toString()) - } + fun uninstall(deviceSerial: String? = null) = + try { + AdbManager.getAdbManager(deviceSerial, unmount).uninstall(packageName) + } catch (e: AdbManager.DeviceNotFoundException) { + logger.severe(e.toString()) + } deviceSerials?.forEach { uninstall(it) } ?: uninstall() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/app/revanced/cli/command/utility/UtilityCommand.kt b/src/main/kotlin/app/revanced/cli/command/utility/UtilityCommand.kt index 70c77c6..b558fdc 100644 --- a/src/main/kotlin/app/revanced/cli/command/utility/UtilityCommand.kt +++ b/src/main/kotlin/app/revanced/cli/command/utility/UtilityCommand.kt @@ -7,4 +7,4 @@ import picocli.CommandLine description = ["Commands for utility purposes"], subcommands = [InstallCommand::class, UninstallCommand::class], ) -internal object UtilityCommand \ No newline at end of file +internal object UtilityCommand