Language Page

kcli for C++

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

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

Karma CLI Parsing SDK

ktools-cpp/kcli/README.md

kcli is a small C++20 SDK for building structured command-line interfaces. It is used by ktrace and kconfig, and 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(argc, argv) for normal executable startup.
  • parseOrThrow(argc, argv) when the caller wants to intercept kcli::CliError.

Documentation

Quick Start

#include <kcli.hpp>

void handleVerbose(const kcli::HandlerContext&) {
}

void handleProfile(const kcli::HandlerContext&, std::string_view) {
}

int main(int argc, char** argv) {
    kcli::Parser parser;
    kcli::InlineParser build("--build");

    build.setHandler("-profile", handleProfile, "Set build profile.");

    parser.addInlineParser(build);
    parser.addAlias("-v", "--verbose");
    parser.setHandler("--verbose", handleVerbose, "Enable verbose logging.");

    parser.parseOrExit(argc, argv);
    return 0;
}

Behavior Highlights

  • The full command line is validated before any registered handler runs.
  • parseOrExit() preserves the caller's argv, reports invalid CLI input to stderr, and exits with code 2.
  • parseOrThrow() preserves the caller's argv and throws kcli::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/include
  • build/latest/sdk/lib
  • build/latest/sdk/lib/cmake/KcliSDK

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

Install

Consumer CMake:

find_package(KcliSDK CONFIG REQUIRED)
target_link_libraries(main PRIVATE kcli::sdk)

Repository Layout

  • Public API: include/kcli.hpp
  • Library implementation: src/
  • API behavior coverage: cmake/tests/kcli_api_cases.cpp
  • Integration demos: demo/

Coding Agents

If you are using a coding agent, paste the following prompt:

Follow the instructions in agent/BOOTSTRAP.md

Kcli Documentation

ktools-cpp/kcli/docs/index.md

kcli is a compact C++20 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 argv
  • support grouped inline roots such as --trace-* and --config-*

Start Here

Typical Flow

kcli::Parser parser;
kcli::InlineParser build("--build");

build.setHandler("-profile", handleProfile, "Set build profile.");

parser.addInlineParser(build);
parser.addAlias("-v", "--verbose");
parser.setHandler("--verbose", handleVerbose, "Enable verbose logging.");

parser.parseOrExit(argc, argv);

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 include/kcli.hpp.

API Guide

ktools-cpp/kcli/docs/api.md

This page summarizes the public types in include/kcli.hpp.

Core Types

Type Purpose
kcli::Parser Owns aliases, top-level handlers, positional handling, and inline parser registration.
kcli::InlineParser Defines one inline root namespace such as --build plus its --build-* handlers.
kcli::HandlerContext Metadata delivered to flag, value, and positional handlers.
kcli::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.
value_tokens 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

kcli::InlineParser parser("--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 value_tokens

Positional Handler

parser.setPositionalHandler(handlePositionals);

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

Inline Parser Registration

parser.addInlineParser(buildParser);

Duplicate inline roots are rejected.

Parse Entry Points

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

parseOrExit()

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

parseOrThrow()

  • preserves the caller's argv
  • throws kcli::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 is moveable and not copyable.
  • InlineParser is copyable and moveable.
  • The public header is intended to be the source-of-truth contract for library consumers.

Parsing Behavior

ktools-cpp/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 argv 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 argv is never rewritten or compacted

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 value_tokens with spaces

Examples:

--name "Joe"            -> value_tokens = ["Joe"]
--name "Joe" "Smith"    -> value_tokens = ["Joe", "Smith"]
--name ""               -> value_tokens = [""]
--profile -debug        -> value_tokens = ["-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 value_tokens
  • 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
  • colors error red and cli blue on terminals
  • exits with code 2

parseOrThrow()

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

Behavior Coverage

The executable behavior is covered by:

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

Examples

ktools-cpp/kcli/docs/examples.md

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

Minimal Executable

#include <kcli.hpp>

void handleVerbose(const kcli::HandlerContext&) {
}

int main(int argc, char** argv) {
    kcli::Parser parser;

    parser.addAlias("-v", "--verbose");
    parser.setHandler("--verbose", handleVerbose, "Enable verbose logging.");

    parser.parseOrExit(argc, argv);
    return 0;
}

Inline Root With Subcommands-Like Options

kcli::Parser parser;
kcli::InlineParser build("--build");

build.setHandler("-profile",
                 handleProfile,
                 "Set build profile.");
build.setHandler("-clean",
                 handleClean,
                 "Enable clean build.");

parser.addInlineParser(build);
parser.parseOrExit(argc, argv);

This enables:

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

Bare Root Value Handler

kcli::InlineParser config("--config");

config.setRootValueHandler(handleConfigValue,
                           "<assignment>",
                           "Store a config assignment.");

This enables:

--config
--config user=alice

Behavior:

  • --config prints inline help
  • --config user=alice invokes handleConfigValue

Alias Preset Tokens

kcli::Parser parser;

parser.addAlias("-c", "--config-load", {"user-file"});
parser.setHandler("--config-load", handleConfigLoad, "Load config.");

This makes:

-c settings.json

behave like:

--config-load user-file settings.json

Inside the handler:

  • context.option is --config-load
  • context.value_tokens is ["user-file", "settings.json"]

Optional Values

parser.setOptionalValueHandler("--color",
                               handleColor,
                               "Set or auto-detect color output.");

This enables both:

--color
--color always

Positionals

parser.setPositionalHandler(
    [&](const kcli::HandlerContext& context) {
        for (std::string_view token : context.value_tokens) {
            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(argc, argv);
} catch (const kcli::CliError& ex) {
    std::cerr << "custom cli error: " << ex.what() << "\n";
    return 2;
}

Use this when:

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