Building Command Line Tools with H.Necessaire CLI
Commands, sub-commands, argument parsing, help and interactive mode with CliWireup.
Applies to H.Necessaire 4.0.5.
H.Necessaire's CLI support turns a console app into a command line tool in a few lines: commands are plain classes, discovered automatically, with sub-commands, argument parsing, usage help and an interactive mode built in.
Install
dotnet add package H.Necessaire.Runtime.CLIH.Necessaire.Runtime.CLI (netstandard2.0) holds the infrastructure. H.Necessaire.CLI (net11.0) is a ready-made tool built on it, with maintenance commands for H.Necessaire itself; you only need it if you want those.
The entry point
using H.Necessaire.Runtime.CLI;
public static class Program
{
public static async Task Main()
{
await new CliWireup()
.WithEverything()
.Run();
}
}CliWireup is an ApiWireupBase (see the getting started article). WithEverything() registers the runtime, the console UI, the command interpreter, and every command and sub-command found in your assemblies. It also hooks Ctrl+C and process exit to a cancellation token, so long-running commands can stop cleanly. Run() executes the command named by the first argument and, if the result failed, prints its reasons as a warning.
To customise the wireup (extra dependency groups, config), derive from CliWireup and override WithEverything(), or chain .With(x => x.Register<...>(...)) before Run().
Writing a command
using H.Necessaire.CLI.Commands;
public class GreetCommand : CommandBase
{
static readonly string[] usage = { "greet name=Ada [shout]" };
protected override string[] GetUsageSyntaxes() => usage;
public override async Task<OperationResult> Run()
{
Note[] args = (await GetArguments()).Jump(1); // skip the command name itself
string name = args.Get("name", ignoreCase: true);
if (name.IsEmpty())
return FailWithUsageSyntax();
string message = $"Hello, {name}!";
Console.WriteLine(args.Any(x => x.ID.Is("shout")) ? message.ToUpperInvariant() : message);
return OperationResult.Win();
}
}mytool greet name=Ada
mytool greet name=Ada shoutCommandBase extends UseCaseBase, so you also get a Logger and the use case context. A command is just a class implementing ImACliCommand with a Run() that returns an OperationResult. A thrown exception is caught, logged and turned into a failed result.
How arguments are parsed
- Each command line argument becomes a
Note.key=valuesplits on the first=, so values may contain more of them. - A bare word (
shout) becomes a note whose ID is the word and whose value is empty, which makes it a flag. - The first note is the command name. Read values with
args.Get("key", ignoreCase: true). - Quote values that contain spaces the way your shell requires: the CLI receives the arguments the runtime gives it.
How a command is found
The first argument is matched, case-insensitively, against each command class by (in order of preference) its [ID("...")], its [Alias("...")] names, its exact type name, and finally any type whose name starts with what you typed. So greet finds GreetCommand without any attribute; add [ID] and [Alias] when you want a short or stable name. If nothing is given, the cli interactive mode starts.
Sub-commands
public class DbCommand : CommandBase
{
public override Task<OperationResult> Run() => RunSubCommand();
[ID("migrate")]
class MigrateSubCommand : SubCommandBase
{
public override async Task<OperationResult> Run(params Note[] args)
{
string target = args.Get("target", ignoreCase: true) ?? "latest";
// ...
return true;
}
}
}mytool db migrate target=latestRunSubCommand() looks at the argument after the command name and looks for a matching sub-command, preferring classes nested inside the command, then classes in the same assembly, then any sub-command registered globally. With no match it prints the command's usage syntax (or fails, if you pass failOnMissingCommand: true). Returning true or a string works because OperationResult converts implicitly: true is a win, a non-empty string is a failure with that reason.
Built-in commands
| Command | What it does |
|---|---|
help (alias ?) | Lists commands with their usage syntax; help build or help q=build searches. |
cli | Interactive prompt; exit, quit or bye leaves it. |
copy (alias cpy) | copy folder src=... dst=... copies a directory tree. |
version | Prints the tool's version; out=path also writes it to a file (in H.Necessaire.CLI). |
ping | Checks authentication and logs a pong (in H.Necessaire.CLI). |
nugetversion | For maintainers: update H.Necessaire=patch bumps versions in NuSpecs, consolidate-deps syncs NuSpec dependencies with CSPROJ versions (in H.Necessaire.CLI). |
Override GetUsageSyntaxes() in your own commands and help will show them too.
Tips
- Commands and sub-commands are registered always-new, so instance fields are safe per run.
- Only assemblies outside the H.Necessaire core are scanned, so put your commands in your own app or library assembly.
- Use
HSafe.Runfor risky I/O inside a command and return its result directly: failures print as warnings and the tool keeps a clean exit path.