Cake构建:如何访问原始命令行参数字符串?

3
在尝试将Mono.Options引入我的Cake脚本时,我注意到我不太确定如何将它与最初启动Cake脚本的命令行调用中的原始参数字符串配合使用。Mono.Options Parse 方法需要一个典型控制台应用程序的 string[] args 参数,因此我需要提供一些它可以处理的东西。
我知道我可以使用ArgumentAlias调用查询特定参数的上下文,但是否有任何方法可以访问整个原始调用字符串?
1个回答

4

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

示例PoC

下面是一种使用Mono.Options和Cake的快速而简单的示例方法:

#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 将输出 "help"。

已指定名称

cake .\Mono.Options.cake --name=Mattias 将向我问候。

已指定名称

cake .\Mono.Options.cake --name="Mattias" --repeat=5 将向我问候5次。

已指定名称和重复次数

cake .\Mono.Options.cake --name="Mattias" --repeat=sdss 将由于重复次数不是数字而失败并报告错误。

输入图像说明


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接