From 95ce4f045e0ca74ad8ac9cfca80005783614630c Mon Sep 17 00:00:00 2001 From: Sebastian Schuberth Date: Tue, 20 Feb 2024 19:17:38 +0100 Subject: [PATCH] Also strip plural "Commands" when inferring command names (#490) Sometimes a `NoOpCliktCommand` is used to just group further sub-commands. Such a class may then be called e.g. "ListCommands" with plural "Commands". Support stripping that suffix for such cases. --- .../kotlin/com/github/ajalt/clikt/core/CliktCommand.kt | 10 ++++++++-- .../com/github/ajalt/clikt/core/CliktCommandTest.kt | 3 ++- 2 files changed, 10 insertions(+), 3 deletions(-) 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 e6a60d27..6bbcdd2b 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 @@ -539,8 +539,14 @@ private fun Any.classSimpleName(): String = this::class.simpleName.orEmpty().spl private fun CliktCommand.inferCommandName(): String { val name = classSimpleName() - if (name == "Command") return "command" - return name.removeSuffix("Command").replace(Regex("([a-z])([A-Z])")) { + + val suffixes = setOf("Command", "Commands") + if (name in suffixes) return name.lowercase() + + val nameWithoutSuffixes = suffixes.fold(name) { acc, s -> acc.removeSuffix(s) } + val lowerUpperRegex = Regex("([a-z])([A-Z])") + + return nameWithoutSuffixes.replace(lowerUpperRegex) { "${it.groupValues[1]}-${it.groupValues[2]}" }.lowercase() } 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 bbf4a7e7..cf3726f0 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 @@ -6,7 +6,6 @@ import com.github.ajalt.clikt.parameters.groups.OptionGroup import com.github.ajalt.clikt.parameters.groups.cooccurring import com.github.ajalt.clikt.parameters.groups.mutuallyExclusiveOptions import com.github.ajalt.clikt.parameters.groups.provideDelegate -import com.github.ajalt.clikt.parameters.options.defaultLazy import com.github.ajalt.clikt.parameters.options.flag import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.required @@ -35,9 +34,11 @@ class CliktCommandTest { class ListAllValuesCommand : TestCommand() class LGTMMeansLookingGoodToMe : TestCommand() class `nothing-to-change` : TestCommand() + class ListCommands : NoOpCliktCommand() ListAllValuesCommand().commandName shouldBe "list-all-values" LGTMMeansLookingGoodToMe().commandName shouldBe "lgtmmeans-looking-good-to-me" `nothing-to-change`().commandName shouldBe "nothing-to-change" + ListCommands().commandName shouldBe "list" } @Test