如何在 Microsoft System.Commandline CLI 中检查特定参数

How to check for specific parameter in Microsoft System.Commandline CLI

提问人:Ruwiwidi 提问时间:11/15/2023 更新时间:11/16/2023 访问量:28

问:

我目前正在使用软件包配置CLI命令。System.CommandLine

在我的 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");
            }
        }
    }
    
}

我已经尝试过这样做,但这只给了我以下错误:参数 1:无法从“字符串”转换为“System.CommandLine.Option”。var isDryRun = context.ParseResult.GetValueForOption<bool>("--dry-run");

请帮忙,谢谢。

C# 命令行接口 system.commandline

评论


答:

0赞 Ali Hemmati 11/16/2023 #1

而不是使用上下文。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;
        }
    }
}

评论

0赞 Ruwiwidi 11/16/2023
谢谢。我将该选项标记为 ,因为我收到错误“非静态字段、方法或属性 'MyCommand.dryRunOpt' 需要对象引用”,但现在它可以工作了。staticcontext.ParseResult.GetValueForOption(dryRunOpt);
0赞 Ali Hemmati 11/16/2023
欢迎您:)