Skip to content

Commit

Permalink
Also strip plural "Commands" when inferring command names (#490)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
sschuberth committed Feb 20, 2024
1 parent 5cb5ab1 commit 95ce4f0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 95ce4f0

Please sign in to comment.