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 将失败并报告,因为重复不是数字