Language Page

kcli for Kotlin

This page is assembled from markdown in ktools-kotlin. GitHub links point to the workspace repo and the relevant source files or directories.

5 markdown sections
QM-Code/ktools-kotlin primary repo
HTML static output

Karma CLI Parsing SDK

ktools-kotlin/kcli/README.md

kcli is the Kotlin command-line parsing SDK in the ktools ecosystem. It is designed around two common CLI shapes:

  • top-level options such as --verbose and --output
  • inline roots such as --trace-*, --config-*, and --build-*

The library gives you two explicit entrypoints:

  • parseOrExit(...) for normal executable startup
  • parseOrThrow(...) when the caller wants to intercept CliError

Documentation

Quick Start

import kcli.InlineParser
import kcli.Parser

val parser = Parser()
val build = InlineParser("--build")

build.setHandler("-profile", { _, value ->
    println("profile=$value")
}, "Set build profile.")

parser.addInlineParser(build)
parser.addAlias("-v", "--verbose")
parser.setHandler("--verbose", { _ ->
}, "Enable verbose logging.")

parser.parseOrExit(args)

Behavior Highlights

  • The full command line is validated before any registered handler runs.
  • parseOrExit() prints invalid CLI input to stderr as [error] [cli] ... and exits with code 2.
  • parseOrThrow() throws CliError.
  • Bare inline roots such as --build print inline help unless a root value handler is registered and a root value is supplied.
  • setHandler(..., ValueHandler, ...) registers a required-value option.
  • setOptionalValueHandler(...) registers an optional-value option.
  • Required values may consume a first token that begins with -.
  • Literal -- is rejected as an unknown option; it is not treated as an option terminator.

Build SDK

kbuild --build-latest

SDK output:

  • build/latest/sdk/classes

Build And Test

kbuild --build-latest
./build/latest/tests/run-tests

Build And Run Demos

# Builds the SDK plus demos listed in .kbuild.json build.defaults.demos.
kbuild --build-latest

# Explicit demo-only run (uses .kbuild.json build.demos when no args are passed).
kbuild --build-demos

Demo directories:

  • Bootstrap compile/import check: demo/bootstrap/
  • SDK demos: demo/sdk/{alpha,beta,gamma}
  • Executable demos: demo/exe/{core,omega}

Useful demo commands:

./demo/exe/core/build/latest/test
./demo/exe/core/build/latest/test --alpha
./demo/exe/core/build/latest/test --alpha-message "hello"
./demo/exe/core/build/latest/test --output stdout
./demo/exe/omega/build/latest/test --beta-workers 8
./demo/exe/omega/build/latest/test --newgamma-tag "prod"
./demo/exe/omega/build/latest/test --build

Repository Layout

  • Public API: src/kcli/Parser.kt
  • Parser internals: src/kcli/internal/
  • API and CLI coverage: tests/src/
  • Integration demos: demo/
  • Hand-written docs: docs/

Kcli Documentation

ktools-kotlin/kcli/docs/index.md

kcli is a compact Kotlin SDK for executable startup and command-line parsing. It is intentionally opinionated about normal CLI behavior:

  • parse first
  • fail early on invalid input
  • do not run handlers until the full command line validates
  • preserve the caller's effective argument list
  • support grouped inline roots such as --trace-* and --config-*

Start Here

Typical Flow

val parser = Parser()
val build = InlineParser("--build")

build.setHandler("-profile", { _, value ->
    println("profile=$value")
}, "Set build profile.")

parser.addInlineParser(build)
parser.addAlias("-v", "--verbose")
parser.setHandler("--verbose", { _ ->
}, "Enable verbose logging.")

parser.parseOrExit(args)

Core Concepts

Parser

  • Owns top-level handlers, aliases, inline parser registrations, and the single parse pass.

InlineParser

  • Defines one inline root namespace such as --alpha, --trace, or --build.

HandlerContext

  • Exposes the effective option, command, root, and value tokens seen by the handler after alias expansion.

CliError

  • Used by parseOrThrow() to surface invalid CLI input and handler failures.

Which Entry Point Should I Use?

Use parseOrExit() when:

  • you are in a normal executable main()
  • invalid CLI input should print a standardized error and exit with code 2
  • you do not need custom formatting or recovery

Use parseOrThrow() when:

  • you want to customize error formatting
  • you want custom exit codes
  • you want to intercept and test parse failures directly

Build And Explore

kbuild --help
kbuild --build-latest
./demo/exe/core/build/latest/test --alpha-message "hello"
./demo/exe/omega/build/latest/test --build

Working References

If you want to see complete, compiling examples, start with:

The public API contract lives in src/kcli/Parser.kt.

API Guide

ktools-kotlin/kcli/docs/api.md

This page summarizes the public types in src/kcli/Parser.kt.

Core Types

Type Purpose
Parser Owns aliases, top-level handlers, positional handling, and inline parser registration.
InlineParser Defines one inline root namespace such as --build plus its --build-* handlers.
HandlerContext Metadata delivered to flag, value, and positional handlers.
CliError Exception used by parseOrThrow() for invalid CLI input and handler failures.

HandlerContext

HandlerContext is passed to every handler.

Field Meaning
root Inline root name without leading dashes, such as build. Empty for top-level handlers and positional dispatch.
option Effective option token after alias expansion, such as --verbose or --build-profile. Empty for positional dispatch.
command Normalized command name without leading dashes. Empty for positional dispatch and inline root value handlers.
valueTokens Effective value tokens after alias expansion. Tokens from the shell are preserved verbatim; alias preset tokens are prepended.

CliError

parseOrThrow() throws CliError when:

  • the command line is invalid
  • a registered option handler throws
  • the positional handler throws

CliError.option returns the option token associated with the failure when one exists. For positional-handler failures and parser-global errors, it may be empty.

InlineParser

Construction

val parser = InlineParser("--build")

The root may be provided as either:

  • "build"
  • "--build"

Root Value Handler

parser.setRootValueHandler(handler)
parser.setRootValueHandler(handler, "<selector>", "Select build targets.")

The root value handler processes the bare root form, for example:

  • --build release
  • --config user.json

If the bare root is used without a value, kcli prints inline help for that root instead.

Inline Handlers

parser.setHandler("-flag", flagHandler, "Enable build flag.")
parser.setHandler("-profile", valueHandler, "Set build profile.")
parser.setOptionalValueHandler("-enable", optionalHandler, "Enable build mode.")

Inline handler options may be written in either form:

  • short inline form: -profile
  • fully-qualified form: --build-profile

Parser

Top-Level Handlers

parser.setHandler("--verbose", handleVerbose, "Enable verbose logging.")
parser.setHandler("--output", handleOutput, "Set output target.")
parser.setOptionalValueHandler("--color", handleColor, "Set or auto-detect color output.")

Top-level handler options may be written as either:

  • "verbose"
  • "--verbose"

Aliases

parser.addAlias("-v", "--verbose")
parser.addAlias("-c", "--config-load", "user-file")

Rules:

  • aliases use single-dash form such as -v
  • alias targets use double-dash form such as --verbose
  • preset tokens are prepended to the handler's effective valueTokens

Positional Handler

parser.setPositionalHandler(handlePositionals)

The positional handler receives remaining non-option tokens in HandlerContext.valueTokens.

Inline Parser Registration

parser.addInlineParser(buildParser)

Duplicate inline roots are rejected.

Parse Entry Points

parser.parseOrExit(argc, argv)
parser.parseOrThrow(argc, argv)

parser.parseOrExit(args)
parser.parseOrThrow(args)

parseOrExit()

  • reports invalid CLI input to stderr as [error] [cli] ...
  • exits with code 2

parseOrThrow()

  • throws CliError
  • does not run handlers until the full command line validates

Value Handler Registration

Use the registration form that matches the CLI contract you want:

  • setHandler(option, FlagHandler, description) for flag-style options
  • setHandler(option, ValueHandler, description) for required values
  • setOptionalValueHandler(option, ValueHandler, description) for optional values
  • setRootValueHandler(...) for bare inline roots such as --build release

API Notes

  • Parser keeps its own internal registration state.
  • InlineParser.copy() returns a deep copy suitable for registering or retargeting under a new root.
  • The public Kotlin source file is intended to be the source-of-truth contract for library consumers.

Parsing Behavior

ktools-kotlin/kcli/docs/behavior.md

This page collects the parsing rules that matter in practice.

Parse Lifecycle

kcli processes the command line in three stages:

  1. Read the caller's arguments into an internal token list.
  2. Validate and schedule handler invocations in a single pass.
  3. Execute scheduled handlers only after the full command line validates.

This means:

  • handlers do not run on partially-valid command lines
  • unknown options fail the parse before any handler side effects occur
  • the caller's effective arguments are not rewritten during parsing

Option Naming Rules

Top-level handlers:

  • accepted forms: "name" or "--name"
  • effective option token at runtime: --name

Inline roots:

  • accepted forms: "build" or "--build"
  • effective bare root token at runtime: --build

Inline handlers:

  • accepted forms: "-flag" or "--build-flag"
  • effective option token at runtime: --build-flag

Aliases:

  • alias form must be single-dash, such as -v
  • target form must be double-dash, such as --verbose

Inline Root Behavior

Bare inline roots behave specially.

--build

  • prints a help listing for the --build-* handlers

--build release

  • invokes the root value handler if one is registered
  • fails if no root value handler is registered

If a root value handler is registered with a placeholder and description, the bare-root help view includes a row such as:

--build <selector>  Select build targets.

Value Consumption Rules

kcli supports three public registration styles:

  • flag handlers consume no trailing value tokens
  • required-value handlers consume at least one value token
  • optional-value handlers consume values only when the next token looks like a value

Additional details:

  • once value collection starts, kcli keeps consuming subsequent non-option-like tokens for that handler
  • explicit empty tokens are preserved
  • joined handler values are produced by joining valueTokens with spaces

Examples:

--name "Joe"            -> valueTokens = ["Joe"]
--name "Joe" "Smith"    -> valueTokens = ["Joe", "Smith"]
--name ""               -> valueTokens = [""]
--profile -debug        -> valueTokens = ["-debug"]

Alias Behavior

Aliases are only expanded when a token is parsed as an option.

Examples:

parser.addAlias("-v", "--verbose")
parser.addAlias("-c", "--config-load", "user-file")

Rules:

  • consumed value tokens are not alias-expanded
  • preset tokens are prepended to effective valueTokens
  • preset tokens can satisfy required-value handlers
  • aliases with preset tokens cannot target flag handlers

Example:

-c settings.json

can behave like:

--config-load user-file settings.json

Positionals

The positional handler receives all remaining non-option tokens in a single invocation.

Important details:

  • explicit empty positional tokens are preserved
  • positionals are dispatched only after option parsing succeeds

Failure Behavior

Unknown option-like tokens fail the parse.

Notable cases:

  • unknown top-level option: --bogus
  • unknown inline option: --build-unknown
  • literal --

kcli does not treat -- as an option terminator. It is reported as an unknown option.

Error Surface

parseOrExit()

  • prints [error] [cli] ... to stderr
  • exits with code 2

parseOrThrow()

  • throws CliError
  • preserves the human-facing error message
  • surfaces handler exceptions as CliError

Behavior Coverage

The API and CLI behavior is covered by:

The demo programs under demo/ show complete, compiling usage.

Examples

ktools-kotlin/kcli/docs/examples.md

This page shows a few common kcli patterns. For complete compiling examples, also see:

Minimal Executable

val parser = Parser()

parser.addAlias("-v", "--verbose")
parser.setHandler("--verbose", { _ ->
}, "Enable verbose logging.")

parser.parseOrExit(args)

Inline Root With Subcommands-Like Options

val parser = Parser()
val build = InlineParser("--build")

build.setHandler("-profile", { _, value ->
    println("profile=$value")
}, "Set build profile.")
build.setHandler("-clean", { _ ->
}, "Enable clean build.")

parser.addInlineParser(build)
parser.parseOrExit(args)

This enables:

--build
--build-profile release
--build-clean

Bare Root Value Handler

val config = InlineParser("--config")

config.setRootValueHandler({ _, value ->
    println(value)
}, "<assignment>", "Store a config assignment.")

This enables:

--config
--config user=alice

Behavior:

  • --config prints inline help
  • --config user=alice invokes the root value handler

Alias Preset Tokens

val parser = Parser()

parser.addAlias("-c", "--config-load", "user-file")
parser.setHandler("--config-load", { context, value ->
    println("${context.option}: $value")
}, "Load config.")

This makes:

-c settings.json

behave like:

--config-load user-file settings.json

Inside the handler:

  • context.option is --config-load
  • context.valueTokens starts with "user-file"

Optional Values

parser.setOptionalValueHandler("--color", { _, value ->
    println(value)
}, "Set or auto-detect color output.")

This enables both:

--color
--color always

Positionals

parser.setPositionalHandler { context ->
    for (token in context.valueTokens) {
        usePositional(token)
    }
}

The positional handler receives all remaining non-option tokens after option parsing succeeds.

Custom Error Handling

If you want your own formatting or exit policy, use parseOrThrow():

try {
    parser.parseOrThrow(args)
} catch (ex: CliError) {
    System.err.println("custom cli error: ${ex.message}")
}

Use this when:

  • you want custom error text
  • you want custom logging
  • you want a different exit code policy