or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

arguments.mdconfiguration-sources.mdcore-commands.mdexceptions.mdindex.mdoptions.mdparameter-groups.mdparameter-types.mdshell-completion.mdtesting-utilities.md
tile.json

tessl/maven-com-github-ajalt--clikt-jvm

Multiplatform command line interface parsing for Kotlin

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.github.ajalt.clikt/clikt-jvm@4.4.x

To install, run

npx @tessl/cli install tessl/maven-com-github-ajalt--clikt-jvm@4.4.0

index.mddocs/

Clikt

Clikt 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.

Package Information

  • Package Name: clikt-jvm
  • Package Type: maven
  • Language: Kotlin
  • Installation:
    • Gradle: implementation("com.github.ajalt.clikt:clikt:4.4.0")
    • Maven: <dependency><groupId>com.github.ajalt.clikt</groupId><artifactId>clikt</artifactId><version>4.4.0</version></dependency>

Core Imports

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.*

Basic Usage

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()

Architecture

Clikt is built around several key components:

  • CliktCommand: Base class for all CLI commands with parameter registration and execution lifecycle
  • Parameter System: Type-safe parameter parsing with delegated properties for options and arguments
  • Context Management: Hierarchical context system for configuration, error handling, and state management
  • Transformation Pipeline: Composable parameter processing with conversion, validation, and default value handling
  • Multi-platform Support: Common API with platform-specific implementations for file handling and terminal operations

The library follows a builder pattern with method chaining, making it easy to compose complex parameter configurations while maintaining type safety and readability.

Capabilities

Core Commands

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)
}

Core Commands

Options

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>

Options

Arguments

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>

Arguments

Parameter Types

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>

Parameter Types

Parameter Groups

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?>

Parameter Groups

Shell Completion

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
}

Shell Completion

Configuration Sources

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>) : ValueSource

Configuration Sources

Error Handling

Comprehensive 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)

Error Handling

Testing Utilities

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
): CliktCommandTestResult

Testing Utilities

Types

Core Types

abstract 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 ParameterGroup

Type Aliases

typealias 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