Skip to content

Commit

Permalink
Reformat based on ktlint 3 plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
martinvisser committed Oct 23, 2023
1 parent 0a247ea commit 5fb563d
Show file tree
Hide file tree
Showing 28 changed files with 191 additions and 138 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ private const val SHEBANG = "#!/bin/zsh"

@ApplicationScoped
class ZshAutocompletionGenerator(private val template: ZshAutocompletionTemplate) {

/**
* This function generates the full ZSH autocompletion script for the command that's provided and all subcommands
*/
Expand Down Expand Up @@ -40,14 +39,16 @@ class ZshAutocompletionGenerator(private val template: ZshAutocompletionTemplate
): List<String> {
val functionName = "${functionPrefix}_${commandLine.commandName}"

val subcommands = commandLine.subcommands.values
.filterNot { it.commandSpec.usageMessage().hidden() }
.sortedBy { it.commandName }
val subcommands =
commandLine.subcommands.values
.filterNot { it.commandSpec.usageMessage().hidden() }
.sortedBy { it.commandName }

val options = commandLine.commandSpec
.options()
.filterNot { it.hidden() }
.sortedBy { it.shortestName() }
val options =
commandLine.commandSpec
.options()
.filterNot { it.hidden() }
.sortedBy { it.shortestName() }

val positionalParameters = commandLine.commandSpec.positionalParameters()

Expand All @@ -56,9 +57,10 @@ class ZshAutocompletionGenerator(private val template: ZshAutocompletionTemplate
return if (shouldGenerateFunction) {
val function =
template.applyForCommand(functionName, subcommands, positionalParameters, options, isRootFunction)
val subcommandFunctions = subcommands.flatMap {
generateFunctionForCommandsRecursively(it, functionName, false)
}
val subcommandFunctions =
subcommands.flatMap {
generateFunctionForCommandsRecursively(it, functionName, false)
}
listOf(function) + subcommandFunctions
} else {
listOf()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ private const val AUTOCOMPLETION_FUNCTION_PREFIX = "function:"

@ApplicationScoped
class ZshAutocompletionTemplate {

/**
* Generates a ZSH function for a command containing either subcommands
* or positional parameters and possibly options(/flags).
Expand All @@ -22,11 +21,12 @@ class ZshAutocompletionTemplate {
options: List<OptionSpec>,
isRootFunction: Boolean,
): String {
val commandOrParameterSpecActionPairs = when {
subcommands.isNotEmpty() -> generateSubcommandSpecActionPairs(subcommands, functionName)
positionalParameters.isNotEmpty() -> generatePositionalParameterSpecActionPairs(positionalParameters)
else -> emptyList()
}
val commandOrParameterSpecActionPairs =
when {
subcommands.isNotEmpty() -> generateSubcommandSpecActionPairs(subcommands, functionName)
positionalParameters.isNotEmpty() -> generatePositionalParameterSpecActionPairs(positionalParameters)
else -> emptyList()
}

val allSpecActionPairs = commandOrParameterSpecActionPairs + generateOptionSpecActionPairs(options)

Expand Down Expand Up @@ -54,36 +54,40 @@ function $functionName() {
subcommands: List<CommandLine>,
parentFunctionName: String,
): List<ArgumentSpecActionPair> {
val overviewValues = subcommands.joinToString(" ") {
val description = it.commandSpec.usageMessage().description().firstOrNull() ?: ""
"'${it.commandName}[$description]'"
}
val overviewValues =
subcommands.joinToString(" ") {
val description = it.commandSpec.usageMessage().description().firstOrNull() ?: ""
"'${it.commandName}[$description]'"
}

val overviewTitle = parentFunctionName.replace("_", " ")
val subcommandOverview = ArgumentSpecActionPair(
"\"1:$overviewTitle subcommands:->subcommands_overview\"",
"subcommands_overview) _values \"autocompletion candidates\" $overviewValues;;",
)

val subcommandActions = ArgumentSpecActionPair(
"\"*::arg:->call_subcommand\"",
"call_subcommand) function=\"${parentFunctionName}_${'$'}{line[1]}\"; " +
"_call_function_if_exists \"${'$'}function\";;",
)
val subcommandOverview =
ArgumentSpecActionPair(
"\"1:$overviewTitle subcommands:->subcommands_overview\"",
"subcommands_overview) _values \"autocompletion candidates\" $overviewValues;;",
)

val subcommandActions =
ArgumentSpecActionPair(
"\"*::arg:->call_subcommand\"",
"call_subcommand) function=\"${parentFunctionName}_${'$'}{line[1]}\"; " +
"_call_function_if_exists \"${'$'}function\";;",
)

return listOf(subcommandOverview, subcommandActions)
}

private fun generateOptionSpecActionPairs(options: List<OptionSpec>) =
options.withIndex().map {
val orderedOptionNames = it.value.names().sortedBy { name -> name.length }
val namesDefinition = if (orderedOptionNames.size == 1) {
it.value.names()[0]
} else {
val optionNamesSpaceSeparated = orderedOptionNames.joinToString(" ")
val optionNamesCommaSeparated = orderedOptionNames.joinToString(",")
"($optionNamesSpaceSeparated)'{$optionNamesCommaSeparated}'"
}
val namesDefinition =
if (orderedOptionNames.size == 1) {
it.value.names()[0]
} else {
val optionNamesSpaceSeparated = orderedOptionNames.joinToString(" ")
val optionNamesCommaSeparated = orderedOptionNames.joinToString(",")
"($optionNamesSpaceSeparated)'{$optionNamesCommaSeparated}'"
}

val description = it.value.description().joinToString("")
val isFlagOption = it.value.type() == java.lang.Boolean.TYPE || it.value.type() == Boolean::class.java
Expand Down Expand Up @@ -153,6 +157,8 @@ function $functionName() {

sealed interface AutoCompleteAction
data object NoAction : AutoCompleteAction

data class FunctionCallAction(val functionName: String) : AutoCompleteAction

data class StaticValuesAction(val staticValues: String) : AutoCompleteAction
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ class ConfigureCommand(
name = "autocomplete",
description = ["Prints the command to install autocomplete. Supported shells are: zsh"],
)
fun printInstallAutocompleteCommand(@Parameters(description = ["shells"]) shell: String) {
fun printInstallAutocompleteCommand(
@Parameters(description = ["shells"]) shell: String,
) {
if (shell.lowercase() == "zsh") {
printConfigureZsh()
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ import picocli.CommandLine.Help.ColorScheme

@ApplicationScoped
class CommandLineConfiguration(private val pluginLoader: PluginLoader) {

@Produces
fun customCommandLine(factory: PicocliCommandLineFactory, retConsole: RetConsole): CommandLine {
val commandLine = factory.create()
.setExecutionExceptionHandler(ExceptionMessageHandler(retConsole))
.setExecutionStrategy { CommandLine.RunLast().execute(it) }
.setColorScheme(ColorScheme.Builder().ansi(AUTO).build())
fun customCommandLine(
factory: PicocliCommandLineFactory,
retConsole: RetConsole,
): CommandLine {
val commandLine =
factory.create()
.setExecutionExceptionHandler(ExceptionMessageHandler(retConsole))
.setExecutionStrategy { CommandLine.RunLast().execute(it) }
.setColorScheme(ColorScheme.Builder().ansi(AUTO).build())

pluginLoader.getPluginCommands(commandLine).forEach {
commandLine.addSubcommand(it.name, it.commandSpec)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import org.eclipse.microprofile.config.inject.ConfigProperty

@ApplicationScoped
class EnvironmentManager {

@Produces
fun environment(@ConfigProperty(name = "ret.env", defaultValue = "CLI") retEnvironment: String): Environment =
fun environment(
@ConfigProperty(name = "ret.env", defaultValue = "CLI") retEnvironment: String,
): Environment =
runCatching {
Log.debug("ret.env value is $retEnvironment")
valueOf(retEnvironment)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@ import picocli.CommandLine.IExecutionExceptionHandler
import picocli.CommandLine.ParseResult

class ExceptionMessageHandler(private val retConsole: RetConsole) : IExecutionExceptionHandler {

override fun handleExecutionException(ex: Exception, commandLine: CommandLine, parseResult: ParseResult) =
if (ex is IllegalArgumentException) {
Log.warn("Input error occurred", ex)
ex.message?.let { retConsole.errorOut(it) }
retConsole.errorOut(commandLine.usageMessage)
commandLine.commandSpec.exitCodeOnInvalidInput()
} else {
ex.message?.let { retConsole.errorOut(it) }
Log.error("An error occurred", ex)
commandLine.commandSpec.exitCodeOnExecutionException()
}
override fun handleExecutionException(
ex: Exception,
commandLine: CommandLine,
parseResult: ParseResult,
) = if (ex is IllegalArgumentException) {
Log.warn("Input error occurred", ex)
ex.message?.let { retConsole.errorOut(it) }
retConsole.errorOut(commandLine.usageMessage)
commandLine.commandSpec.exitCodeOnInvalidInput()
} else {
ex.message?.let { retConsole.errorOut(it) }
Log.error("An error occurred", ex)
commandLine.commandSpec.exitCodeOnExecutionException()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import jakarta.enterprise.context.ApplicationScoped

@ApplicationScoped
class ExecutionContext(private val versionProperties: VersionProperties = VersionProperties()) {

private val gitContext = GitContext.create()

fun repositoryName() = gitContext?.repositoryName()

fun branchName() = gitContext?.branchName()

fun version() = versionProperties.getAppVersion()
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.storage.file.FileRepositoryBuilder

internal class GitContext internal constructor(private val repository: Repository) {

fun repositoryName(): String? {
val remoteOriginURL: String? = repository.config.getString("remote", "origin", "url")
return remoteOriginURL?.substringAfterLast("/")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ import kotlin.io.path.walk

@ApplicationScoped
class PluginExtensionLoader {

@OptIn(ExperimentalPathApi::class)
@Produces
@ApplicationScoped
fun plugins(osUtils: OsUtils, objectMapper: ObjectMapper): List<Plugin> =
fun plugins(
osUtils: OsUtils,
objectMapper: ObjectMapper,
): List<Plugin> =
osUtils.getRetPluginsDirectory().let { pluginPath ->
pluginPath.walk()
.map(Path::toFile)
Expand Down
23 changes: 13 additions & 10 deletions ret-cli/src/main/kotlin/io/rabobank/ret/plugins/PluginLoader.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ class PluginLoader(
private val executionContext: ExecutionContext,
private val environment: Environment,
) {

fun getPluginCommands(commandLine: CommandLine): List<PluginCommandEntry> =
plugins.flatMap { plugin ->
plugin.pluginDefinition.commands.map {
Expand All @@ -36,14 +35,15 @@ class PluginLoader(
commandLine: CommandLine,
plugin: Plugin,
): CommandSpec {
val commandSpec = CommandSpec.wrapWithoutInspection(
Runnable {
System.load(plugin.pluginLocation.pathString)
val retContext = createRetContext(commandLine.parseResult, topCommand)
val isolate = RetPlugin.createIsolate()
RetPlugin.invoke(isolate, objectMapper.writeValueAsString(retContext))
},
)
val commandSpec =
CommandSpec.wrapWithoutInspection(
Runnable {
System.load(plugin.pluginLocation.pathString)
val retContext = createRetContext(commandLine.parseResult, topCommand)
val isolate = RetPlugin.createIsolate()
RetPlugin.invoke(isolate, objectMapper.writeValueAsString(retContext))
},
)

commandSpec.usageMessage().description(command.description)
commandSpec.usageMessage().hidden(command.hidden)
Expand Down Expand Up @@ -75,7 +75,10 @@ class PluginLoader(
return commandSpec
}

private fun createRetContext(parseResult: ParseResult, topCommand: String): RetContext =
private fun createRetContext(
parseResult: ParseResult,
topCommand: String,
): RetContext =
RetContext(
parseResult.originalArgs().filter { it != topCommand },
environment.name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import org.junit.jupiter.api.Test
import picocli.CommandLine.Model.CommandSpec

internal class ConfigureCommandTest {

private lateinit var command: ConfigureCommand

private val retConsole = mockk<RetConsole>(relaxed = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ import org.eclipse.jgit.lib.Repository
import org.junit.jupiter.api.Test

internal class GitContextTest {

private val mockedGitRepository = mockk<Repository>()
private val gitContext = GitContext(mockedGitRepository)

@Test
fun getRepositoryFromRemoteURL() {
every { mockedGitRepository.config } returns mockk {
every {
getString("remote", "origin", "url")
} returns "[email protected]:v3/raboweb/Skunk%20Works/rabobank-engineering-tools"
}
every { mockedGitRepository.config } returns
mockk {
every {
getString("remote", "origin", "url")
} returns "[email protected]:v3/raboweb/Skunk%20Works/rabobank-engineering-tools"
}

val actualRepositoryName = gitContext.repositoryName()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,10 @@ class PluginLoaderTest {
}

private fun loadPlugin(file: String): Plugin {
val definition = this.javaClass.classLoader.getResourceAsStream("testdata/$file")!!
.bufferedReader()
.readText()
val definition =
this.javaClass.classLoader.getResourceAsStream("testdata/$file")!!
.bufferedReader()
.readText()

return objectMapper.readValue(definition, PluginDefinition::class.java).let {
Plugin(it, Path.of(it.libName))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ import picocli.CommandLine
import picocli.CommandLine.Model.CommandSpec

class ExceptionMessageHandlerTest {

private val retConsole = mockk<RetConsole>(relaxed = true)
private val exceptionHandler = ExceptionMessageHandler(retConsole)

@Test
fun `another exception results in exit code 1`() {
val ex = IllegalStateException("Boom!")
val commandLine = mockk<CommandLine> {
every { usageMessage } returns "Use this correctly"
every { commandSpec } returns CommandSpec.create()
}
val commandLine =
mockk<CommandLine> {
every { usageMessage } returns "Use this correctly"
every { commandSpec } returns CommandSpec.create()
}

val exitCode = exceptionHandler.handleExecutionException(ex, commandLine, mockk())

Expand All @@ -32,10 +32,11 @@ class ExceptionMessageHandlerTest {
@Test
fun `illegal argument results in exit code 2`() {
val ex = IllegalArgumentException("Boom!")
val commandLine = mockk<CommandLine> {
every { usageMessage } returns "Use this correctly"
every { commandSpec } returns CommandSpec.create()
}
val commandLine =
mockk<CommandLine> {
every { usageMessage } returns "Use this correctly"
every { commandSpec } returns CommandSpec.create()
}

val exitCode = exceptionHandler.handleExecutionException(ex, commandLine, mockk())

Expand Down
Loading

0 comments on commit 5fb563d

Please sign in to comment.