Created
December 1, 2025 23:49
-
-
Save chrisyarbrough/8c03cd7b36b5bb7d35ce4d255199cb49 to your computer and use it in GitHub Desktop.
CommandLine ICommand
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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