dotnet / dotnet/command-line-api
Simple ICommandHandler that injects the ParseResult
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
Idea for an alternative to `SetHandler()` that is used in the example [here](https://github.com/dotnet/command-line-api/blob/main/docs/Your-first-app-with-System-CommandLine.md).
```
class ParseResultHandler : ICommandHandler
{
public ParseResultHandler(Action handle) { ... }
...
}
static class Program {
static int Main(string[] args)
{
var inputFileArg = new Argument("input", "Path to the input file");
var exampleOpt = new Option(new[] { "-n", "--number" }, "Example option");
var rootCommand = new RootCommand(Description)
{
inputFileArg,
exampleOpt,
};
rootCommand.Handler = new ParseResultHandler((result) => {
var input_path = result.GetValueForArgument(inputFileArg);
var option = result.GetValueForOption(exampleOpt);
Console.WriteLine("Input path: {0}", input_path?.FullName ?? "None");
Console.WriteLine("Option: {0}", option?.ToString() ?? "None");
});
return rootCommand.Invoke(args);
}
}
```
I like this approach because it is easier for me to wrap my head around how it is working. Whereas I don't really understand what `SetHandler()` is doing except that it creates a handle function for `AnonymousCommandHandler` that eventually calls `context.ParseResult.GetValueForArgument()` and `context.ParseResult.GetValueForOption()` anyways.
Contributor guide
Assessment
This issue has not been assessed yet.