【问题标题】:Cake build: access original command line arguments string?Cake build:访问原始命令行参数字符串?
【发布时间】:2018-04-14 10:06:46
【问题描述】:

在尝试将Mono.Options 压缩到我的Cake 脚本中时,我注意到我并不完全确定如何从最初启动Cake 脚本的命令行调用中为其提供原始参数字符串。 Mono.Options Parse 方法采用典型控制台应用程序的 string[] args 参数,因此我需要为其提供可以使用的东西。

我知道我可以使用 ArgumentAlias 调用查询特定参数的上下文,但是有没有办法访问整个原始字符串调用字符串?

【问题讨论】:

    标签: c# command-line-arguments cakebuild


    【解决方案1】:

    Cake 脚本本质上只是一个常规的 .NET 进程,您可以通过 System.Environment.GetCommandLineArgs() 访问它

    PoC 示例

    你可以在下面的 Cake 中使用 Mono.Options 的一种方法的快速 n 肮脏示例

    #addin nuget:?package=Mono.Options&version=5.3.0.1
    using Mono.Options;
    
    public static class MyOptions
    {
        public static bool ShouldShowHelp { get; set; } = false;
        public static List<string> Names { get; set; } = new List<string>();
        public static int Repeat { get; set; } = 1;
    }
    
    var p = new OptionSet {
                { "name=",    "the name of someone to greet.",                          n => MyOptions.Names.Add (n) },
                { "repeat=",  "the number of times to MyOptions.Repeat the greeting.",  (int r) => MyOptions.Repeat = r },
                // help is reserved cake command so using options instead
                { "options",     "show this message and exit",                             h => MyOptions.ShouldShowHelp = h != null },
            };
    
    try {
        p.Parse (
            System.Environment.GetCommandLineArgs()
            // Skip Cake.exe and potential cake file.
            // i.e. "cake --name="Mattias""
            //  or "cake build.cake --name="Mattias""
            .SkipWhile(arg=>arg.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)||arg.EndsWith(".cake", StringComparison.OrdinalIgnoreCase))
            .ToArray()
        );
    }
    catch (OptionException e) {
        Information("Options Sample: ");
        Information (e.Message);
        Information ("--options' for more information.");
        return;
    }
    
    if (MyOptions.ShouldShowHelp || MyOptions.Names.Count == 0)
    {
        var sw = new StringWriter();
        p.WriteOptionDescriptions (sw);
        Information(
            "Usage: [OPTIONS]"
            );
        Information(sw);
        return;
    }
    
    string message = "Hello {0}!";
    
    foreach (string name in MyOptions.Names) {
        for (int i = 0; i < MyOptions.Repeat; ++i)
            Information (message, name);
    }
    

    示例输出

    cake .\Mono.Options.cake 将在未指定名称时输出帮助

    cake .\Mono.Options.cake --options 将输出“帮助”

    cake .\Mono.Options.cake --name=Mattias 会和我打招呼

    cake .\Mono.Options.cake --name="Mattias" --repeat=5会打招呼5次

    cake .\Mono.Options.cake --name="Mattias" --repeat=sdss 将失败并报告,因为重复不是数字

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      相关资源
      最近更新 更多