Skip to content
ConsoleMonster

Command-line tools

Parse command lines with ConsoleMonster.Commands: subcommands, typed options, themed help, typo suggestions and fixed exit codes. Works with native AOT.

audit scan --help 90 columns24-bitFull
C#Program.cs
// A small audit tool with one subcommand. Run without arguments, it shows the help for "audit scan",
// the page a user gets from "audit scan --help".
Option<string[]> servers = new Option<string[]>("--server", "-s") {
    Description = "Servers to scan, separated by commas.",
    ValueName = "name",
    Required = true,
    Separator = ','
};
Option<string> depth = new Option<string>("--depth", "-d") {
    Description = "How much to check on each server.",
    DefaultValue = "quick"
}.AcceptOnly("quick", "full");
Option<TimeSpan> timeout = new Option<TimeSpan>("--timeout") {
    Description = "How long to wait for one server, such as 30s or 2m.",
    DefaultValue = TimeSpan.FromSeconds(30),
    Group = "Connection"
};
Option<bool> dryRun = new Option<bool>("--dry-run") {
    Description = "List the checks without running them.",
    Group = "Connection"
};
Argument<string> report = new Argument<string>("report") {
    Description = "Where to save the report."
};

Command scan = new Command("scan",
    "Scans servers and writes a report.") { servers, depth, timeout, dryRun, report };
scan.Examples.Add(new CommandExample("audit scan -s DC1,DC2 --depth full report.html",
    "Two domain controllers, every check"));
scan.SetAction(context => 0);

CommandApp app = new CommandApp("audit", "Checks servers against the baseline.") { scan };
app.Version = "1.4.0";
return app.Run(args.Length > 0 ? args : new[] { "scan", "--help" });
Full program
using ConsoleMonster.Commands;

// A small audit tool with one subcommand. Run without arguments, it shows the help for "audit scan",
// the page a user gets from "audit scan --help".
Option<string[]> servers = new Option<string[]>("--server", "-s") {
    Description = "Servers to scan, separated by commas.",
    ValueName = "name",
    Required = true,
    Separator = ','
};
Option<string> depth = new Option<string>("--depth", "-d") {
    Description = "How much to check on each server.",
    DefaultValue = "quick"
}.AcceptOnly("quick", "full");
Option<TimeSpan> timeout = new Option<TimeSpan>("--timeout") {
    Description = "How long to wait for one server, such as 30s or 2m.",
    DefaultValue = TimeSpan.FromSeconds(30),
    Group = "Connection"
};
Option<bool> dryRun = new Option<bool>("--dry-run") {
    Description = "List the checks without running them.",
    Group = "Connection"
};
Argument<string> report = new Argument<string>("report") {
    Description = "Where to save the report."
};

Command scan = new Command("scan",
    "Scans servers and writes a report.") { servers, depth, timeout, dryRun, report };
scan.Examples.Add(new CommandExample("audit scan -s DC1,DC2 --depth full report.html",
    "Two domain controllers, every check"));
scan.SetAction(context => 0);

CommandApp app = new CommandApp("audit", "Checks servers against the baseline.") { scan };
app.Version = "1.4.0";
return app.Run(args.Length > 0 ? args : new[] { "scan", "--help" });
audit scan --help at 90 columns, drawn by the program shown with it.

Add it with dotnet add package ConsoleMonster.Commands. The package brings ConsoleMonster with it and nothing else.

ConsoleMonster.Commands parses command lines and draws their help, errors and completions with ConsoleMonster. It depends on nothing but ConsoleMonster, runs on .NET Framework 4.7.2, .NET Standard 2.0, .NET 8 and .NET 10, and works with trimming and native AOT. ConsoleMonster.Examples.Extensions cli --servers 4 runs this example (CommandLineExample.cs):

Option<int> servers = new Option<int>("--servers", "-s") {
    Description = "How many servers to check (1–100).",
    DefaultValue = 3
}.Validate(count => count < 1 || count > 100 ? "The server count must be between 1 and 100." : null);
CommandApp app = new CommandApp("cli", "Checks a few servers and prints what it found.") { servers };
app.SetAction(context => {
    int count = context.GetValue(servers);
    // ... a live status list while it works, then a table
    return 0;
});
return app.Run(args);

A command is a tree: CommandApp is the root and is named as the executable, Command adds subcommands, and each command holds Option<T>, ListOption<T>, Argument<T> and ListArgument<T> values. Values convert without reflection: strings, numbers, bool, enumerations (written in kebab case, dry-run; [Flags] enumerations also take read,write and numbers), TimeSpan (30s, 1h30m or 00:05:00), dates, Guid, Version, Uri, FileInfo, DirectoryInfo and one-dimensional arrays of these. Anything else takes a Parser.

What the parser accepts:

  • --name value, --name=value and --name:value; a flag may be followed by true or false.
  • -- ends the options; negative numbers are values, not options.
  • @file reads more arguments from a response file, one or more per line, # for comments.
  • --help, -h, -?, /? and help <command> show help; --version shows CommandApp.Version when it is set.
  • IgnoreCase matches names and listed values in any case.
  • A mistyped name gets a suggestion: Unknown option '--dpeth'. Did you mean '--depth'?

Exit codes follow one rule everywhere: ExitCode.Success (0), Failure (1, an unhandled exception, drawn with ExceptionView), Usage (2, a parse error or a prompt nobody can answer) and Cancelled (130, Ctrl+C). Errors go to standard error with a pointer to the command's help.

Checks run in order once the line has been read: each value's AcceptOnly list and Validate callbacks, required options and arguments, then each command's own Validate(check => ...) for rules that span options. CommandApp.ValueSource supplies values the line left out, such as defaults read from a configuration file; a supplied value counts as given. app.Use((context, next) => ...) wraps every action, for output policy, transcripts or timing.

Help is a HelpTopic drawn with HelpView, so it follows the theme and the terminal, and CommandHelp.CreateTopic returns the same topic for other renderers. Options show their groups, defaults and accepted values (--mode <fast|thorough>); HelpTopicCreated lets a product add groups, families or examples. app.Complete(words) returns completions for the word being typed: subcommands, option names, listed values and each value's own Completions.

For settings classes, CommandBinding<TSettings> declares options that read their defaults from a new instance and assign the parsed value back, so a command's action receives a filled settings object.

Next

Edit this page on GitHub