Language Page

kcli for Java

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

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

Karma CLI Parsing SDK

ktools-java/kcli/README.md

kcli is the Java 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;

public final class Main {
    private Main() {
    }

    public static void main(String[] args) {
        Parser parser = new Parser();
        InlineParser build = new InlineParser("--build");

        build.setHandler("-profile", (context, value) -> {
        }, "Set build profile.");

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

        parser.parseOrExit(args);
    }
}

Behavior Highlights

  • The full command line is validated before any registered handler runs.
  • parseOrExit(...) reports invalid CLI input to stderr and exits with code 2.
  • parseOrThrow(...) throws CliError.
  • Bare inline roots such as --build print inline help unless a root value is provided.
  • 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.

For the full parsing rules, see docs/behavior.md.

Build SDK

kbuild --build-latest

SDK output:

  • build/latest/sdk/classes

Build And Test 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/link 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/
  • Library implementation details: src/kcli/internal/
  • API and CLI coverage: tests/src/kcli/tests/
  • Integration demos: demo/

Kcli Java Documentation

ktools-java/kcli/docs/index.md

kcli is the Java command-line parsing SDK in the ktools ecosystem.

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 argument array
  • support grouped inline roots such as --trace-* and --config-*

Start Here

Typical Flow

import kcli.InlineParser;
import kcli.Parser;

Parser parser = new Parser();
InlineParser build = new InlineParser("--build");

build.setHandler("-profile", (context, value) -> {
}, "Set build profile.");

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

parser.parseOrExit(args);

Core Concepts

Parser

  • owns top-level handlers, aliases, positional handling, and inline parser registrations

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 complete, working examples, start with:

The public API contract lives in src/kcli/.

API Guide

ktools-java/kcli/docs/api.md

This page summarizes the public Java API in src/kcli/.

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

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

InlineParser parser = new 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", handler, "Enable build flag.");
parser.setHandler("-profile", handler, "Set build profile.");
parser.setOptionalValueHandler("-enable", handler, "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", context -> {
}, "Enable verbose logging.");
parser.setHandler("--output", (context, value) -> {
}, "Set output target.");
parser.setOptionalValueHandler("--color", (context, value) -> {
}, "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", "user-file=/tmp/user.json");

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(context -> {
});

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

  • preserves the caller's argument array
  • reports invalid CLI input to stderr as [error] [cli] ...
  • exits with code 2

parseOrThrow(...)

  • preserves the caller's argument array
  • 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 and InlineParser are mutable builder-style objects.
  • InlineParser.copy() creates a detached copy that can be retargeted with setRoot(...).
  • The public src/kcli/ package is intended to be the source-of-truth contract for library consumers.

Parsing Behavior

ktools-java/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 argument array is never rewritten

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", "user-file=/tmp/user.json");

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

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 executable behavior is covered by:

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

Examples

ktools-java/kcli/docs/examples.md

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

Minimal Executable

import kcli.Parser;

Parser parser = new Parser();

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

parser.parseOrExit(args);

Inline Root With Subcommand-Like Options

Parser parser = new Parser();
InlineParser build = new InlineParser("--build");

build.setHandler("-profile", (context, value) -> {
}, "Set build profile.");
build.setHandler("-clean", context -> {
}, "Enable clean build.");

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

This enables:

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

Bare Root Value Handler

InlineParser config = new InlineParser("--config");

config.setRootValueHandler((context, 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

Parser parser = new Parser();

parser.addAlias("-c", "--config", "user-file=/tmp/user.json");
parser.parseOrExit(args);

This makes:

-c

behave like:

--config user-file=/tmp/user.json

Inside the handler:

  • context.option() is --config
  • context.valueTokens() contains the preset value token

Optional Values

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

This enables both:

--color
--color always

Positionals

parser.setPositionalHandler(context -> {
    for (String token : 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 (CliError ex) {
    System.err.println("custom cli error: " + ex.getMessage());
    System.exit(2);
}

Use this when:

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