Skip to content

Commit

Permalink
Combine test annotations, reformat all code
Browse files Browse the repository at this point in the history
  • Loading branch information
ajalt committed Feb 9, 2025
1 parent 8f3668b commit 38c6e81
Show file tree
Hide file tree
Showing 45 changed files with 471 additions and 792 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
package com.github.ajalt.clikt.output

import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.core.UsageError
import com.github.ajalt.clikt.core.terminal
import com.github.ajalt.clikt.output.HelpFormatter.ParameterHelp
import com.github.ajalt.mordant.markdown.Markdown
import com.github.ajalt.mordant.rendering.Theme
import com.github.ajalt.mordant.rendering.Whitespace
import com.github.ajalt.mordant.rendering.Widget
import com.github.ajalt.mordant.table.verticalLayout
import com.github.ajalt.mordant.widgets.Text
import com.github.ajalt.mordant.widgets.definitionList
import com.github.ajalt.mordant.widgets.withPadding

/**
* A [HelpFormatter] that uses Mordant to render its output as GitHub Flavored Markdown.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.github.ajalt.clikt.command

import com.github.ajalt.clikt.core.*
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.installMordant
import com.github.ajalt.clikt.parsers.CommandLineParser
import com.github.ajalt.clikt.testing.CliktCommandTestResult
import com.github.ajalt.clikt.testing.test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ abstract class CoreChainedCliktCommand<T>(
}



/**
* Parse the command line and print helpful output if any errors occur.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ fun <T : BaseCliktCommand<*>> T.completionOption(
help: String = "",
hidden: Boolean = false,
): T = apply {
registerOption(option(
*names, help = help, hidden = hidden, eager = true,
metavar = choices.joinToString("|", prefix = "(", postfix = ")")
).validate {
throw PrintCompletionMessage(generateCompletionForCommand(context.command, it))
})
registerOption(
option(
*names, help = help, hidden = hidden, eager = true,
metavar = choices.joinToString("|", prefix = "(", postfix = ")")
).validate {
throw PrintCompletionMessage(generateCompletionForCommand(context.command, it))
})
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.github.ajalt.clikt.completion

import com.github.ajalt.clikt.core.BaseCliktCommand
import com.github.ajalt.clikt.core.PrintCompletionMessage

object CompletionGenerator {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,109 +11,110 @@ internal object FishCompletionGenerator {
}


private fun generateFishCompletionForCommand(command: BaseCliktCommand<*>): String = buildString {
val parentCommandName = command.currentContext.parentNames().lastOrNull()
val rootCommandName = command.currentContext.commandNameWithParents().first()
val isTopLevel = parentCommandName == null
val commandName = command.commandName
val options = command._options.filterNot { it.hidden }
val arguments = command._arguments
val subcommands = command._subcommands
val hasSubcommands = subcommands.isNotEmpty()
val subcommandsVarName =
command.currentContext.commandNameWithParents().subcommandsVarName()
val parentSubcommandsVarName = when {
isTopLevel -> subcommandsVarName
else -> command.currentContext.parentNames().subcommandsVarName()
}
private fun generateFishCompletionForCommand(command: BaseCliktCommand<*>): String =
buildString {
val parentCommandName = command.currentContext.parentNames().lastOrNull()
val rootCommandName = command.currentContext.commandNameWithParents().first()
val isTopLevel = parentCommandName == null
val commandName = command.commandName
val options = command._options.filterNot { it.hidden }
val arguments = command._arguments
val subcommands = command._subcommands
val hasSubcommands = subcommands.isNotEmpty()
val subcommandsVarName =
command.currentContext.commandNameWithParents().subcommandsVarName()
val parentSubcommandsVarName = when {
isTopLevel -> subcommandsVarName
else -> command.currentContext.parentNames().subcommandsVarName()
}

if (isTopLevel) {
appendLine(
"""
if (isTopLevel) {
appendLine(
"""
|# Command completion for $commandName
|# Generated by Clikt
""".trimMargin()
)
}
)
}

if (hasSubcommands || !isTopLevel) {
appendLine("\n\n### Setup for $commandName")
}
if (hasSubcommands || !isTopLevel) {
appendLine("\n\n### Setup for $commandName")
}

if (hasSubcommands) {
val subcommandsStr = subcommands.joinToString(" ") { it.commandName }
appendLine("set -l $subcommandsVarName '$subcommandsStr'")
}
if (hasSubcommands) {
val subcommandsStr = subcommands.joinToString(" ") { it.commandName }
appendLine("set -l $subcommandsVarName '$subcommandsStr'")
}

if (!isTopLevel) {
append("complete -c $rootCommandName -f ")
if (!isTopLevel) {
append("complete -c $rootCommandName -f ")

if (rootCommandName == parentCommandName) {
append("-n __fish_use_subcommand ")
} else {
append("-n \"__fish_seen_subcommand_from $parentCommandName; and not __fish_seen_subcommand_from \$$parentSubcommandsVarName\" ")
}
if (rootCommandName == parentCommandName) {
append("-n __fish_use_subcommand ")
} else {
append("-n \"__fish_seen_subcommand_from $parentCommandName; and not __fish_seen_subcommand_from \$$parentSubcommandsVarName\" ")
}

append("-a $commandName ")

append("-a $commandName ")
val help = command.help(command.currentContext).replace("'", "\\'")
if (help.isNotBlank()) {
append("-d '${help}'")
}

val help = command.help(command.currentContext).replace("'", "\\'")
if (help.isNotBlank()) {
append("-d '${help}'")
appendLine()
}

appendLine()
}
if (options.any { o -> o.allNames.any { it.isValidFishCompletionOption } }) {
appendLine("\n## Options for $commandName")
}

if (options.any { o -> o.allNames.any { it.isValidFishCompletionOption } }) {
appendLine("\n## Options for $commandName")
}
for (option in options) {
val names = option.allNames.filter { it.isValidFishCompletionOption }
if (names.isEmpty()) {
continue
}

for (option in options) {
val names = option.allNames.filter { it.isValidFishCompletionOption }
if (names.isEmpty()) {
continue
}
appendCompleteCall(rootCommandName, isTopLevel, hasSubcommands, commandName)

appendCompleteCall(rootCommandName, isTopLevel, hasSubcommands, commandName)
for (name in names) {
append(' ')
when {
name.startsWith("--") -> append("-l ")
name.length == 2 -> append("-s ")
else -> append("-o ")
}
append(name.trimStart('-'))
}

for (name in names) {
append(' ')
when {
name.startsWith("--") -> append("-l ")
name.length == 2 -> append("-s ")
else -> append("-o ")
if (option.nvalues.first > 0) {
append(" -r")
}
append(name.trimStart('-'))
}

if (option.nvalues.first > 0) {
append(" -r")
appendParamCompletion(option.completionCandidates)
appendHelp(option.optionHelp(command.currentContext))
appendLine()
}

appendParamCompletion(option.completionCandidates)
appendHelp(option.optionHelp(command.currentContext))
appendLine()
}

if (arguments.isNotEmpty()) {
appendLine("\n## Arguments for $commandName")
}
if (arguments.isNotEmpty()) {
appendLine("\n## Arguments for $commandName")
}

for (argument in arguments) {
appendCompleteCall(rootCommandName, isTopLevel, hasSubcommands, commandName)
appendParamCompletion(argument.completionCandidates)
appendHelp(argument.getArgumentHelp(command.currentContext))
appendLine()
}
for (argument in arguments) {
appendCompleteCall(rootCommandName, isTopLevel, hasSubcommands, commandName)
appendParamCompletion(argument.completionCandidates)
appendHelp(argument.getArgumentHelp(command.currentContext))
appendLine()
}

for (subcommand in subcommands) {
append(
generateFishCompletionForCommand(
command = subcommand
for (subcommand in subcommands) {
append(
generateFishCompletionForCommand(
command = subcommand
)
)
)
}
}
}

private fun StringBuilder.appendCompleteCall(
rootCommandName: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ class CoOccurringOptionGroup<GroupT : OptionGroup, OutT> internal constructor(

override fun getValue(thisRef: BaseCliktCommand<*>, property: KProperty<*>): OutT = value

override fun finalize(context: Context, invocationsByOption: Map<Option, List<OptionInvocation>>) {
override fun finalize(
context: Context,
invocationsByOption: Map<Option, List<OptionInvocation>>,
) {
occurred = invocationsByOption.isNotEmpty() || group.options.any {
it.hasEnvvarOrSourcedValue(context, invocationsByOption[it] ?: emptyList())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ open class OptionGroup(
options += option
}

override fun finalize(context: Context, invocationsByOption: Map<Option, List<OptionInvocation>>) {
override fun finalize(
context: Context,
invocationsByOption: Map<Option, List<OptionInvocation>>,
) {
finalizeOptions(context, options, invocationsByOption)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,10 @@ inline fun <OutT> OptionWithValues<Boolean, Boolean, Boolean>.convert(
* @param clamp If `true`, the counted value will be clamped to the [limit] if it is exceeded. If
* `false`, an error will be shown isntead of clamping.
*/
fun RawOption.counted(limit: Int = Int.MAX_VALUE, clamp: Boolean = true): OptionWithValues<Int, Int, Int> {
fun RawOption.counted(
limit: Int = Int.MAX_VALUE,
clamp: Boolean = true,
): OptionWithValues<Int, Int, Int> {
return int().transformValues(0..0) { it.lastOrNull() ?: 1 }.transformAll {
val s = it.sum()
if (!clamp && s > limit) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ fun <EachT, ValueT> NullableOption<EachT, ValueT>.multiple(
* ```
*/
fun <T, EachT, ValueT> OptionWithValues<List<T>, EachT, ValueT>.unique()
: OptionWithValues<Set<T>, EachT, ValueT> {
: OptionWithValues<Set<T>, EachT, ValueT> {
return copy(transformValue, transformEach, { transformAll(it).toSet() }, defaultValidator())
}

Expand All @@ -155,7 +155,7 @@ fun <T, EachT, ValueT> OptionWithValues<List<T>, EachT, ValueT>.unique()
* If the same key appears more than once, the last one will be added to the map.
*/
fun <A, B, EachT, ValueT> OptionWithValues<List<Pair<A, B>>, EachT, ValueT>.toMap()
: OptionWithValues<Map<A, B>, EachT, ValueT> {
: OptionWithValues<Map<A, B>, EachT, ValueT> {
return copy(transformValue, transformEach, { transformAll(it).toMap() }, defaultValidator())
}

Expand Down Expand Up @@ -188,7 +188,7 @@ inline fun <K, V> RawOption.associate(
inline fun <K> RawOption.associateBy(
delimiter: String = "=",
crossinline keySelector: (String) -> K,
): OptionWithValues<Map<K, String>, Pair<K, String>, Pair<K, String>> {
): OptionWithValues<Map<K, String>, Pair<K, String>, Pair<K, String>> {
return associate(delimiter) { keySelector(it.first) to it.second }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,13 @@ fun <EachT, ValueT> NullableOption<ValueT, ValueT>.transformValues(
transformAll = defaultAllProcessor(),
validator = defaultValidator(),
metavarGetter = when (nvalues) {
0..0 -> { { null } }
else -> { metavarGetter }
0..0 -> {
{ null }
}

else -> {
metavarGetter
}
},
nvalues = nvalues
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ package com.github.ajalt.clikt.core
* @see Context.callOnClose
* @see Context.registerCloseable
*/
fun <T: AutoCloseable> Context.registerJvmCloseable(closeable: T): T {
fun <T : AutoCloseable> Context.registerJvmCloseable(closeable: T): T {
callOnClose { closeable.close() }
return closeable
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ import kotlin.test.Test


class ChainedCliktCommandTest {
@Test
@JsName("chained_run")
@[Test JsName("chained_run")]
fun `chained run`() = runTest {
class C : ChainedCliktCommand<List<Int>>() {
override val allowMultipleSubcommands: Boolean = true
Expand All @@ -37,8 +36,7 @@ class ChainedCliktCommandTest {
}


@Test
@JsName("chained_command_context")
@[Test JsName("chained_command_context")]
fun `chained command context`() {
class C : ChainedCliktCommand<Int>() {
val arg by argument().int()
Expand All @@ -52,8 +50,7 @@ class ChainedCliktCommandTest {
}


@Test
@JsName("chained_command_test")
@[Test JsName("chained_command_test")]
fun `chained command test`() {
class C : ChainedCliktCommand<Int>() {
val arg by argument().int()
Expand Down
Loading

0 comments on commit 38c6e81

Please sign in to comment.