在尝试将Mono.Options压缩到我的Cake脚本中时,我注意到我并不完全确定如何从首先启动Cake脚本的命令行调用中提供原始参数字符串。 Mono.Options Parse
方法采用典型的控制台应用string[] args
参数,因此我需要提供它可以使用的内容。
我知道我可以使用ArgumentAlias调用查询特定参数的上下文,但有没有办法访问整个原始字符串调用字符串?
答案 0 :(得分:4)
Cake脚本本质上只是一个常规的.NET进程,您可以通过System.Environment.GetCommandLineArgs()
快速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
将输出帮助,因为没有指定名称
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
将失败并报告,因为重复不是数字