Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

Respect.CommandLine

Warning

Respect.CommandLine is an early preview. The API may change before 1.0.

CI License: MIT .NET

A declarative command-line framework for .NET. Build a conventional CLI, a runtime-extensible host, or both from the same command model.

Respect.CommandLine gives an ordinary application the pieces expected from an alternative to System.CommandLine or Spectre.Console.Cli:

  • POSIX/GNU parsing, including short-option bundles, --name=value, --, and POSIXLY_CORRECT;
  • typed options and arguments with command-line, environment, configuration, and default-value precedence;
  • generated help, diagnostics with stable codes, shell completion, and version handling, with one diagnostic per mistake and did-you-mean suggestions;
  • a versioned --json result envelope that keeps machine output separate from prose;
  • BCL-only packages that are trimming-safe and Native AOT compatible.

Commands are immutable data rather than classes or delegates. That also lets applications add commands at runtime, serialize the command tree, or execute a command through another invoker. Those capabilities are available when needed; they do not require an application to support third-party plugins.

Install

For a normal CLI:

dotnet add package Respect.CommandLine

Add completion only when you want it:

dotnet add package Respect.CommandLine.Completion

For a normal CLI, there is no plugin package or loader involved. Plugin authors reference Respect.CommandLine.Abstractions instead of the engine.

A regular CLI

Define a command, register its handler, and run the application:

using Respect.CommandLine;

var build = CommandBuilder.Create("acme.build", "build")
    .Summary("Compile a project.")
    .Option("jobs", option => option
        .Short('j')
        .Takes(ValueTypeRef.Int32)
        .Default(1)
        .ValueName("N")
        .Summary("Number of parallel jobs."))
    .Argument("project", argument => argument
        .Required()
        .OfType(ValueTypeRef.Path)
        .CompletesFiles("*.csproj"))
    .Build();

var registry = new CommandRegistry();
using var registration = registry.Register(new CommandContribution
{
    Descriptor = build,
    SourceId = "acme",
});

var application = new CommandLineApplication(registry, new ApplicationOptions
{
    Name = "acme",
    Version = "1.0.0",
});

application.Handlers.Add(build.Id, context =>
{
    var project = context.Values.GetValueOrDefault<string>("project");
    var jobs = context.Values.GetValueOrDefault<int>("jobs");

    context.Output.WriteLine($"Building {project} with {jobs} jobs.");
    context.Output.AddData("project", project);
    context.Output.AddData("jobs", jobs);

    return 0;
});

return await application.RunAsync(args);

The same declaration drives parsing, help, and JSON. The optional completion package reads it too:

$ acme build src/App.csproj -j 4
Building src/App.csproj with 4 jobs.

$ acme build --help
Usage: acme build [options] PROJECT

Compile a project.

$ acme build src/App.csproj -j nope
error RCL1006: Invalid value for 'jobs': 'nope' is not a whole number.
$ echo $?
2

$ acme build src/App.csproj -j 4 --json | jq '.data.jobs'
4

This application performs no assembly scanning or plugin discovery. Only the command registered by its own code is available. See Getting started for subcommands, validation, configuration, and optional completion.

Standard options

--help, --version, --json, and --no-color are injected as global options by default. A host that owns one of those spellings, or has no version to report, selects the rest:

new ApplicationOptions
{
    StandardOptions = StandardOptions.Help | StandardOptions.Version,
}

StandardOptions.All is the default. InjectStandardOptions = false remains the legacy off switch and forces StandardOptions.None. A spelling that is not injected is not special: it is parsed as an ordinary unknown option, with the usual diagnostic and suggestions. A host that declares its own option under one of those names keeps it either way.

If you are coming from another CLI framework

The day-to-day workflow stays familiar:

Need Respect.CommandLine
Declare a command CommandBuilder → immutable CommandDescriptor
Attach behavior application.Handlers.Add(commandId, handler)
Parse and validate ValueTypeRef, AllowedValues, arity, conflicts, dependencies
Render help --help or --help --json from the same declaration
Add completion Reference Respect.CommandLine.Completion, then call AddCompletion()
Add plugins Optional: implement your own loader and call RegisterSource()

You can start with the static path above and adopt runtime registration later without rewriting the command declarations.

Optional: runtime-extensible hosts

A host may accept commands after startup through the same registry. A plugin references only Respect.CommandLine.Abstractions and contributes descriptors through ICommandProvider:

[assembly: PluginContract(ContractVersion.Current)]

public sealed class WasmPlugin : ICommandProvider, ICommandHandlerResolver
{
    public string SourceId => "wasm";

    public ValueTask<IReadOnlyList<CommandContribution>> GetCommandsAsync(
        CancellationToken cancellationToken)
        => ValueTask.FromResult<IReadOnlyList<CommandContribution>>
        ([
            new CommandContribution
            {
                SourceId = SourceId,
                ParentPath = ["build"],
                Descriptor = CommandBuilder.Create("wasm.build", "wasm")
                    .Summary("Build for WebAssembly.")
                    .Build(),
            },
        ]);

    public bool TryResolve(CommandId commandId, out ICommandHandler? handler)
    {
        handler = commandId.Value == "wasm.build" ? new WasmHandler() : null;
        return handler is not null;
    }
}

The host chooses whether and how to discover that assembly, then opts in explicitly:

var commandRegistration = registry.RegisterSource(provider);
var handlerRegistration = application.Handlers.AddResolver(resolver);

Respect.CommandLine never scans a directory or loads an assembly on its own. The host owns its allowlist, signatures, manifests, and load locations. A loaded in-process plugin has the process's permissions; AssemblyLoadContext is not a security sandbox. See Plugins and the security policy before accepting third-party code.

Name conflicts are deterministic. Built-in commands can receive BuiltInPriority; losing plugin commands remain available as source:name under the default policy. Curated hosts can instead select ConflictPolicy.Fail and reject catalogs with errors. Priority and Replace are catalog inputs, not permissions: a host accepting third-party contributions should normalize priorities and reject replacements unless its own policy explicitly allows them.

Why commands are data

CommandDescriptor contains names, options, arguments, help text, and metadata. It contains no delegate and no System.Type. Execution is registered separately by stable CommandId.

That separation provides three useful properties without changing the basic CLI workflow:

Property What it enables
One immutable command model Parsing, help, completion, JSON introspection, and GUI command palettes use the same tree.
Handlers resolved by ID Commands can be renamed or qualified after a collision without changing which code runs.
Runtime registration Trusted application modules or optional plugins can add and remove commands without rebuilding the host.

Every invocation uses an immutable catalog snapshot. Loading or unloading a command while another command is running cannot change that invocation's route or syntax.

Packages

Package Use it for
Respect.CommandLine Applications and hosts: registration, parsing, binding, help, output, and execution.
Respect.CommandLine.Completion Optional bash, zsh, fish, and PowerShell completion.
Respect.CommandLine.Abstractions Plugin or shared-contract projects that must not depend on the engine. Applications receive it transitively.

All packages target .NET 10 and have no runtime dependencies outside the BCL.

Every package includes its README and a .snupkg symbol package, so a debugger can step into the framework rather than guess from a stack trace. scripts/verify-pack.sh is the release gate: it packs the solution into a temporary directory and refuses a release with a missing package, a package without its README, or a dependency on a project that was not packed.

Completion answers are capped at 1000 candidates by default, so a runaway provider cannot flood a shell menu. Pass maxItems to AddCompletion or set CompletionService.MaxItems; 0 means no limit.

Project status

The current version is 0.1.0-preview.1. The engine is covered by unit, conformance, completion, integration, and Native AOT build tests. It is not yet recommended for production use.

Current limitations:

  • the public API may change before 1.0;
  • fish and PowerShell completion scripts are preview; their generated scripts are parsed in CI (fish on Linux, PowerShell on Windows), but not exercised interactively;
  • ICommandInvoker provides the extension point for out-of-process execution, but no transport ships yet;
  • the JSON Schema for declaring descriptors outside .NET is available in docs/schema; it covers the wire shape, not the runtime validation rules.

Documentation

Guide Contents
Getting started Build a static CLI, add subcommands, validate input, and enable completion.
Architecture Command data, catalog snapshots, and the execution pipeline.
Help output Text and JSON help contracts.
Machine-readable output The versioned --json envelope.
JSON Schema Draft 2020-12 schema for command descriptors read or declared outside .NET.
Shell completion Installation, completion sources, and custom providers.
Plugins The optional plugin contract, loading, unloading, and trust boundary.
Diagnostics Stable diagnostic codes and their remedies.
Versioning Compatibility guarantees for APIs, plugins, JSON, and diagnostics.

See CONTRIBUTING.md to build and test the repository.

License

MIT

About

No description, website, or topics provided.

Resources

Contributing

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages