dotnet / dotnet/command-line-api

Simple ICommandHandler that injects the ParseResult

Open
#1,602 1 comment 0 reactions 0 assignees View on GitHub
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.