Skip to content

Instantly share code, notes, and snippets.

@chrisyarbrough
Created December 1, 2025 23:49
Show Gist options
  • Select an option

  • Save chrisyarbrough/8c03cd7b36b5bb7d35ce4d255199cb49 to your computer and use it in GitHub Desktop.

Select an option

Save chrisyarbrough/8c03cd7b36b5bb7d35ce4d255199cb49 to your computer and use it in GitHub Desktop.
CommandLine ICommand
using CommandLine;
using CommandLine.Text;
using System.Reflection;
/// <summary>
/// A CLI command of the application, like <i>clone</i> in <i>git clone</i>.
/// Corresponds to a verb in the CommandLineParser.
/// </summary>
/// <remarks>
/// Derived types are created by the CommandLineParser and their Run method is called when parsing was successful.
/// Using this interface makes it possible to automatically parse all verbs in the assembly without having to
/// define them individually by hand.
/// </remarks>
[UsedImplicitly(ImplicitUseTargetFlags.WithInheritors | ImplicitUseTargetFlags.Members)]
public interface ICommand
{
public void Run();
/// <summary>
/// Run this in the program's entry point to parse the command line arguments and execute the appropriate command.
/// </summary>
/// <param name="args">
/// The arguments passed in the main method.
/// Do not use Environment.GetCommandLineArgs() because it includes the path to the executable.
/// </param>
public static void Parse(IEnumerable<string> args)
{
// Find all commands in the executing program.
var commandTypes = Assembly.GetEntryAssembly()
.GetTypes()
.Where(t => typeof(ICommand).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract)
.ToArray();
// Parse the arguments with customized help text.
var parser = new Parser(with => with.HelpWriter = null);
var parserResult = parser.ParseArguments(args, commandTypes);
parserResult
.WithParsed(command => ((ICommand)command).Run())
.WithNotParsed(_ =>
{
var helpText = HelpText.AutoBuild(parserResult, h =>
{
h.AutoVersion = false; // hides --version
h.Copyright = string.Empty;
return HelpText.DefaultParsingErrorsHandler(parserResult, h);
}, e => e);
Console.WriteLine(helpText);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment