static void Main(string[] args) { // ask docopt to parse input args var inputs = new Docopt().Apply( Usage.Replace("{name}", Name), args, version: $"{Name} {Version}", exit: true // exit if input args does not match pattern ); if (inputs["init"].IsTrue) { ProgramConfigs.InitConfigs( // grab the optional project name inputs["<project_name>"] is null ? string.Empty : inputs["<project_name>"].Value.ToString() ); } else if (inputs["build"].IsTrue) { string source = ProgramConfigs.GetProjectSource(); if (source is null) { Console.Error.WriteLine("Can not determine source directory from configs"); Environment.Exit(1); } var examplesDir = ProgramConfigs.GetExamplesSource(); var outputDir = ProgramConfigs.GetProjectTarget(); // write project info var configs = ProgramConfigs.GetConfigs(); ProjectConfigs.WriteProjectInfo(configs, outputDir); // build the docs data file Console.WriteLine($"Building docs:\n{source} => {outputDir}"); Docify(source, examplesDir, outputDir); } }
public void Should_generate_code() { // TODO: not a very useful test, more of a sanity check const string USAGE = @"Test host app for T4 Docopt.NET Usage: prog command ARG <myarg> [OPTIONALARG] [-o -s=<arg> --long=ARG --switch] prog files FILE... Options: -o Short switch. -s=<arg> Short option with arg. --long=ARG Long option with arg. --swith Long switch. Explanation: This is a test usage file. "; const string expected = @" public bool CmdCommand { get { return _args[""command""].IsTrue; } } public string ArgArg { get { return _args[""ARG""].ToString(); } } public string ArgMyarg { get { return _args[""<myarg>""].ToString(); } } public string ArgOptionalarg { get { return _args[""OPTIONALARG""].ToString(); } } public bool OptO { get { return _args[""-o""].IsTrue; } } public string OptS { get { return _args[""-s""].ToString(); } } public string OptLong { get { return _args[""--long""].ToString(); } } public bool OptSwitch { get { return _args[""--switch""].IsTrue; } } public bool CmdFiles { get { return _args[""files""].IsTrue; } } public ArrayList ArgFile { get { return _args[""FILE""].AsList; } } "; var s = new Docopt().GenerateCode(USAGE); Assert.AreEqual(expected.Trim(), s.Trim()); }
public MainArgs(string[] argsv) { argsv = argsv.Any() ? argsv : new string[] { "up" }; var version = typeof(MainArgs).Assembly.GetName().Version.ToString(); var args = new Docopt().Apply(usage, argsv, version: version); if (args["up"].IsTrue) { long up = 0; if (args["<version>"] != null) { long.TryParse(args["<version>"].ToString(), out up); } Up = up; } if (args["down"].IsTrue) { long.TryParse(args["<version>"].ToString(), out long down); Down = down; } if (args["rollback"].IsTrue) { Rollback = args["<steps>"].AsInt; } }
public void Test_issue_126_defaults_not_parsed_correctly_when_tabs() { const string section = "Options:\n\t--foo=<arg> [default: bar]"; var expected = new Option[] { new Option(null, "--foo", 1, "bar") }; Assert.AreEqual(expected, Docopt.ParseDefaults(section)); }
private static void Main(string[] argv) { Console.OutputEncoding = Encoding.UTF8; IDictionary <string, ValueObject> args = new Docopt().Apply(Usage, argv, exit: true); string?mode = null; string modeConfigFilename = args["--mode-config"].ToString(); if (args["--mode"] != null && !args["--mode"].IsNullOrEmpty) { mode = args["--mode"].ToString(); if (!DefaultConfigs.ContainsKey(mode)) { Console.WriteLine( $"Unknown mode '{mode}', possible values: {string.Join(", ", DefaultConfigs.Keys)}"); Environment.Exit(1); } modeConfigFilename = modeConfigFilename.Replace("<mode>", mode); } if (args["start"].IsTrue) { Mode(mode !, args["--config"].ToString(), modeConfigFilename); } else if (args["testconfig"].IsTrue) { TestConfig(args["--config"].ToString(), mode, modeConfigFilename); } else if (args["gendefaultconfig"].IsTrue) { OutputDefaultConfig(mode, args["--outfile"]); } else if (args["regenjsonschemas"].IsTrue) { RegenerateJsonSchema(); } }
private void GetCommandLineConfiguration(string[] args) { var docopt = new Docopt(); IDictionary <string, ValueObject> res = docopt.Apply(Usage, args, help: true, exit: true); _ocdmModelExportPath = res["--modelExport"] == null ? _ocdmModelExportPath : res["--modelExport"].ToString(); _readerName = res["--reader"] == null ? _readerName : res["--reader"].ToString(); _writerName = res["--writer"] == null ? _writerName : res["--writer"].ToString(); if (res["--outputPath"] == null) { // do nothing, rely on default } else if (res["--outputPath"].ToString() == String.Empty) { _outputPath = @".\"; // current working directory } else { _outputPath = res["--outputPath"].ToString(); } _metadataPath = res["<inputFile>"] == null ? _metadataPath : res["<inputFile>"].ToString(); }
public async static Task Main(string[] args) { var usage = Resources.docopt; var arguments = new Docopt().Apply(usage, args, version: "Path Convert 1.0", exit: true); bool clipboard = arguments["--clipboard"].IsTrue; bool windows = arguments["--windows"].IsTrue; string path = arguments["<path>"]?.ToString(); if (clipboard && path == null) { path = await Clipboard.GetTextAsync(); } if (windows) { path = path.Replace('/', '\\'); } else { path = path.Replace(@"\\", "/"); path = path.Replace('\\', '/'); } if (clipboard) { await Clipboard.SetTextAsync(path); } Console.WriteLine(path); }
static void Main(string[] args) { Task.Run(async() => { try { var arguments = new Docopt().Apply(Usage, args, version: "Seq Enable AAD 0.1", exit: true); var server = arguments["<server>"].ToString(); var username = Normalize(arguments["--uname"]); var tenantId = Normalize(arguments["--tenantid"]); var clientId = Normalize(arguments["--clientid"]); var clientKey = Normalize(arguments["--clientkey"]); var authority = Normalize(arguments["--authority"]); await Run(server, username, tenantId, clientId, clientKey, authority); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine("seq-enable-aad: {0}", ex); Console.ResetColor(); Environment.Exit(-1); } }).Wait(); }
static void Main(string[] args) { Task.Run(async() => { try { var arguments = new Docopt().Apply(Usage, args, version: "Seq Signal Copy 0.1", exit: true); var src = arguments["<src>"].ToString(); var dst = arguments["<dst>"].ToString(); var srcKey = Normalize(arguments["--srckey"]); var dstKey = Normalize(arguments["--dstkey"]); await Run(src, srcKey, dst, dstKey); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine("signal-copy: {0}", ex); Console.ResetColor(); Environment.Exit(-1); } }).Wait(); }
internal static void Main(string[] args) { var container = ContainerProvider.Build(); var parameters = new Docopt().Apply(Usage, args, version: Version, exit: true); var appSettingsResult = SettingsParser.GetSettings(parameters); if (!appSettingsResult.IsSuccess) { Console.WriteLine(appSettingsResult.Error); return; } var appSettings = appSettingsResult.Value; var bitmap = container.Resolve <TagCreator>().DrawTag(appSettings.ReaderSettings, appSettings.DrawerSettings, appSettings.LayouterSettings); if (!bitmap.IsSuccess) { Console.WriteLine(bitmap.Error); return; } var saveResult = container.Resolve <IImageSaverFactory>().GetSaver(appSettings.ImageExt) .Save(bitmap.Value, appSettings.SavePath); if (!saveResult.IsSuccess) { Console.WriteLine(saveResult.Error); } Console.WriteLine("Ended successful"); }
public string Docopt(string doc, string cmdLine) { try { var arguments = new Docopt().Apply(doc, cmdLine); var dict = new Dictionary<string, object>(); foreach (var argument in arguments) { if (argument.Value == null) dict[argument.Key] = null; else if (argument.Value.IsList) { var l = new ArrayList(); foreach (var v in argument.Value.AsList) { if (v is ValueObject) l.Add(((v) as ValueObject).Value); else l.Add(v); } dict[argument.Key] = l; } else dict[argument.Key] = argument.Value.Value; } return JsonConvert.SerializeObject(dict); } catch (Exception) { return "\"user-error\""; } }
static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.LiterateConsole(outputTemplate: "seq-import {Level} {Message}{NewLine}{Exception}") .CreateLogger(); Task.Run(async() => { try { var propertyArgs = args.Where(s => s.StartsWith("--p:", StringComparison.OrdinalIgnoreCase) || s.StartsWith("--property:", StringComparison.OrdinalIgnoreCase)).ToList(); var cleanedArgs = args.Except(propertyArgs).ToArray(); var additionalTags = ParseAdditionalTagsToDictionary(propertyArgs); var arguments = new Docopt().Apply(Usage, cleanedArgs, version: "Seq Import 0.1", exit: true); var server = arguments["<server>"].ToString(); var file = Normalize(arguments["<file>"]); var apiKey = Normalize(arguments["--apikey"]); await Run(server, apiKey, file, additionalTags, 256 * 1024, 1024 * 1024); } catch (Exception ex) { Log.Error(ex, "Could not complete import"); Environment.Exit(-1); } }).Wait(); }
static void Main(string[] args) { Task.Run(async() => { try { var arguments = new Docopt().Apply(Usage, args, version: "Seq Query 0.1", exit: true); var server = arguments["<server>"].ToString(); var query = Normalize(arguments["<query>"]); var apiKey = Normalize(arguments["--apikey"]); var @from = Normalize(arguments["--from"]); var to = Normalize(arguments["--to"]); await Run(server, apiKey, query, from, to); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine("seq-query: {0}", ex); Console.ResetColor(); Environment.Exit(-1); } }).Wait(); }
private static Dictionary <string, string> ParseArguments(string[] args) { var parsedArguments = new Dictionary <string, string>(); var arguments = new Docopt().Apply(Usage, args, exit: true); parsedArguments.Add("--input", arguments["--input"].ToString()); parsedArguments.Add("--output", arguments["--output"].ToString()); var inputFormat = parsedArguments["--input"] .Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Last(); parsedArguments.Add("--fileFormat", inputFormat); if (arguments["--sqrt"].IsTrue) { parsedArguments.Add("--form", "sqrt"); } else if (arguments["--trgl"].IsTrue) { parsedArguments.Add("--form", "trgl"); } else { parsedArguments.Add("--form", "circle"); } parsedArguments.Add("--bgColor", arguments["--bgColor"] != null ? arguments["--bgColor"].ToString() : "#FFFFFF"); parsedArguments.Add("--textColor", arguments["--textColor"] != null ? arguments["--textColor"].ToString() : "#000000"); return(parsedArguments); }
private static void Main(string[] args) { var arguments = new Docopt().Apply(usage, args, exit: true); Setup(); if (arguments["save"].IsTrue) { SaveBob(); } if (arguments["load"].IsTrue) { LoadBob(arguments["<id>"].ToString()); } if (arguments["list"].IsTrue) { ListBobs(); } if (arguments["add_hometown"].IsTrue) { SaveBobsHometown(arguments["<id>"].ToString(), arguments["<hometown>"].ToString()); } }
static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Console() .CreateLogger(); TaskScheduler.UnobservedTaskException += (s, e) => Log.Fatal(e.Exception, "Unobserved task exception"); try { var arguments = new Docopt().Apply(Usage, args, version: "Seq Tail 0.2", exit: true); var server = arguments["<server>"].ToString(); var apiKey = Normalize(arguments["--apikey"]); var filter = Normalize(arguments["--filter"]); var cancel = new CancellationTokenSource(); Console.WriteLine("Tailing, press Ctrl+C to exit."); Console.CancelKeyPress += (s, a) => cancel.Cancel(); var run = Task.Run(() => Run(server, apiKey, filter, cancel)); run.GetAwaiter().GetResult(); } catch (Exception ex) { Log.Fatal(ex, "Tailing aborted"); Environment.Exit(-1); } }
static void Main(string[] args) { Console.WriteLine(string.Empty); var desc = " Foreach"; var fontArr = System.Text.Encoding.Default.GetBytes(ContessaFont.CONTESSA); FigletFont font = FigletFont.Load(fontArr); Figlet figlet = new Figlet(font); Console.WriteLine(figlet.ToAscii(desc), Color.Blue); Console.WriteFormatted("Turn easy the execution of loops, for and batch command line programs using statments like ", Color.White); Console.WriteLineFormatted("foreach ", Color.Green); try { var multiplierIndex = args.ToList().IndexOf("*"); if (multiplierIndex == -1) { throw new DocoptNet.DocoptInputErrorException("You must to specify * multiplier character"); } var beforeArgs = SubArray <string>(args, 0, multiplierIndex); var afterArgs = SubArray <string>(args, multiplierIndex + 1, args.Length - multiplierIndex - 1); var arguments = new Docopt().Apply(Usage.SHORT_HELP, beforeArgs, version: "Foreach", exit: false); try { Run(afterArgs, arguments).Wait(); Environment.Exit(0); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Environment.Exit(2); } } catch (Exception e) { Console.WriteLine(Usage.SHORT_HELP); Console.WriteLine(string.Empty); //Console.WriteLine($@" > To convert all wav files in currenty folder (and sub-directories recursivelly) and convert to mp3 format"); //Console.WriteLineFormatted($@" ffmpeg-batch -s /**/*.wav -o mp3", Color.Green); //Console.WriteLine(string.Empty); //Console.WriteLine($@" > To convert all wma files in c:\music and convert to mp3 format"); //Console.WriteLineFormatted($@" ffmpeg-batch -s c:\music\*.wma -o mp3", Color.Green); Console.WriteLine("Install/Uninstall tool:"); Console.WriteLine($@" > To install tool from system"); Console.WriteLineFormatted($@" dotnet tool install -g foreach", Color.Green); Console.WriteLine(string.Empty); Console.WriteLine($@" > To uninstall tool from system"); Console.WriteLineFormatted($@" dotnet tool uninstall -g foreach", Color.Green); Environment.Exit(1); } }
private static void Main(string[] argv) { Console.OutputEncoding = Encoding.UTF8; IDictionary <string, ValueObject> args = new Docopt().Apply(Usage, argv, exit: true); string?mode = null; string modeConfigFilename = args["--mode-config"].ToString(); if (args["--mode"] is { IsNullOrEmpty : false })
public void Test_issue_40_help() { var message = ""; var d = new Docopt(); d.PrintExit += (s, e) => message = e.Message; d.Apply("usage: prog --help-commands | --help", "--help"); StringAssert.StartsWith("usage", message); }
public static void Main(string[] args) { var arguments = new Docopt().Apply(USAGE, args, version: "serve 0.0.1", exit: true); var register = arguments["--register"]?.IsTrue == true; var unregister = arguments["--unregister"]?.IsTrue == true; if (register) { if (OperatingSystem.IsWindows()) { RegisterContextMenu(); Console.WriteLine("Context menu items added."); } else { Console.WriteLine("--register is not supported on this operating system."); } Environment.Exit(0); } if (unregister) { if (OperatingSystem.IsWindows()) { UnregisterContextMenu(); Console.WriteLine("Context menu items removed."); } else { Console.WriteLine("--unregister is not supported on this operating system."); } Environment.Exit(0); } var path = arguments["<path>"] != null ? arguments["<path>"].ToString() : Directory.GetCurrentDirectory(); Environment.CurrentDirectory = path; var httpsPort = arguments["--port"] != null ? arguments["--port"].AsInt : DefaultHttpsPort; var httpPort = httpsPort - 1; WebHost.CreateDefaultBuilder() .UseStartup <Startup>() .UseKestrel() .UseContentRoot(path) .UseWebRoot(path) .UseUrls($"http://localhost:{httpPort}", $"https://localhost:{httpsPort}") .Build() .Run(); }
public void Required() { var expected = new Dictionary<string, ValueObject> { {"add", new ValueObject(true)} }; var actual = new Docopt().Apply("Usage: prog add", "add"); Assert.AreEqual(expected, actual); }
public MainArgs(string[] argv) { var version = Assembly.GetEntryAssembly().GetName().Version.ToString(); var args = new Docopt().Apply(usage, argv, version: version, exit: true); IsVersionRequest = bool.Parse(args["--version"]?.ToString()); Version = args["--version"]?.ToString(); }
public void Optional_no_args() { var expected = new Dictionary<string, ValueObject> { {"add", new ValueObject(false)} }; var actual = new Docopt().Apply("Usage: prog [add]", ""); Assert.AreEqual(expected, actual); }
public void Flag_one_or_more() { var expected = new Dictionary<string, ValueObject> { {"-v", new ValueObject(6)} }; var actual = new Docopt().Apply("Usage: prog -v...", "-vvvvvv"); Assert.AreEqual(expected, actual); }
public void Test_parse_argv_opt_with_arg() { Assert.AreEqual(new[] { new Option("-h", null, 0, new ValueObject(true)), new Option("-f", "--file", 1, "f.txt") }, Docopt.ParseArgv(TS("-h --file f.txt"), _options)); }
public void Test_parse_argv_short_and_long() { Assert.AreEqual(new[] { new Option("-h", null, 0, new ValueObject(true)), new Option("-v", "--verbose", 0, new ValueObject(true)) }, Docopt.ParseArgv(TS("-h --verbose"), _options)); }
public CloudSettings CreateCloudSettings(string[] args) { var arguments = new Docopt().Apply(usage, args, exit: true); var point = new Point(int.Parse(arguments["--x_coord"].Value.ToString()), int.Parse(arguments["--y_coord"].Value.ToString())); var radius = int.Parse(arguments["--radius"].Value.ToString()); radius = radius == 0 ? int.MaxValue : radius; return(new CloudSettings(point, radius)); }
public void Simple_flag() { var expected = new Dictionary<string, ValueObject> { {"-v", new ValueObject(true)} }; var actual = new Docopt().Apply("Usage: prog [-v]", "-v"); Assert.AreEqual(expected, actual); }
public void Flag_3() { var expected = new Dictionary<string, ValueObject> { {"-v", new ValueObject(3)} }; var actual = new Docopt().Apply("Usage: prog [-v | -vv | -vvv]", "-vvv"); Assert.AreEqual(expected, actual); }
public void Expect_one_arg() { var expected = new Dictionary<string, ValueObject> { {"<p>", new ValueObject(new[] {"this"})} }; var actual = new Docopt().Apply("usage: prog [<p>]...\n\n<p> [default: x y]", "this"); Assert.AreEqual(expected, actual); }
public void Test_issue_68_options_shortcut_does_not_include_options_in_usage_pattern() { var args = new Docopt().Apply("usage: prog [-ab] [options]\noptions: -x\n -y", "-ax"); Assert.True(args["-a"].IsTrue); Assert.True(args["-b"].IsFalse); Assert.True(args["-x"].IsTrue); Assert.True(args["-y"].IsFalse); }
public void Expect_empty_collection() { var expected = new Dictionary<string, ValueObject> { {"<p>", new ValueObject(new string[0])} }; var actual = new Docopt().Apply("usage: prog [<p>]...\n\n<p> [default: x y]", ""); Assert.AreEqual(expected, actual); }
public void Expect_none() { var expected = new Dictionary<string, ValueObject> { {"<p>", null} }; var actual = new Docopt().Apply("usage: prog [<p>]\n\n<p> [default: x]", ""); Assert.AreEqual(expected, actual); }
public void Expect_default_value() { var expected = new Dictionary<string, ValueObject> { {"--data", new ValueObject(new[] {"x"})} }; var actual = new Docopt().Apply("Usage: prog [--data=<data>...]\n\nOptions:\n\t-d --data=<arg> Input data [default: x]", ""); Assert.AreEqual(expected, actual); }
public TextSettings CreateTextSettings(string[] args, IMorphAnalyzer analyzer) { var arguments = new Docopt().Apply(usage, args, exit: true); var path = arguments["--file"].Value.ToString(); var filter = arguments["--filter"].Value.ToString(); var partsOfSpeech = arguments["--exclude"].Value.ToString(); var partOfSpeech = arguments["--print_only"].Value.ToString(); return(new TextSettings(path, filter, partsOfSpeech, partOfSpeech, analyzer)); }
public void Expect_default_value() { var expected = new Dictionary <string, ValueObject> { { "--data", new ValueObject(new[] { "x" }) } }; var actual = new Docopt().Apply("Usage: prog [--data=<data>...]\n\nOptions:\n\t-d --data=<arg> Input data [default: x]", ""); Assert.AreEqual(expected, actual); }
public void Optional_either_second_specified() { var expected = new Dictionary<string, ValueObject> { {"add", new ValueObject(false)}, {"rm", new ValueObject(true)} }; var actual = new Docopt().Apply("Usage: prog (add|rm)", "rm"); Assert.AreEqual(expected, actual); }
public void Test_issue_40_same_prefix() { var expected = new Dictionary<string, ValueObject> { {"--aabb", new ValueObject(false)}, {"--aa", new ValueObject(true)} }; var actual = new Docopt().Apply("usage: prog --aabb | --aa", "--aa"); Assert.AreEqual(expected, actual); }
public void Flag_one_or_more() { var expected = new Dictionary <string, ValueObject> { { "-v", new ValueObject(6) } }; var actual = new Docopt().Apply("Usage: prog -v...", "-vvvvvv"); Assert.AreEqual(expected, actual); }
public void Flag_long_2() { var expected = new Dictionary <string, ValueObject> { { "--ver", new ValueObject(2) } }; var actual = new Docopt().Apply("Usage: prog [--ver --ver]", "--ver --ver"); Assert.AreEqual(expected, actual); }
public void Simple_flag() { var expected = new Dictionary <string, ValueObject> { { "-v", new ValueObject(true) } }; var actual = new Docopt().Apply("Usage: prog [-v]", "-v"); Assert.AreEqual(expected, actual); }
public void Flag_3() { var expected = new Dictionary <string, ValueObject> { { "-v", new ValueObject(3) } }; var actual = new Docopt().Apply("Usage: prog [-v | -vv | -vvv]", "-vvv"); Assert.AreEqual(expected, actual); }
public void Match_opt_first() { var expected = new Dictionary<string, ValueObject> { {"--opt", new ValueObject(true)}, {"<args>", new ValueObject(new[]{"this", "that"})} }; var actual = new Docopt().Apply("usage: prog [--opt] [<args>...]", "--opt this that"); Assert.AreEqual(expected, actual); }
public void No_double_dash() { var expected = new Dictionary<string, ValueObject> { {"-o", new ValueObject(true)}, {"<arg>", new ValueObject("1")}, {"--", new ValueObject(false)} }; var actual = new Docopt().Apply("usage: prog [-o] [--] <arg>\nOptions: -o", "-o 1"); Assert.AreEqual(expected, actual); }
public void Match_opt_and_arg() { var expected = new Dictionary<string, ValueObject> { {"-v", new ValueObject(true)}, {"A", new ValueObject("arg")} }; var actual = new Docopt().Apply(@"Usage: prog [-v] A Options: -v Be verbose.", "-v arg"); Assert.AreEqual(expected, actual); }
public void Short_and_long_option_lead_to_only_one_property() { const string usage = @"Usage: naval_fate -h | --help Options: -h --help Show this screen."; var generatedCode = new Docopt().GenerateCode(usage); Assert.AreEqual(1, Regex.Matches(generatedCode, "OptHelp").Count); }
public void Should_return_duplicates_so_caller_knows_which_args_are_after_each_command() { const string USAGE = @"Test for duplicate commands and arguments. Usage: prog command ARG <myarg> [OPTIONALARG] [-o -s=<arg> --long=ARG --switch] prog command ARG <myarg> [OPTIONALARG] [-o -s=<arg> --long=ARG --switch] FILE... prog diff-command <myarg> [OPTIONALARG] ARG Options: -o --option Short & long option flag, the long will be used as it's more descriptive. -s=<arg> Short option with arg. --long=ARG Long option with arg. --switch Long switch. "; var actual = new Docopt().GetNodes(USAGE); CollectionAssert.AreEqual( new Node[] { new CommandNode ("command"), new ArgumentNode("ARG", ValueType.String), new ArgumentNode("<myarg>", ValueType.String), new ArgumentNode("OPTIONALARG", ValueType.String), new OptionNode ("option", ValueType.Bool), new OptionNode ("s", ValueType.String), new OptionNode ("long", ValueType.String), new OptionNode ("switch", ValueType.Bool), new CommandNode ("command"), new ArgumentNode("ARG", ValueType.String), new ArgumentNode("<myarg>", ValueType.String), new ArgumentNode("OPTIONALARG", ValueType.String), new OptionNode ("option", ValueType.Bool), new OptionNode ("s", ValueType.String), new OptionNode ("long", ValueType.String), new OptionNode ("switch", ValueType.Bool), new ArgumentNode("FILE", ValueType.List), new CommandNode ("diff-command"), new ArgumentNode("<myarg>", ValueType.String), new ArgumentNode("OPTIONALARG", ValueType.String), new ArgumentNode("ARG", ValueType.String), }, actual); }
public void Should_get_nodes() { const string USAGE = @"Test host app for T4 Docopt.NET Usage: prog command ARG <myarg> [OPTIONALARG] [-o -s=<arg> --long=ARG --switch] prog files FILE... Options: -o --opt Short switch with a longer name. The longer name is the ""main"" one. -s=<arg> Short option with arg. --long=ARG Long option with arg. --switch Long switch. [default: false] Explanation: This is a test ""usage"". "; var actual = new Docopt().GetNodes(USAGE); CollectionAssert.AreEqual( new Node[] { new CommandNode ("command"), new ArgumentNode("ARG", ValueType.String), new ArgumentNode("<myarg>", ValueType.String), new ArgumentNode("OPTIONALARG", ValueType.String), new OptionNode ("opt", ValueType.Bool), new OptionNode ("s", ValueType.String), new OptionNode ("long", ValueType.String), new OptionNode ("switch", ValueType.Bool), new CommandNode ("files"), new ArgumentNode("FILE", ValueType.List), }, actual); }
public void Display_help() { var message = ""; var errorCode = 0; var d = new Docopt(); d.PrintExit += (s, e) => { message = e.Message; errorCode = e.ErrorCode; }; d.Apply(DOC, "--help"); StringAssert.StartsWith("Usage", message); Assert.AreEqual(0, errorCode); }
public void Test_issue_59_assign_empty_string_to_short() { var expected = new Dictionary<string, ValueObject> { {"-l", new ValueObject("")} }; var actual = new Docopt().Apply("usage: prog -l <a>\noptions: -l <a>", new[] {"-l", ""}); Assert.AreEqual(expected, actual); }
public void Should_exit_error_code_1() { var message = ""; var errorCode = 0; var d = new Docopt(); d.PrintExit += (s, e) => { message = e.Message; errorCode = e.ErrorCode; }; d.Apply(DOC, "--fake", exit:true); StringAssert.StartsWith("Usage", message); Assert.AreEqual(1, errorCode); }
public void Flag_long_2() { var expected = new Dictionary<string, ValueObject> { {"--ver", new ValueObject(2)} }; var actual = new Docopt().Apply("Usage: prog [--ver --ver]", "--ver --ver"); Assert.AreEqual(expected, actual); }
public void Should_exit_error_code_1() { var message = ""; var errorCode = 0; var d = new Docopt(); d.PrintExit += (s, e) => { message = e.Message; errorCode = e.ErrorCode; }; d.Apply(DOC, "--fake", exit:true); StringAssert.StartsWith("Usage", message); Assert.AreEqual(1, errorCode, "Should exit with error code 1 when exit=true and invalid args provided"); }
public void Test_issue_59_assign_empty_string_to_long() { var expected = new Dictionary<string, ValueObject> { {"--long", new ValueObject("")} }; var actual = new Docopt().Apply("usage: prog --long=<a>", "--long="); Assert.AreEqual(expected, actual); }
public void Match_one_opt_with_arg() { var expected = new Dictionary<string, ValueObject> { {"-v", new ValueObject(true)}, {"-q", new ValueObject(false)}, {"-r", new ValueObject(false)}, {"--help", new ValueObject(false)}, {"FILE", new ValueObject("file.py")}, {"INPUT", null}, {"OUTPUT", null} }; var actual = new Docopt().Apply(DOC, "-v file.py"); Assert.AreEqual(expected, actual); }