While trying to squeeze Mono.Options into my Cake script, I noticed I wasn't entirely sure how to give it the original arguments string from the command line call that launched the Cake script in the first place. Mono.Options Parse
method takes what would be a typical console app's string[] args
parameter, so I need to feed it something it can work with.
I know I can query the context for specific arguments with ArgumentAlias calls, but is there any way to access the entire original string calling string?
Cake scripts are essentially just a regular .NET Process to you can access it through System.Environment.GetCommandLineArgs()
Quick n dirty example of one way you could use Mono.Options with Cake below
#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
will output help as no names specified
cake .\\Mono.Options.cake --options
will output "help"
cake .\\Mono.Options.cake --name=Mattias
will greet me
cake .\\Mono.Options.cake --name="Mattias" --repeat=5
will greet me 5 times
cake .\\Mono.Options.cake --name="Mattias" --repeat=sdss
will fail and report because repeat not a number
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.