chore: Lint code

This commit is contained in:
oSumAtrIX 2023-11-26 05:56:31 +01:00
parent e7c3d64bf1
commit 5fd205f77d
No known key found for this signature in database
GPG Key ID: A9B3094ACDB604B4
7 changed files with 202 additions and 180 deletions

View File

@ -8,78 +8,81 @@ import picocli.CommandLine.Help.Visibility.ALWAYS
import java.io.File import java.io.File
import java.util.logging.Logger import java.util.logging.Logger
@Command( @Command(
name = "list-patches", name = "list-patches",
description = ["List patches from supplied patch bundles."] description = ["List patches from supplied patch bundles."],
) )
internal object ListPatchesCommand : Runnable { internal object ListPatchesCommand : Runnable {
private val logger = Logger.getLogger(ListPatchesCommand::class.java.name) private val logger = Logger.getLogger(ListPatchesCommand::class.java.name)
@Parameters( @Parameters(
description = ["Paths to patch bundles."], description = ["Paths to patch bundles."],
arity = "1..*" arity = "1..*",
) )
private lateinit var patchBundles: Array<File> private lateinit var patchBundles: Array<File>
@Option( @Option(
names = ["-d", "--with-descriptions"], names = ["-d", "--with-descriptions"],
description = ["List their descriptions."], description = ["List their descriptions."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var withDescriptions: Boolean = true private var withDescriptions: Boolean = true
@Option( @Option(
names = ["-p", "--with-packages"], names = ["-p", "--with-packages"],
description = ["List the packages the patches are compatible with."], description = ["List the packages the patches are compatible with."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var withPackages: Boolean = false private var withPackages: Boolean = false
@Option( @Option(
names = ["-v", "--with-versions"], names = ["-v", "--with-versions"],
description = ["List the versions of the apps the patches are compatible with."], description = ["List the versions of the apps the patches are compatible with."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var withVersions: Boolean = false private var withVersions: Boolean = false
@Option( @Option(
names = ["-o", "--with-options"], names = ["-o", "--with-options"],
description = ["List the options of the patches."], description = ["List the options of the patches."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var withOptions: Boolean = false private var withOptions: Boolean = false
@Option( @Option(
names = ["-u", "--with-universal-patches"], names = ["-u", "--with-universal-patches"],
description = ["List patches which are compatible with any app."], description = ["List patches which are compatible with any app."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var withUniversalPatches: Boolean = true private var withUniversalPatches: Boolean = true
@Option( @Option(
names = ["-i", "--index"], names = ["-i", "--index"],
description = ["List the index of each patch in relation to the supplied patch bundles."], description = ["List the index of each patch in relation to the supplied patch bundles."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var withIndex: Boolean = true private var withIndex: Boolean = true
@Option( @Option(
names = ["-f", "--filter-package-name"], names = ["-f", "--filter-package-name"],
description = ["Filter patches by package name."] description = ["Filter patches by package name."],
) )
private var packageName: String? = null private var packageName: String? = null
override fun run() { override fun run() {
fun Patch.CompatiblePackage.buildString() = buildString { fun Patch.CompatiblePackage.buildString() =
buildString {
if (withVersions && versions != null) { if (withVersions && versions != null) {
appendLine("Package name: $name") appendLine("Package name: $name")
appendLine("Compatible versions:") appendLine("Compatible versions:")
append(versions!!.joinToString("\n") { version -> version }.prependIndent("\t")) append(versions!!.joinToString("\n") { version -> version }.prependIndent("\t"))
} else append("Package name: $name") } else {
append("Package name: $name")
}
} }
fun PatchOption<*>.buildString() = buildString { fun PatchOption<*>.buildString() =
buildString {
appendLine("Title: $title") appendLine("Title: $title")
description?.let { appendLine("Description: $it") } description?.let { appendLine("Description: $it") }
default?.let { default?.let {
@ -93,7 +96,8 @@ internal object ListPatchesCommand : Runnable {
} }
} }
fun IndexedValue<Patch<*>>.buildString() = let { (index, patch) -> fun IndexedValue<Patch<*>>.buildString() =
let { (index, patch) ->
buildString { buildString {
if (withIndex) appendLine("Index: $index") if (withIndex) appendLine("Index: $index")
@ -106,20 +110,23 @@ internal object ListPatchesCommand : Runnable {
append( append(
patch.options.values.joinToString("\n\n") { option -> patch.options.values.joinToString("\n\n") { option ->
option.buildString() option.buildString()
}.prependIndent("\t") }.prependIndent("\t"),
) )
} }
if (withPackages && patch.compatiblePackages != null) { if (withPackages && patch.compatiblePackages != null) {
appendLine("\nCompatible packages:") appendLine("\nCompatible packages:")
append(patch.compatiblePackages!!.joinToString("\n") { append(
patch.compatiblePackages!!.joinToString("\n") {
it.buildString() it.buildString()
}.prependIndent("\t")) }.prependIndent("\t"),
)
} }
} }
} }
fun Patch<*>.filterCompatiblePackages(name: String) = compatiblePackages?.any { it.name == name } fun Patch<*>.filterCompatiblePackages(name: String) =
compatiblePackages?.any { it.name == name }
?: withUniversalPatches ?: withUniversalPatches
val patches = PatchBundleLoader.Jar(*patchBundles).withIndex().toList() val patches = PatchBundleLoader.Jar(*patchBundles).withIndex().toList()

View File

@ -7,23 +7,24 @@ import picocli.CommandLine.Command
import picocli.CommandLine.IVersionProvider import picocli.CommandLine.IVersionProvider
import java.util.* import java.util.*
fun main(args: Array<String>) { fun main(args: Array<String>) {
Logger.setDefault() Logger.setDefault()
CommandLine(MainCommand).execute(*args).let(System::exit) CommandLine(MainCommand).execute(*args).let(System::exit)
} }
private object CLIVersionProvider : IVersionProvider { private object CLIVersionProvider : IVersionProvider {
override fun getVersion() = arrayOf( override fun getVersion() =
arrayOf(
MainCommand::class.java.getResourceAsStream( MainCommand::class.java.getResourceAsStream(
"/app/revanced/cli/version.properties" "/app/revanced/cli/version.properties",
)?.use { stream -> )?.use { stream ->
Properties().apply { Properties().apply {
load(stream) load(stream)
}.let { }.let {
"ReVanced CLI v${it.getProperty("version")}" "ReVanced CLI v${it.getProperty("version")}"
} }
} ?: "ReVanced CLI") } ?: "ReVanced CLI",
)
} }
@Command( @Command(
@ -36,6 +37,6 @@ private object CLIVersionProvider : IVersionProvider {
PatchCommand::class, PatchCommand::class,
OptionsCommand::class, OptionsCommand::class,
UtilityCommand::class, UtilityCommand::class,
] ],
) )
private object MainCommand private object MainCommand

View File

@ -17,39 +17,42 @@ internal object OptionsCommand : Runnable {
@CommandLine.Parameters( @CommandLine.Parameters(
description = ["Paths to patch bundles."], description = ["Paths to patch bundles."],
arity = "1..*" arity = "1..*",
) )
private lateinit var patchBundles: Array<File> private lateinit var patchBundles: Array<File>
@CommandLine.Option( @CommandLine.Option(
names = ["-p", "--path"], names = ["-p", "--path"],
description = ["Path to patch options JSON file."], description = ["Path to patch options JSON file."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var filePath: File = File("options.json") private var filePath: File = File("options.json")
@CommandLine.Option( @CommandLine.Option(
names = ["-o", "--overwrite"], names = ["-o", "--overwrite"],
description = ["Overwrite existing options file."], description = ["Overwrite existing options file."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var overwrite: Boolean = false private var overwrite: Boolean = false
@CommandLine.Option( @CommandLine.Option(
names = ["-u", "--update"], names = ["-u", "--update"],
description = ["Update existing options by adding missing and removing non-existent options."], description = ["Update existing options by adding missing and removing non-existent options."],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var update: Boolean = false private var update: Boolean = false
override fun run() = try { override fun run() =
try {
PatchBundleLoader.Jar(*patchBundles).let { patches -> PatchBundleLoader.Jar(*patchBundles).let { patches ->
val exists = filePath.exists() val exists = filePath.exists()
if (!exists || overwrite) { if (!exists || overwrite) {
if (exists && update) patches.setOptions(filePath) if (exists && update) patches.setOptions(filePath)
Options.serialize(patches, prettyPrint = true).let(filePath::writeText) Options.serialize(patches, prettyPrint = true).let(filePath::writeText)
} else throw OptionsFileAlreadyExistsException() } else {
throw OptionsFileAlreadyExistsException()
}
} }
} catch (ex: OptionsFileAlreadyExistsException) { } catch (ex: OptionsFileAlreadyExistsException) {
logger.severe("Options file already exists, use --overwrite to override it") logger.severe("Options file already exists, use --overwrite to override it")

View File

@ -219,19 +219,23 @@ internal object PatchCommand : Runnable {
override fun run() { override fun run() {
// region Setup // region Setup
val outputFilePath = outputFilePath ?: File("").absoluteFile.resolve( val outputFilePath =
outputFilePath ?: File("").absoluteFile.resolve(
"${apk.nameWithoutExtension}-patched.${apk.extension}", "${apk.nameWithoutExtension}-patched.${apk.extension}",
) )
val resourceCachePath = resourceCachePath ?: outputFilePath.parentFile.resolve( val resourceCachePath =
resourceCachePath ?: outputFilePath.parentFile.resolve(
"${outputFilePath.nameWithoutExtension}-resource-cache", "${outputFilePath.nameWithoutExtension}-resource-cache",
) )
val optionsFile = optionsFile ?: outputFilePath.parentFile.resolve( val optionsFile =
optionsFile ?: outputFilePath.parentFile.resolve(
"${outputFilePath.nameWithoutExtension}-options.json", "${outputFilePath.nameWithoutExtension}-options.json",
) )
val keystoreFilePath = keystoreFilePath ?: outputFilePath.parentFile val keystoreFilePath =
keystoreFilePath ?: outputFilePath.parentFile
.resolve("${outputFilePath.nameWithoutExtension}.keystore") .resolve("${outputFilePath.nameWithoutExtension}.keystore")
// endregion // endregion
@ -265,7 +269,8 @@ internal object PatchCommand : Runnable {
true, true,
), ),
).use { patcher -> ).use { patcher ->
val filteredPatches = patcher.filterPatchSelection(patches).also { patches -> val filteredPatches =
patcher.filterPatchSelection(patches).also { patches ->
logger.info("Setting patch options") logger.info("Setting patch options")
if (optionsFile.exists()) { if (optionsFile.exists()) {
@ -277,7 +282,8 @@ internal object PatchCommand : Runnable {
// region Patch // region Patch
val patcherResult = patcher.apply { val patcherResult =
patcher.apply {
acceptIntegrations(integrations) acceptIntegrations(integrations)
acceptPatches(filteredPatches.toList()) acceptPatches(filteredPatches.toList())
@ -298,7 +304,8 @@ internal object PatchCommand : Runnable {
// region Save // region Save
val alignedFile = resourceCachePath.resolve(apk.name).apply { val alignedFile =
resourceCachePath.resolve(apk.name).apply {
ApkUtils.copyAligned(apk, this, patcherResult) ApkUtils.copyAligned(apk, this, patcherResult)
} }
@ -341,7 +348,8 @@ internal object PatchCommand : Runnable {
* @param patches The patches to filter. * @param patches The patches to filter.
* @return The filtered patches. * @return The filtered patches.
*/ */
private fun Patcher.filterPatchSelection(patches: PatchSet): PatchSet = buildSet { private fun Patcher.filterPatchSelection(patches: PatchSet): PatchSet =
buildSet {
val packageName = context.packageMetadata.packageName val packageName = context.packageMetadata.packageName
val packageVersion = context.packageMetadata.packageVersion val packageVersion = context.packageMetadata.packageVersion
@ -354,7 +362,8 @@ internal object PatchCommand : Runnable {
// Make sure the patch is compatible with the supplied APK files package name and version. // Make sure the patch is compatible with the supplied APK files package name and version.
patch.compatiblePackages?.let { packages -> patch.compatiblePackages?.let { packages ->
packages.singleOrNull { it.name == packageName }?.let { `package` -> packages.singleOrNull { it.name == packageName }?.let { `package` ->
val matchesVersion = force || `package`.versions?.let { val matchesVersion =
force || `package`.versions?.let {
it.any { version -> version == packageVersion } it.any { version -> version == packageVersion }
} ?: true } ?: true
@ -391,7 +400,8 @@ internal object PatchCommand : Runnable {
} }
private fun purge(resourceCachePath: File) { private fun purge(resourceCachePath: File) {
val result = if (resourceCachePath.deleteRecursively()) { val result =
if (resourceCachePath.deleteRecursively()) {
"Purged resource cache directory" "Purged resource cache directory"
} else { } else {
"Failed to purge resource cache directory" "Failed to purge resource cache directory"

View File

@ -32,7 +32,8 @@ internal object InstallCommand : Runnable {
private var packageName: String? = null private var packageName: String? = null
override fun run() { override fun run() {
fun install(deviceSerial: String? = null) = try { fun install(deviceSerial: String? = null) =
try {
AdbManager.getAdbManager(deviceSerial, packageName != null).install(AdbManager.Apk(apk, packageName)) AdbManager.getAdbManager(deviceSerial, packageName != null).install(AdbManager.Apk(apk, packageName))
} catch (e: AdbManager.DeviceNotFoundException) { } catch (e: AdbManager.DeviceNotFoundException) {
logger.severe(e.toString()) logger.severe(e.toString())

View File

@ -5,36 +5,36 @@ import picocli.CommandLine.*
import picocli.CommandLine.Help.Visibility.ALWAYS import picocli.CommandLine.Help.Visibility.ALWAYS
import java.util.logging.Logger import java.util.logging.Logger
@Command( @Command(
name = "uninstall", 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 { internal object UninstallCommand : Runnable {
private val logger = Logger.getLogger(UninstallCommand::class.java.name) private val logger = Logger.getLogger(UninstallCommand::class.java.name)
@Parameters( @Parameters(
description = ["ADB device serials. If not supplied, the first connected device will be used."], description = ["ADB device serials. If not supplied, the first connected device will be used."],
arity = "0..*" arity = "0..*",
) )
private var deviceSerials: Array<String>? = null private var deviceSerials: Array<String>? = null
@Option( @Option(
names = ["-p", "--package-name"], names = ["-p", "--package-name"],
description = ["Package name of the app to uninstall"], description = ["Package name of the app to uninstall"],
required = true required = true,
) )
private lateinit var packageName: String private lateinit var packageName: String
@Option( @Option(
names = ["-u", "--unmount"], names = ["-u", "--unmount"],
description = ["Uninstall by unmounting the patched APK file"], description = ["Uninstall by unmounting the patched APK file"],
showDefaultValue = ALWAYS showDefaultValue = ALWAYS,
) )
private var unmount: Boolean = false private var unmount: Boolean = false
override fun run() { override fun run() {
fun uninstall(deviceSerial: String? = null) = try { fun uninstall(deviceSerial: String? = null) =
try {
AdbManager.getAdbManager(deviceSerial, unmount).uninstall(packageName) AdbManager.getAdbManager(deviceSerial, unmount).uninstall(packageName)
} catch (e: AdbManager.DeviceNotFoundException) { } catch (e: AdbManager.DeviceNotFoundException) {
logger.severe(e.toString()) logger.severe(e.toString())