private void GetInputValues(string[] args) { GetOpt opt = new GetOpt(args,"vi:o:c:t:"); Arg arg = opt.NextArg(); while(arg != null) { switch(arg.Flag) { case "-v": verbose = true; break; case "-i": inputFolder = GetFolderPath(arg, "Invalid input folder path."); break; case "-o": outputFolder = GetFolderPath(arg, "Invalid output folder path"); break; case "-c": connectionString = arg.Parameter.Trim(); break; case "-t": providerType = arg.Parameter.Trim(); break; default: PrintUsage(); return; } arg = opt.NextArg(); } }
public void ShowHelpIfNoArgumentsInMultiCommandMode() { var calc = new Calculator(); using (var c = new CaptureConsoleOutput()) { var e = GetOpt.Run(calc, new string[] { }); Assert.AreEqual(0, e); Assert.IsTrue(c.output.ToString().StartsWith("Usage:")); } }
public void OptionsInSubcommandsAreConsidered() { var commands = new Commands(); using (var c = new CaptureConsoleOutput()) { Assert.AreEqual(0, GetOpt.Run(commands, new[] { "calculator", "--print", "sum", "1", "2", "3" })); Assert.AreEqual(true, commands.Calculator.Print); Assert.AreEqual(6.0, commands.Calculator.Result); } }
public void BoolWrongArguments() { void CheckWrongBoolArguments(IList <string> arguments) { Assert.ThrowsException <GetOptException>(() => GetOpt.Parse(arguments, TestOptions.Standard)); } CheckWrongBoolArguments(new[] { "-eTrue" }); CheckWrongBoolArguments(new[] { "-e", "False" }); CheckWrongBoolArguments(new[] { "--show-minor-errors=dummy" }); }
public void ShowHelp() { var calc = new Calculator(); using (var c = new CaptureConsoleOutput()) { var e = GetOpt.Run(calc, new[] { "--help" }); Assert.AreEqual(0, e); Assert.IsTrue(c.output.ToString().StartsWith("Usage:")); } }
public void WorkingDayInvalid() { void CheckForInvalidEnum(IEnumerable <string> arguments) { Assert.ThrowsException <GetOptException>(() => GetOpt.Parse(arguments, TestOptions.Standard)); } CheckForInvalidEnum(new[] { "-wMOnday" }); CheckForInvalidEnum(new[] { "-w", "tuesday" }); CheckForInvalidEnum(new[] { "--work-day=bullshit" }); }
public void AbbreviateCommands() { var c = new Commands(); using (var o = new CaptureConsoleOutput()) { var e = GetOpt.Run(c, new[] { "c", "s", "1", "1", "--pr", "-p" }); Assert.AreEqual(e, 0); Assert.AreEqual(2.0, c.Calculator.Result); } }
public void ArgumentMissing() { var co = new TestCommandObject(); var exitCode = GetOpt.Run(new[] { "add", "1", }, co); Assert.That(exitCode, Is.Not.EqualTo(0)); }
public void WorkingDayOutOfRange() { void CheckForOutOfRange(IEnumerable <string> arguments) { Assert.ThrowsException <GetOptException>(() => GetOpt.Parse(arguments, TestOptions.Standard)); } CheckForOutOfRange(new[] { "-wSaturday" }); CheckForOutOfRange(new[] { "-w", "Sunday" }); CheckForOutOfRange(new[] { "--work-day=Sunday" }); }
public void TestCustomValidationSuccess() { GetOpt.Parse ( options, null, "-r127.0.0.1", "-r127.0.0.256", // this is a valid hostname according to RFC 1123 (pray that your gethostbyname knows that) "--remote-host=www.xn--hochsttter-v5a.de", "-r", "2001:db8::dead:beef:FACE:B00C", "--remote-host", "::FFFF:192.168.0.1" ); }
public void BasicCommand() { var calc = new Calculator(); var e = GetOpt.Run(calc, new[] { "add", "1", "1" }); Assert.AreEqual(0, e); Assert.AreEqual(2.0, calc.Result); e = GetOpt.Run(calc, new[] { "sum", "1", "2", "3" }); Assert.AreEqual(0, e); Assert.AreEqual(6.0, calc.Result); }
public void DefaultCommandWithoutParameters() { var o = new WithDefaultCommandNoParameters(); int exitCode = 0; var(output, error) = CaptureOutput(() => { exitCode = GetOpt.Run(new string[] { "1", "1" }, o); }); Console.WriteLine(error); Assert.AreEqual(ExitCode.CommandLineError, exitCode); }
public void WorkDayArgumentMissing() { void CheckForMissingArgument(IEnumerable <string> arguments) { Assert.ThrowsException <GetOptException>(() => GetOpt.Parse(arguments, TestOptions.Standard)); } CheckForMissingArgument(new[] { "-w" }); CheckForMissingArgument(new[] { "--work-day" }); CheckForMissingArgument(new[] { "--work-day", "--", "Monday" }); CheckForMissingArgument(new[] { "-w", "--", "Tuesday" }); }
public void HelpForDefaultCommandNoParameters() { var o = new WithDefaultCommandNoParameters(); var(output, error) = CaptureOutput(() => { var exitCode = GetOpt.Run(new string[] { "-h" }, o); Assert.AreEqual(ExitCode.HelpDisplayed, exitCode); }); Console.WriteLine(output); Assert.That(!output.Contains("do-something")); }
//[ExpectedException(typeof(CommandLineException), ExpectedMessage = "Missing parameters")] public void StringParamPlusMissingFilenameShouldGenerateError() { var opts = new GetOpt("desc", new[] { new CommandLineOption('s', null, "a param", ParameterType.String, null), new CommandLineOption("filename", ParameterType.String, null), }); var exception = Assert.Throws <CommandLineException>(() => opts.ParseOptions(new[] { "-s", "sparam" })); Assert.AreEqual("Missing parameters", exception.Message); }
public void TestCustomValidationFail() { var getOpt = new GetOpt(options, Parameters.Default); void CheckRemoteHost(params string[] arguments) { Assert.ThrowsException <GetOptException>(() => getOpt.Parse(arguments)); } CheckRemoteHost("-r127.0.0.1/32"); CheckRemoteHost("-r", "2001:db8::dead:beef:FACE:B00K"); CheckRemoteHost("--remote-host", "_sip._udp.dus.net"); CheckRemoteHost("--remote-host=www.hochstätter.de"); }
static void Main(string[] args) { GetOpt opts = configOpts(); opts.ParseOptions(args); if (projectOpt.Equals(String.Empty)) { opts.ShowUsage(); } else { generate(); } }
/// <summary> /// Parse the command line and exit the process as needed. /// </summary> private static void ParseCmdLine(string[] args) { try { int c = 0; while ((c = GetOpt.GetOptions(args, "e:i:M:S:")) != -1) { switch ((char)c) { // Export switch. case 'e': ExportKwsPath = GetOpt.Text; if (ExportKwsPath == "" || ExportKwsPath == null) { throw new Exception("empty export path"); } break; // Import switch. case 'i': ImportKwsPath = GetOpt.Text; if (ImportKwsPath == "" || ImportKwsPath == null) { throw new Exception("empty import path"); } break; // Fatal error message switch. case 'M': WmUi.TellUser(GetOpt.Text, KwmStrings.Kwm + " fatal error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); break; case '?': case ':': default: throw new Exception("invalid option"); } } } catch (Exception ex) { Console.WriteLine("Option error: " + ex.Message); usage(); Environment.Exit(1); } }
// entry-point comment /// entry-point comment public static void Main(string[] args) { int nArgs; bool bSortSize = false; if (args != null && (nArgs = args.Length) > 0) { int c; bool bSubtotal, bAll, bDirsOnly; bSubtotal = bAll = bDirsOnly = false; // bDirsOnly=true; while ((c = GetOpt.getopt(args, "adhsS")) >= 0) { switch (c) { case 'a': bAll = true; break; case 'd': bDirsOnly = !bDirsOnly; break; case 'h': usage(0); break; case 's': bSubtotal = true; break; case 'S': bSortSize = true; break; default: usage(1); break; } } if (GetOpt.optind < nArgs) { for (int i = GetOpt.optind; i < nArgs; i++) { doArg(args[i], bSubtotal, bAll, bSortSize, bDirsOnly); } } else { doArg(Directory.GetCurrentDirectory(), bSubtotal, bAll, bSortSize, bDirsOnly); } } else { doArg(Directory.GetCurrentDirectory(), false, false, bSortSize, false); } }
public void Run() { var co = new TestCommandObject(); var exitCode = GetOpt.Run(new[] { "add", "1", "--name", "Alice", "2", "subtract", "3", "2", "greet" }, co); Assert.That(exitCode, Is.EqualTo(0)); Assert.That(co.Name, Is.EqualTo("Alice")); }
public void CanUseEqualToAssignValues() { string s = null; int num = 0; var opts = new GetOpt("desc", new[] { new CommandLineOption('s', null, "a param", ParameterType.String, o => s = (string)o), new CommandLineOption('\0', "num", "a number", ParameterType.Integer, o => num = (int)o), }); // Act opts.ParseOptions(new[] { "--num=32", "-s=sparam" }); // Assert Assert.AreEqual("sparam", s); Assert.AreEqual(32, num); }
public void CanParseMultipleShortParametersSeparated() { bool a = false, b = true, c = false; var opts = new GetOpt("desc", new[] { new CommandLineOption('a', null, "a param", ParameterType.None, o => a = true), new CommandLineOption('b', null, "a param", ParameterType.None, o => b = false), new CommandLineOption('c', null, "a param", ParameterType.None, o => c = true), }); // Act opts.ParseOptions(new[] { "foo", "-a", "bar", "-b", "-c" }); // Assert Assert.AreEqual(true, a); Assert.AreEqual(false, b); Assert.AreEqual(true, c); }
private static void Main(string[] args) { var opts = new GetOpt("This application clones a website into a local folder, rewriting URLs as needed.", new[] { new CommandLineOption('o', "outputPath", "The folder where the downloaded pages will be written", ParameterType.String, value => SETTINGS.OutputPath = (string)value), } ); opts.ParseOptions(args); var downloader = new SiteDownloader(); if (opts.AdditionalParameters.Any()) { downloader.Download(opts.AdditionalParameters[0], SETTINGS); } }
public void CanParseSeveralUnnamed() { string s = null, f = null; var opts = new GetOpt("desc", new[] { new CommandLineOption("filename", ParameterType.String, o => s = (string)o), new CommandLineOption("filename2", ParameterType.String, o => f = (string)o), }); // Act opts.ParseOptions(new[] { "string1", "string2", "ignored" }); // Assert Assert.AreEqual("string1", s); Assert.AreEqual("string2", f); Assert.AreEqual(1, opts.AdditionalParameters.Count); Assert.AreEqual("ignored", opts.AdditionalParameters[0]); }
public void TestBoolOption() { GetOpt parser = new GetOpt(); parser.AddBoolOption(flags: new string[] { "-h", "-help" }); Assert.False(parser.IsSet("-h"), "-h option should not be set"); Assert.False(parser.IsSet("-help"), "-help option should not be set"); string[] rest = parser.Parse( "-not option -help -file name bla bla -fbla".Split(" ")); Assert.True(parser.IsSet("-h"), "-h option should be set"); Assert.True(parser.IsSet("-help"), "-help option should be set"); parser.Reset(); Assert.False(parser.IsSet("-h"), "-h option should not be set"); Assert.False(parser.IsSet("-help"), "-help option should not be set"); }
static void Main(string [] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 myForm = new Form1(); // For the sake of this example, we're just printing the arguments to the console. // for (int i = 0; i < args.Length; i++) // { // Console.WriteLine("args[{0}] == {s}", i, args[i]); //} // Tim hieu va phan tich bang GetOpt string paramFileName = string.Empty; var opt = new GetOpt("Chuong trinh ky ten", new[] { new CommandLineOption('s', "save", "Luu file voi ten da duoc quy uoc", ParameterType.String, o => paramFileName = (string)o), }); myForm.DestinationFileName = paramFileName; Application.Run(myForm); }
public void CanShowHelp() { // Arrange var opts = new GetOpt("desc", new[] { new CommandLineOption('a', null, "a param", ParameterType.None, null), new CommandLineOption('b', "btext", "a param", ParameterType.None, null), new CommandLineOption('c', null, "a param", ParameterType.None, null), }); // Act opts.ShowUsage(false); // Assert var output = this.StdOutLines; Assert.AreEqual(8, output.Length); Assert.AreEqual("desc", output[0]); Assert.IsTrue(output[1].StartsWith("Usage: ")); Assert.IsTrue(output[1].EndsWith(" -abch")); }
public void WorkingDayStandardTests() { var commandLine = new[] { "-wFriday", "--work-day=Wednesday", "-vwMonday", "-w", "Tuesday", "Friday", "-vw", "Tuesday", "--work-day", "Thursday", "--", "-wSaturday", "--work-day=Sunday" }; var result = GetOpt.Parse(commandLine, TestOptions.Standard); Assert.AreEqual(3, result.NonOptions.Count); Assert.AreEqual("Friday", result.NonOptions[0]); Assert.AreEqual("-wSaturday", result.NonOptions[1]); Assert.AreEqual("--work-day=Sunday", result.NonOptions[2]); var options = result.Options; Assert.AreEqual(8, result.Options.Count); Assert.AreSame(TestOptions.Standard.Single(o => o.ShortName == 'w'), options[0].Definition); Assert.AreEqual(WeekDay.Friday, options[0].Argument); Assert.AreSame(TestOptions.Standard.Single(o => o.ShortName == 'w'), options[1].Definition); Assert.AreEqual(WeekDay.Wednesday, options[1].Argument); Assert.AreSame(TestOptions.Standard.Single(o => o.ShortName == 'v'), options[2].Definition); Assert.IsNull(options[2].Argument); Assert.AreSame(TestOptions.Standard.Single(o => o.ShortName == 'w'), options[3].Definition); Assert.AreEqual(WeekDay.Monday, options[3].Argument); Assert.AreSame(TestOptions.Standard.Single(o => o.ShortName == 'w'), options[4].Definition); Assert.AreEqual(WeekDay.Tuesday, options[4].Argument); Assert.AreSame(TestOptions.Standard.Single(o => o.ShortName == 'v'), options[5].Definition); Assert.IsNull(options[5].Argument); Assert.AreSame(TestOptions.Standard.Single(o => o.ShortName == 'w'), options[6].Definition); Assert.AreEqual(WeekDay.Tuesday, options[6].Argument); Assert.AreSame(TestOptions.Standard.Single(o => o.ShortName == 'w'), options[6].Definition); Assert.AreEqual(WeekDay.Thursday, options[7].Argument); }
private void Principal(string[] args) { try { GetOpt getOpt = new GetOpt(args, new CommandArgument[] { intCommand, doubleCommand, bigIntCommand, maxLimit }, new CommandConstraits[] { constraints }); //We check if the value is not null because they are initialised to null. We can cast inside the if statement if //the value does have aa value if (doubleCommand.Value != null) { WriteLine("Execution of the double command..."); } if (intCommand.Value != null) { WriteLine("Execution of the int command..."); } if (bigIntCommand.Value != null) { WriteLine("Execution of the bigInt command..."); } if (maxLimit.Value != null) { //We can cast here because we know the command has a value and it needs to respect the TypeCode pass to the constructor int limit = (int)maxLimit.Value; WriteLine(limit); } } catch (OptionException e) { //The exception information needs to be more precise, right i dont pass any relavant information when i throw a new exception Write(e.OptionName + " " + e.Message); } }
public void TestAttributesSuccess() { var getOpt = new GetOpt(this); Assert.AreEqual(3, getOpt.OptionDefinitions.Count); getOpt.Parse ( "-vlC:\\Temp\\Logfile.txt", "-nroot@localhost", "[email protected]", "-n", "*****@*****.**" ); var help = getOpt.GetHelp(); Assert.IsTrue(verbose); Assert.AreEqual("C:\\Temp\\Logfile.txt", LogFile); Assert.AreEqual(3, EmailNotifications.Count); Assert.IsTrue(EmailNotifications.Contains("root@localhost")); Assert.IsTrue(EmailNotifications.Contains("*****@*****.**")); Assert.IsTrue(EmailNotifications.Contains("*****@*****.**")); }
private void GetInputValues(string[] args) { GetOpt opt = new GetOpt(args, "vi:o:c:t:"); Arg arg = opt.NextArg(); while (arg != null) { switch (arg.Flag) { case "-v": verbose = true; break; case "-i": inputFolder = GetFolderPath(arg, "Invalid input folder path."); break; case "-o": outputFolder = GetFolderPath(arg, "Invalid output folder path"); break; case "-c": connectionString = arg.Parameter.Trim(); break; case "-t": providerType = arg.Parameter.Trim(); break; default: PrintUsage(); return; } arg = opt.NextArg(); } }
public Program(string[] args) { JabberClient jc = new JabberClient(); jc.OnReadText += new Bedrock.TextHandler(jc_OnReadText); jc.OnWriteText += new Bedrock.TextHandler(jc_OnWriteText); jc.OnError += new Bedrock.ExceptionHandler(jc_OnError); jc.OnStreamError += new Jabber.Protocol.ProtocolHandler(jc_OnStreamError); jc.AutoReconnect = 3f; GetOpt go = new GetOpt(this); try { go.Process(args); } catch (ArgumentException) { go.UsageExit(); } if (untrustedOK) jc.OnInvalidCertificate += new System.Net.Security.RemoteCertificateValidationCallback(jc_OnInvalidCertificate); JID j = new JID(jid); jc.User = j.User; jc.Server = j.Server; jc.NetworkHost = networkHost; jc.Port = port; jc.Resource = "Jabber.Net Console Client"; jc.Password = pass; jc.AutoStartTLS = TLS; jc.AutoPresence = initialPresence; if (certificateFile != null) { jc.SetCertificateFile(certificateFile, certificatePass); Console.WriteLine(jc.LocalCertificate.ToString(true)); } if (boshURL != null) { jc[Options.POLL_URL] = boshURL; jc[Options.CONNECTION_TYPE] = ConnectionType.HTTP_Binding; } if (register) { jc.AutoLogin = false; jc.OnLoginRequired += new Bedrock.ObjectHandler(jc_OnLoginRequired); jc.OnRegisterInfo += new RegisterInfoHandler(this.jc_OnRegisterInfo); jc.OnRegistered += new IQHandler(jc_OnRegistered); } CapsManager cm = new CapsManager(); cm.Stream = jc; cm.Node = "http://cursive.net/clients/ConsoleClient"; Console.WriteLine("Connecting"); jc.Connect(); Console.WriteLine("Connected"); string line; while ((line = Console.ReadLine()) != null) { if (line == "/clear") { // Hm.... I wonder if this works on windows. Console.Write("\x1b[H\x1b[2J"); continue; } if ((line == "/q") || (line == "/quit")) { jc.Close(); break; } if (line.Trim() == "") { continue; } try { if (line == "</stream:stream>") { jc.Write(line); } else { // TODO: deal with stanzas that span lines... keep // parsing until we have a full "doc". XmlDocument doc = new XmlDocument(); doc.LoadXml(line); XmlElement elem = doc.DocumentElement; if (elem != null) jc.Write(elem); } } catch (XmlException ex) { Console.WriteLine("Invalid XML: " + ex.Message); } } }
public void Test_Indexer() { NonChild nc = new NonChild(); GetOpt go = new GetOpt(nc); go["test"] = "foo"; Assert.AreEqual("foo", nc.test); }
public void Test_NonChild() { NonChild nc = new NonChild(); GetOpt go = new GetOpt(nc); go.Process(new string[] { "-test", "foo" }); Assert.AreEqual("foo", nc.test); }