I am currently configuring a CLI command with the package System.CommandLine.
In my CommandClass I have added an option for the user to select if he wants to do a dry-run.
How do I check if the user has given that specific paramter?
Snippets of my code:
using System.CommandLine;
namespace MyApp.Cli.commands;
public class MyCommandClass : Command
{
public MyCommandClass()
: base("start-my-command", "test the functionalities of system.commandline")
{
AddOption(new Option<bool>(new string[] { "--dry-run", "-d" }, "Simulate the actions without making any actual changes"));
}
public new class Handler : ICommandHandler
{
private readonly ILogger<MyCommandClass> _log;
public Handler(ILogger<MyCommandClass> log)
{
_log = log;
}
public async Task<int> InvokeAsync(InvocationContext context)
{
var isDryRun = /* check if the user has provided the parameter "--dry-run" */
if (isDryRun)
{
_log.LogInformation("is dry run");
}
else
{
_log.LogInformation("is no dry run");
}
}
}
}
I already tried to do var isDryRun = context.ParseResult.GetValueForOption<bool>("--dry-run"); but this just gives me the following error: Argument 1: cannot convert from 'string' to 'System.CommandLine.Option'.
Please help, thanks.
Instead of using context.ParseResult.GetValueForOption("--dry-run") it's better to refer directly to the Option object created when adding the option to the command.