Language Page

kcli for C#

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

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

Karma CLI Parsing SDK For C#

ktools-csharp/kcli/README.md

kcli is a small C# SDK for building structured command-line interfaces. It supports the same two CLI shapes used elsewhere in the ktools stack:

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

The C# API keeps the same conceptual model as the existing C++ and Java implementations while using .NET-style naming.

Quick Start

using Kcli;

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

Documentation

Behavior Highlights

  • The full command line is validated before any registered handler runs.
  • ParseOrExit() prints [error] [cli] ... to stderr and exits with code 2.
  • ParseOrThrow() raises CliError.
  • Bare inline roots print inline help when no root value is provided.
  • Required values may consume an option-like first token.
  • Literal -- remains an unknown option; it is not treated as a separator.

Build

kbuild --build-latest

SDK output:

  • build/latest/sdk/lib/Kcli.dll
  • build/latest/tests/bin/Kcli.Tests.dll

Build And Run Demos

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

# Explicit demo-only run.
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

Run Tests

dotnet build/latest/tests/bin/Kcli.Tests.dll

Layout

  • Public API and implementation: src/
  • API tests: tests/src/
  • Demo builds: demo/

Working references:

  • src/Kcli/Parser.cs
  • src/Kcli/InlineParser.cs
  • src/Kcli/ParseEngine.cs
  • tests/src/Kcli.Tests/Program.cs
  • demo/sdk/alpha/src/Kcli/Demo/Alpha/AlphaSdk.cs
  • demo/exe/core/src/Kcli/Demo/Core/Program.cs
  • demo/exe/omega/src/Kcli/Demo/Omega/Program.cs

Kcli C# Documentation

ktools-csharp/kcli/docs/index.md

kcli is the C# implementation of the ktools command-line parsing layer.

It keeps the same core model used across the ecosystem:

  • one Parser for top-level options and aliases
  • one InlineParser per inline root such as --build or --trace
  • full command-line validation before any handler runs
  • explicit failure through CliError or exit-oriented parsing

Start Here

Typical Flow

using Kcli;

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

InlineParser

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

HandlerContext

  • Exposes the effective root, option, command, 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 entrypoint
  • invalid CLI input should print a standardized error and exit with code 2
  • you do not need custom error handling

Use ParseOrThrow() when:

  • you want custom formatting or exit behavior
  • you want to test parse failures directly
  • you want to intercept handler failures as exceptions

Build And Explore

kbuild --build-latest
dotnet build/latest/tests/bin/Kcli.Tests.dll
./demo/exe/core/build/latest/test --alpha-message "hello"
./demo/exe/omega/build/latest/test --build

Working References

API Guide

ktools-csharp/kcli/docs/api.md

This page summarizes the public C# API in the src/Kcli/ implementation, primarily:

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.

Property 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. Shell tokens 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

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", 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

Root Changes

parser.SetRoot("--newbuild");

SetRoot() replaces the inline root after construction. Existing command handlers stay attached to the parser and will use the new root name.

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", "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(args);
parser.ParseOrThrow(args);
parser.ParseOrExit(argc, argv);
parser.ParseOrThrow(argc, argv);

ParseOrExit()

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

ParseOrThrow()

  • preserves the caller's argument vector
  • 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 registration objects.
  • Optional-value handlers receive an empty string when no value is provided.
  • Literal -- is not a terminator; it is treated as an unknown option.

Parsing Behavior

ktools-csharp/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. Copy 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 vector 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-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

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 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-csharp/kcli/docs/examples.md

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

Minimal Executable

using Kcli;

Parser parser = new Parser();

parser.AddAlias("-v", "--verbose");
parser.SetHandler("--verbose", context => { }, "Enable verbose logging.");

parser.ParseOrExit(args);

Inline Root With Subcommands-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-load", "user-file");
parser.SetHandler("--config-load", (context, 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 is ["user-file", "settings.json"]

Optional Values

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

This enables both:

--color
--color always

Positionals

parser.SetPositionalHandler(context =>
{
    foreach (string 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 (CliError ex)
{
    Console.Error.WriteLine($"custom cli error: {ex.Message}");
    return;
}