From 97a02924a3ccd3d16290d918df8568817cda4864 Mon Sep 17 00:00:00 2001 From: Sebastian Schuberth Date: Thu, 30 Apr 2020 18:01:52 +0200 Subject: [PATCH] Improve the logic to infer command names (#168) --- .../kotlin/com/github/ajalt/clikt/core/CliktCommand.kt | 7 ++++++- .../com/github/ajalt/clikt/core/CliktCommandTest.kt | 8 ++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/clikt/src/commonMain/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt b/clikt/src/commonMain/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt index dc551d0c8..a5448a3ee 100644 --- a/clikt/src/commonMain/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt +++ b/clikt/src/commonMain/kotlin/com/github/ajalt/clikt/core/CliktCommand.kt @@ -51,7 +51,7 @@ abstract class CliktCommand( private val autoCompleteEnvvar: String? = "", internal val allowMultipleSubcommands: Boolean = false ) : ParameterHolder { - val commandName = name ?: classSimpleName().toLowerCase() + val commandName = name ?: inferCommandName(classSimpleName()) val commandHelp = help val commandHelpEpilog = epilog internal var _subcommands: List = emptyList() @@ -371,3 +371,8 @@ fun T.context(block: Context.Builder.() -> Unit): T = apply { } private fun Any.classSimpleName(): String = this::class.simpleName.orEmpty().split("$").last() + +internal fun inferCommandName(name: String) = + name.removeSuffix("Command").replace(Regex("([a-z])([A-Z])")) { + "${it.groupValues[1]}-${it.groupValues[2]}" + }.toLowerCase() diff --git a/clikt/src/commonTest/kotlin/com/github/ajalt/clikt/core/CliktCommandTest.kt b/clikt/src/commonTest/kotlin/com/github/ajalt/clikt/core/CliktCommandTest.kt index c4c658bd0..8d36d086b 100644 --- a/clikt/src/commonTest/kotlin/com/github/ajalt/clikt/core/CliktCommandTest.kt +++ b/clikt/src/commonTest/kotlin/com/github/ajalt/clikt/core/CliktCommandTest.kt @@ -25,6 +25,14 @@ import kotlin.test.Test @Suppress("unused") class CliktCommandTest { + @Test + @JsName("commandNameInferred") + fun `command name inferred`() { + inferCommandName("ListAllValuesCommand") shouldBe "list-all-values" + inferCommandName("LGTMMeansLookingGoodToMe") shouldBe "lgtmmeans-looking-good-to-me" + inferCommandName("nothing-to-change") shouldBe "nothing-to-change" + } + @Test @JsName("invokeWithoutSubcommand_false") fun `invokeWithoutSubcommand=false`() {