我目前正在使用包
System.CommandLine
配置 CLI 命令。
在我的 CommandClass 中,我添加了一个选项,供用户选择是否要执行
dry-run
。
如何检查用户是否给出了该特定参数?
我的代码片段:
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");
}
}
}
}
我已经尝试过这样做
var isDryRun = context.ParseResult.GetValueForOption<bool>("--dry-run");
但这只会给我以下错误:参数1:无法从'string'转换为'System.CommandLine.Option'。
请帮忙,谢谢。
不要使用 context.ParseResult.GetValueForOption("--dry-run") ,而是直接引用将选项添加到命令时创建的 Option 对象。
public class MyCommandClass : Command
{
// Declaring the dry-run option at the class level
private Option<bool> dryRunOpt = new Option<bool>(
aliases: new[] { "--dry-run", "-d" },
description: "Run in dry mode without actual changes"
);
public MyCommandClass() : base("start-my-command", "Testing the functionalities")
{
// Adding the dry-run option to our command
// This line is important :)
AddOption(dryRunOpt);
}
public class Handler : ICommandHandler
{
private readonly ILogger<MyCommandClass> logger;
public Handler(ILogger<MyCommandClass> logger)
{
this.logger = logger;
}
public async Task<int> InvokeAsync(InvocationContext context)
{
// Checking the dry-run option value
var isDryRun = context.ParseResult.GetValueForOption(dryRunOpt);
if (isDryRun)
{
logger.LogInformation("Running in dry-run mode.");
}
else
{
logger.LogInformation("Executing normal operation.");
}
// ...
return 0;
}
}
}