如何使用自定义解析器调用CommandLineUtils ExecuteAsync?

时间:2018-08-12 10:04:14

标签: .net-core commandlineutils

我想使用https://natemcmaster.github.io/CommandLineUtils/来使用不支持即用型选项和非常规执行方法的属性。

class Program
{
    //--from-date="2018-01-01"  --to-date="2018-07-01"
    [Option()]
    public DateTime? FromDate { get; }
    [Option()]
    public DateTime? ToDate { get; }

    private async Task OnExecuteAsync()
    {
        //do the actual work 
    }
  }  

如果我使用的是字符串类型,则静态ExecuteAsync可以正常工作。

var ret = CommandLineApplication.ExecuteAsync<Program>(args);

但是,如果参数的类型为DateTime ?,我必须添加自定义解析器(如Support passing Uri values #97中的建议)

我已经创建了一个应用程序对象,添加了解析器,分配了OnExecute并调用了execute方法

 private static int AddValueParsersAndExecute(string[] args)
    {
        var app = new CommandLineApplication<Program>();
        app.ValueParsers.AddOrReplace(new NullableDateTimeParser());
        app.OnExecute((Func<Task>) new Program().OnExecuteAsync);
        var ret = app.Execute(args);
        return ret;
    }

不幸的是,当我传递--from-date="2018-01-01" --to-date="2018-07-01"(并且尝试了选项名称的不同变体)时,它会导致错误

McMaster.Extensions.CommandLineUtils.CommandParsingException
  HResult=0x80131500
  Message=Unrecognized option '--from-date=2018-01-01'
  Source=McMaster.Extensions.CommandLineUtils
  StackTrace:
   at McMaster.Extensions.CommandLineUtils.CommandLineProcessor.HandleUnexpectedArg(String argTypeName) in C:\projects\commandlineutils\src\CommandLineUtils\Internal\CommandLineProcessor.cs:line 246
   at McMaster.Extensions.CommandLineUtils.CommandLineProcessor.ProcessOption() in C:\projects\commandlineutils\src\CommandLineUtils\Internal\CommandLineProcessor.cs:line 162
   at McMaster.Extensions.CommandLineUtils.CommandLineProcessor.ProcessNext() in C:\projects\commandlineutils\src\CommandLineUtils\Internal\CommandLineProcessor.cs:line 62
   at McMaster.Extensions.CommandLineUtils.CommandLineProcessor.Process() in C:\projects\commandlineutils\src\CommandLineUtils\Internal\CommandLineProcessor.cs:line 35
   at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Parse(String[] args) in C:\projects\commandlineutils\src\CommandLineUtils\CommandLineApplication.cs:line 532
   at McMaster.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args) in C:\projects\commandlineutils\src\CommandLineUtils\CommandLineApplication.cs:line 611
   at BlobsProcessor.Program.AddValueParsersAndExecute(String[] args) 

谁能建议,可以将ExecuteAsync,属性选项和自定义解析器结合起来吗?

到目前为止,我发现它具有字符串选项并将其解析为DateTime的解决方法?在我的应用程序中。

1 个答案:

答案 0 :(得分:0)

CommandLineApplication.ExecuteAsync<Program>(args)

的糖
using (var app = new CommandLineApplication<TApp>())
{
    app.SetContext(context);
    app.Conventions.UseDefaultConventions();
    return app.Execute(context.Arguments);
}

(请参见https://github.com/natemcmaster/CommandLineUtils/blob/e65492d1270067087cfdb80f6266290af0a563c7/src/CommandLineUtils/CommandLineApplication.Execute.cs#L53-L58

似乎您需要向app.Conventions.UseDefaultConventions();方法中添加AddValueParsersAndExecute