Cake build:访问原始命令行参数字符串?

时间:2017-11-02 00:48:41

标签: c# command-line-arguments cakebuild

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

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

1 个答案:

答案 0 :(得分:4)

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

访问它

示例PoC

快速n脏的例子,你可以使用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将输出帮助,因为没有指定名称

no arguments

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

nane specified

cake .\Mono.Options.cake --name=Mattias会问候我

name specified

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

name and repeat specified

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

enter image description here