Multiplatform command line interface parsing for Kotlin
npx @tessl/cli install tessl/maven-com-github-ajalt--clikt-jvm@4.4.0Clikt is a multiplatform Kotlin library that makes writing command line interfaces simple and intuitive. It provides a type-safe, declarative DSL for parsing command line arguments, with support for subcommands, parameter groups, shell completion, and rich terminal output.
implementation("com.github.ajalt.clikt:clikt:4.4.0")<dependency><groupId>com.github.ajalt.clikt</groupId><artifactId>clikt</artifactId><version>4.4.0</version></dependency>import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.*
import com.github.ajalt.clikt.parameters.arguments.*For completion and advanced features:
import com.github.ajalt.clikt.completion.*
import com.github.ajalt.clikt.parameters.groups.*
import com.github.ajalt.clikt.sources.*import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import com.github.ajalt.clikt.parameters.arguments.argument
class Hello : CliktCommand() {
private val greeting by option("-g", "--greeting", help="Greeting to use").required()
private val name by argument(help="Name of person to greet")
override fun run() {
echo("$greeting $name!")
}
}
fun main() = Hello().main()Clikt is built around several key components:
The library follows a builder pattern with method chaining, making it easy to compose complex parameter configurations while maintaining type safety and readability.
Foundation command classes and execution framework for building CLI applications. The CliktCommand class provides the base functionality for parameter registration, parsing, and execution.
abstract class CliktCommand(
help: String = "",
epilog: String = "",
name: String? = null,
invokeWithoutSubcommand: Boolean = false,
printHelpOnEmptyArgs: Boolean = false,
helpTags: Map<String, String> = emptyMap(),
allowMultipleSubcommands: Boolean = false,
treatUnknownOptionsAsArgs: Boolean = false,
hidden: Boolean = false
) {
abstract fun run()
fun main(argv: List<String>)
fun echo(message: Any?, trailingNewline: Boolean = true, err: Boolean = false)
}Declarative option parsing with type conversion, validation, and default values. Options are declared as delegated properties with a fluent API for configuration.
fun CliktCommand.option(
vararg names: String,
help: String = "",
metavar: String? = null,
hidden: Boolean = false,
helpTags: Map<String, String> = emptyMap(),
envvar: String? = null,
valueSourceKey: String? = null,
completionCandidates: CompletionCandidates? = null
): RawOption
fun <T : Any> RawOption.convert(
metavar: String,
conversion: ValueConverter<String, T>
): NullableOption<T, T>Positional argument parsing with type conversion and validation. Arguments are processed in order and support optional, multiple, and paired value patterns.
fun CliktCommand.argument(
name: String = "",
help: String = "",
helpTags: Map<String, String> = emptyMap(),
completionCandidates: CompletionCandidates? = null
): RawArgument
fun <T : Any> RawArgument.convert(
conversion: ArgValueConverter<String, T>
): ProcessedArgument<T, T>Built-in type converters for common data types including numeric types, enums, choices, and platform-specific types like files and paths.
fun RawOption.int(): NullableOption<Int, Int>
fun RawOption.string(): NullableOption<String, String>
fun RawOption.boolean(): NullableOption<Boolean, Boolean>
fun <T : Enum<T>> RawOption.enum(): NullableOption<T, T>
fun <T : Any> RawOption.choice(choices: Map<String, T>): NullableOption<T, T>Organize related parameters into groups with mutual exclusion, co-occurrence, and choice-based selection patterns.
open class OptionGroup(name: String? = null, help: String? = null)
fun ParameterHolder.mutuallyExclusiveOptions(
vararg options: OptionDelegate<*>
): MutuallyExclusiveOptions
fun <T : Any> CliktCommand.groupChoice(
vararg choices: Pair<String, T>
): ParameterGroupDelegate<T?>Generate shell completion scripts for Bash and Fish, with support for dynamic completion candidates including files, hostnames, and custom completions.
sealed class CompletionCandidates {
object None : CompletionCandidates()
object Path : CompletionCandidates()
object Hostname : CompletionCandidates()
object Username : CompletionCandidates()
data class Fixed(val candidates: Set<String>) : CompletionCandidates()
data class Custom(val generator: (ShellType) -> String?) : CompletionCandidates()
}
interface CompletionGenerator {
fun generateScript(commandName: String, command: CliktCommand): String
}Load parameter values from external sources including environment variables, configuration files, and custom value providers with priority chaining.
interface ValueSource {
data class Invocation(val values: List<String>)
fun getValues(context: Context, option: Option): List<Invocation>
}
class MapValueSource(private val map: Map<String, String>) : ValueSource
class ChainedValueSource(private val sources: List<ValueSource>) : ValueSourceComprehensive exception hierarchy for different types of CLI errors and command execution failures. All exceptions provide structured error information for proper error handling and user feedback.
open class CliktError(
message: String?,
cause: Exception? = null,
val statusCode: Int = 1,
val printError: Boolean = true
) : RuntimeException(message, cause)
open class UsageError(
message: String? = null,
val paramName: String? = null,
statusCode: Int = 1
) : CliktError(message, null, statusCode)
class BadParameterValue(
message: String,
paramName: String? = null,
statusCode: Int = 1
) : UsageError(message, paramName, statusCode)Test command execution with controlled input/output, environment variables, and terminal settings for comprehensive CLI testing.
data class CliktCommandTestResult(
val stdout: String,
val stderr: String,
val output: String,
val statusCode: Int
)
fun CliktCommand.test(
argv: String,
stdin: String = "",
envvars: Map<String, String> = emptyMap(),
includeSystemEnvvars: Boolean = false,
ansiLevel: AnsiLevel = AnsiLevel.NONE,
width: Int = 79,
height: Int = 24
): CliktCommandTestResultabstract class CliktCommand(/* constructor parameters */)
class Context(
val parent: Context?,
val command: CliktCommand,
val allowInterspersedArgs: Boolean = true,
val allowGroupedShortOptions: Boolean = true,
val autoEnvvarPrefix: String? = null,
val printExtraMessages: Boolean = true,
val helpOptionNames: Set<String> = setOf("-h", "--help"),
val terminal: Terminal,
val valueSource: ValueSource? = null,
val localization: Localization = defaultLocalization,
val obj: Any? = null
)
interface Option
interface Argument
interface ParameterGrouptypealias ValueConverter<InT, ValueT> = OptionTransformContext.(InT) -> ValueT
typealias ArgValueConverter<InT, ValueT> = ArgumentTransformContext.(InT) -> ValueT
typealias OptionValidator<T> = OptionTransformContext.(T) -> Unit
typealias ArgValidator<T> = ArgumentTransformContext.(T) -> Unit