public void Parse_NullArgs_ThrowsArgumentNullException() { object output; var parser = new OptionsParser(typeof(OptionsObjectWith1RequiredStringOption)); parser.Parse(null, out output, new CommandLineLogger()); }
public static int Main(string[] args) { var options = new Options(); var parser = new OptionsParser(); if(!parser.Parse(options, args)) { return 1; } if(options.Interactive) { return HandleInteractive(options.Directories.ToList(), options.BinariesDirectory, options.OutputDirectory, options.GenerateEntryProject); } switch(options.Action) { case Operation.GenerateAll: var configuration = GenerateAllProjects(options.BinariesDirectory, options.GenerateEntryProject, options.Directories); configuration.Save(options.OutputDirectory); break; case Operation.Clean: Cleaner.Clean(options.OutputDirectory); break; case Operation.GenerateSolution: HandleGenerateSolution(options.MainProject, options.BinariesDirectory, options.AdditionalProjects, options.RobotTests, options.OutputDirectory, options.GenerateEntryProject); break; case Operation.Scan: HandleScan(options.Type, options.Directories); break; } return 0; }
public void Parse_TooManyArgsProvided_ReturnsFalse() { object output; var parser = new OptionsParser(typeof(OptionsObjectWith1RequiredStringOption)); Assert.IsFalse(parser.Parse(new string[] { "foo", "bar" }, out output, new CommandLineLogger())); }
public static int Main(string[] args) { var options = new Options(); var parser = new OptionsParser(); if(!parser.Parse(options, args)) { return 1; } if(options.Interactive) { return HandleInteractive(options.Directories.ToList()); } switch(options.Action) { case Operation.GenerateAll: GenerateAllProjects(options.Directories).Save(solutionName); break; case Operation.Clean: Cleaner.Clean(options.MainProject); break; case Operation.GenerateSolution: HandleGenerateSolution(options.MainProject, options.AdditionalProjects, options.Output); break; case Operation.Scan: HandleScan(options.Type, options.Directories); break; } return 0; }
public void ShouldSetDefaultValueWhenParameterIsNotFound() { var args = new string[0]; var parser = new OptionsParser(); var options = new OptionsWithParameterWithDefaultValue(); parser.Parse(options, args); Assert.AreEqual(0, parser.ParsedOptions.Count()); Assert.AreEqual(147, options.NumericParameter); }
public static void Main(string[] args) { var parser = new OptionsParser(new ParserConfiguration { GenerateHelp = true, CustomFooterGenerator = () => "All unparsed options will be forwarded to CLI application.", CustomUsageLineGenerator = usageLine => usageLine + " [script]", AllowUnexpectedArguments = true }); var options = new Options(); if(!parser.Parse(options, args)) { return; } var mode = options.Debug ? "Debug" : "Release"; var monoOptions = options.Debug ? "--debug" : string.Empty; if(options.DebuggerSocketPort != -1) { monoOptions += string.Format(" --debugger-agent=transport=dt_socket,address=127.0.0.1:{0},server=y", options.DebuggerSocketPort); Console.WriteLine("Listening on port {0}", options.DebuggerSocketPort); } var rootPath = (options.RootPath == ".") ? Environment.CurrentDirectory : options.RootPath; Console.WriteLine("Running in {0} mode.\nROOT_PATH={1}", mode, rootPath); var binaryPath = Path.Combine(rootPath, "output", mode, "CLI.exe"); var optionsToPass = parser.RecreateUnparsedArguments(); if(options.HelpCLI) { Console.WriteLine("NOTE: showing help from binary: {0}", binaryPath); optionsToPass = "******"; } var process = new Process(); process.StartInfo.FileName = "mono"; process.StartInfo.Arguments = string.Format("{0} {1} {2}", monoOptions, binaryPath, optionsToPass); if(options.Quiet) { process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; } process.Start(); if(options.Quiet) { process.StandardError.Close(); } process.WaitForExit(); }
public void ShouldDetectLongSwitch() { var args = new [] { "--long" }; var parser = new OptionsParser(); parser.WithOption<bool>("long"); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual("long", parser.ParsedOptions.First().Flag.LongName); }
public void ShouldUseValueParserCreatedByFactory() { var factoryMock = new Mock <IValueParserFactory>(); factoryMock .Setup(x => x.CreateParser <OptionsWithCustomParser.CustomParser>()) .Returns(new OptionsWithCustomParser.CustomParser("OtherCustomValue")); var parser = new OptionsParser <OptionsWithCustomParser>(factoryMock.Object); var options = parser.Parse(new[] { "--string-option", "some-value" }); Assert.Equal("OtherCustomValue", options.StringOption); }
public void ParseOneSingleRuleWithTwoArgs() { object[] expected = { new RuleOptions("rule1", new object[] { $"{1}", $"{2}" }) }; var parser = new OptionsParser(); var actual = parser.Parse("rule1:1,2"); actual.Should().BeEquivalentTo(expected); }
public void Pause_WhenPassingPauseFlag_ShouldSetFlagToTrue() { var args = new List <string> { "some-filename.txt", "--pause" }; var options = OptionsParser.Parse(args); options.FileName.Should().Be("some-filename.txt"); options.Pause.Should().BeTrue(); options.DisplayHelp.Should().BeFalse(); }
public void Parse_MissingRequiredOptions_ParsedIsFalse() { // Arrange var arguments = new List <string>() { "-i", "myfile.csv", "-o", "myfile.json" }; // Act var options = OptionsParser.Parse(arguments); // Assert Assert.That(options.Parsed, Is.False); }
public void ShouldParsePositionalValues() { var args = new [] { "value", "value-2" }; var parser = new OptionsParser(); var options = new OptionsWithPositionalValues(); parser.Parse(options, args); Assert.AreEqual(1, parser.Values.Count()); Assert.AreEqual(1, parser.UnexpectedArguments.Count()); Assert.AreEqual("value", options.Value); Assert.AreEqual("value-2", parser.UnexpectedArguments.First().Value); }
public void Parse_ValidOptions_ParsedIsTrue() { // Arrange var arguments = new List <string>() { "-i", "myfile.csv", "--inputtype", "csv", "-o", "myfile.json", "--outputtype", "json" }; // Act var options = OptionsParser.Parse(arguments); // Assert Assert.That(options.Parsed, Is.True); }
public void ShouldDetectedUnexpectedShortSwitchWithValue() { var args = new [] { "-cx", "value with whitespace" }; var parser = new OptionsParser(); parser.WithOption<bool>('c'); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual('c', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual(2, parser.UnexpectedArguments.Count()); Assert.AreEqual("x", parser.UnexpectedArguments.ElementAt(0).Value); Assert.AreEqual("value with whitespace", parser.UnexpectedArguments.ElementAt(1).Value); }
public void ShouldRecreateMixedShortFlag() { var args = new [] { "-AwB" }; var parser = new OptionsParser(); parser.WithOption <bool>('A'); parser.WithOption <bool>('B'); parser.Parse(args); Assert.AreEqual(2, parser.ParsedOptions.Count()); Assert.AreEqual('A', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual('B', parser.ParsedOptions.Last().Flag.ShortName); Assert.AreEqual("-w", parser.RecreateUnparsedArguments()); }
public void ShouldRemoveEmptyShortFlagPrefix() { var args = new [] { "-AB" }; var parser = new OptionsParser(); parser.WithOption <bool>('A'); parser.WithOption <bool>('B'); parser.Parse(args); Assert.AreEqual(2, parser.ParsedOptions.Count()); Assert.AreEqual('A', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual('B', parser.ParsedOptions.Last().Flag.ShortName); Assert.AreEqual(string.Empty, parser.RecreateUnparsedArguments()); }
public void ParseManyRulesWithDifferentArgs() { var expected = new[] { new RuleOptions("rule1", new object[] { $"{1}", $"{2}" }), new RuleOptions("rule2", new object[] { $"{0}" }), new RuleOptions("rule3", new object[0]) }; var parser = new OptionsParser(); var actual = parser.Parse("rule1:1,2;rule2:0;rule3:"); actual.Should().BeEquivalentTo(expected); }
public void ShouldHandleIntOptionWithDefaultValueFollowedByString() { var args = new [] { "--value", "test" }; var parser = new OptionsParser(new ParserConfiguration { AllowUnexpectedArguments = true }); var options = new OptionsWithInt(); parser.Parse(options, args); Assert.AreEqual(-1, options.Value); Assert.AreEqual(1, parser.UnexpectedArguments.Count()); Assert.AreEqual("test", parser.UnexpectedArguments.First().Value); Assert.AreEqual("test", parser.RecreateUnparsedArguments()); }
public void ShouldDetectUnexpectedShortSwitch() { var args = new [] { "-xc" }; var parser = new OptionsParser(); parser.WithOption <bool>('c'); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual('c', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual(1, parser.UnexpectedArguments.Count()); Assert.AreEqual("x", parser.UnexpectedArguments.First().Value); }
public void ShouldDetectUnexpectedLongSwitch() { var args = new [] { "--long", "--secondLong" }; var parser = new OptionsParser(); parser.WithOption <bool>("long"); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual("long", parser.ParsedOptions.First().Flag.LongName); Assert.AreEqual(1, parser.UnexpectedArguments.Count()); Assert.AreEqual("secondLong", parser.UnexpectedArguments.First().Value); }
public void ShouldParseOptionValueWithHyphen() { var args = new [] { "-c", "value-with-hyphen" }; var parser = new OptionsParser(); parser.WithOption <string>('c'); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual('c', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual("value-with-hyphen", parser.ParsedOptions.First().Value); Assert.AreEqual(0, parser.UnexpectedArguments.Count()); }
public void ShouldParseShortSwitchWithStringValue() { var args = new [] { "-nmValue" }; var parser = new OptionsParser(); parser.WithOption <bool>('n'); parser.WithOption <String>('m'); parser.Parse(args); Assert.AreEqual(2, parser.ParsedOptions.Count()); Assert.AreEqual('n', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual('m', parser.ParsedOptions.Skip(1).First().Flag.ShortName); Assert.AreEqual("Value", parser.ParsedOptions.Skip(1).First().Value); }
public void ThrowWhenFactoryFailsToCreateParser() { var exception = new Exception(); var factoryMock = new Mock <IValueParserFactory>(); factoryMock .Setup(x => x.CreateParser <OptionsWithCustomParser.CustomParser>()) .Throws(exception); var parser = new OptionsParser <OptionsWithCustomParser>(factoryMock.Object); Assert.Throws <CreatingValueParserFailedException>( () => parser.Parse(new[] { "--string-option", "some-value" })); }
public void ShouldDetectedUnexpectedShortSwitchWithValue() { var args = new [] { "-cx", "value with whitespace" }; var parser = new OptionsParser(); parser.WithOption <bool>('c'); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual('c', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual(2, parser.UnexpectedArguments.Count()); Assert.AreEqual("x", parser.UnexpectedArguments.ElementAt(0).Value); Assert.AreEqual("value with whitespace", parser.UnexpectedArguments.ElementAt(1).Value); }
public void ShouldParseOptionWithMultipleValues() { var args = new [] { "-v", "1:2:3" }; var parser = new OptionsParser(); var options = new OptionsWithMultipleValues(); parser.Parse(options, args); Assert.AreEqual(3, options.Values.Length); Assert.AreEqual(1, options.Values[0]); Assert.AreEqual(2, options.Values[1]); Assert.AreEqual(3, options.Values[2]); Assert.AreEqual(0, parser.Values.Count()); Assert.AreEqual(0, parser.UnexpectedArguments.Count()); }
protected virtual void ExecuteInternal() { if (_options.DisplayLogo) { PrintLogo(); } if (_options.RunAction == ConsoleHostOptions.Action.DisplayHelp) { PrintHelp(); _exitCode = 0; return; } SetEnvironment(); if (_options.RunAction == ConsoleHostOptions.Action.ExecuteFile) { _exitCode = ExecuteFile(_options.Files[_options.Files.Count - 1], _options.IgnoredArgs.ToArray()); return; } Debug.Assert(_options.LanguageProvider != null); OptionsParser opt_parser = _options.LanguageProvider.GetOptionsParser(); opt_parser.GlobalOptions = ScriptDomainManager.Options; try { opt_parser.Parse(_options.IgnoredArgs.ToArray()); } catch (InvalidOptionException e) { Console.Error.WriteLine(e.Message); _exitCode = -1; return; } switch (_options.RunAction) { case ConsoleHostOptions.Action.RunConsole: _exitCode = RunCommandLine(opt_parser); break; case ConsoleHostOptions.Action.RunFiles: _exitCode = RunFiles(opt_parser); break; } }
public void ShouldRecreateUnparsedArgument13() { var args = new[] { "-n", "123", "--wrong-arg" }; var parser = new OptionsParser(); parser.WithOption <int>('n'); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual('n', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual(123, parser.ParsedOptions.First().Value); Assert.AreEqual(1, parser.UnexpectedArguments.Count()); Assert.AreEqual("wrong-arg", parser.UnexpectedArguments.ElementAt(0).Value); Assert.AreEqual("--wrong-arg", parser.RecreateUnparsedArguments()); }
public void ShouldThrowAnExceptionWhenDefaultValueIsOfAWrongType() { var args = new [] { "--arg" }; var parser = new OptionsParser(); var options = new OptionsWithDefault(); try { parser.Parse(options, args); Assert.Fail("Expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.Contains("is of unexpected type")); } }
public void ShouldNotParseAfterDoubleHyphen() { var args = new [] { "--", "--value", "test" }; var parser = new OptionsParser(new ParserConfiguration { AllowUnexpectedArguments = true }); var options = new OptionsWithInt(); parser.Parse(options, args); Assert.AreEqual(-1, options.Value); Assert.AreEqual(0, parser.ParsedOptions.Count()); Assert.AreEqual(2, parser.UnexpectedArguments.Count()); Assert.AreEqual("--value", parser.UnexpectedArguments.ElementAt(0).Value); Assert.AreEqual("test", parser.UnexpectedArguments.ElementAt(1).Value); Assert.AreEqual("--value test", parser.RecreateUnparsedArguments()); }
public void ShouldParseOptionWithMultipleValuesWithDefaultDelimiterValue() { var args = new [] { "-m", "this;is;a;test" }; var parser = new OptionsParser(); var options = new OptionsWithMultipleValuesWithDefaultDelimiterValue(); parser.Parse(options, args); Assert.AreEqual(4, options.Values.Length); Assert.AreEqual("this", options.Values[0]); Assert.AreEqual("is", options.Values[1]); Assert.AreEqual("a", options.Values[2]); Assert.AreEqual("test", options.Values[3]); Assert.AreEqual(0, parser.Values.Count()); Assert.AreEqual(0, parser.UnexpectedArguments.Count()); }
public void ShouldThrowAnExceptionWhenDefaultValueIsOfAWrongType() { var args = new [] { "--arg" }; var parser = new OptionsParser(); var options = new OptionsWithDefault(); try { parser.Parse(options, args); Assert.Fail("Expected exception"); } catch(ArgumentException e) { Assert.IsTrue(e.Message.Contains("is of unexpected type")); } }
public void ShouldThrowExceptionWhenRequiredParamterIsNotFound() { var args = new string[0]; var parser = new OptionsParser(new ParserConfiguration { ThrowValidationException = true }); var options = new OptionsWithRequiredParameter(); try { parser.Parse(options, args); Assert.Fail("Expected exception"); } catch (ValidationException) { // intentionally left blank } }
public static void Main(string[] args) { //var testArgs = new[] { "-i", @"D:\deploy\project", "-n", "TESTRUN2" }; var options = new OptionsParser(); var serviceData = options.Parse(args); if (serviceData == null) { return; } var client = new ClientFacade( ConfigurationManager.AppSettings["login"], ConfigurationManager.AppSettings["password"], serviceData); try { if (client.OpenSession()) { Console.WriteLine("Connection to service is established. Connection session is opened."); client.SendFiles(); client.Deploy(); } else { Console.WriteLine("Connection was terminated because folder '{0}' is already is use.", serviceData.Directory); client.Close(); ClientFacade.NeedClose = true; } } catch (Exception ex) { HandleException(ex); client.Abort(); ClientFacade.NeedClose = true; } while (ClientFacade.NeedClose != true) { Thread.Sleep(500); } Console.WriteLine("\r\nPress any key to close..."); Console.ReadKey(); }
public void ShouldRecreateUnparsedArgument15() { var args = new[] { "--port=8888", "--no-xwt" }; var parser = new OptionsParser(); parser.WithOption <int>("port"); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual("port", parser.ParsedOptions.First().Flag.LongName); Assert.AreEqual(8888, parser.ParsedOptions.First().Value); Assert.AreEqual(1, parser.UnexpectedArguments.Count()); Assert.AreEqual("no-xwt", parser.UnexpectedArguments.ElementAt(0).Value); Assert.AreEqual("--no-xwt", parser.RecreateUnparsedArguments()); }
public void Parse_ValidOptions_ParsedValuesMatchInput() { // Arrange var arguments = new List <string>() { "-i", "myfile.csv", "--inputtype", "csv", "-o", "myfile.json", "--outputtype", "json" }; // Act var options = OptionsParser.Parse(arguments); // Assert Assert.That(options.InputLocation, Is.EqualTo("myfile.csv")); Assert.That(options.InputType, Is.EqualTo("csv")); Assert.That(options.OutputLocation, Is.EqualTo("myfile.json")); Assert.That(options.OutputType, Is.EqualTo("json")); }
public void ShouldDetectOptionHavingBothShortAndLongName() { var argsShort = new [] { "-l" }; var argsLong = new [] { "--long" }; foreach (var args in new [] { argsShort, argsLong }) { var parser = new OptionsParser(); parser.WithOption <bool>('l', "long"); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); var flag = parser.ParsedOptions.First().Flag; Assert.AreEqual('l', flag.ShortName); Assert.AreEqual("long", flag.LongName); } }
public void ShouldCallCustomValidator() { var args = new [] { "--stringValue=foo", "-n1" }; var parser = new OptionsParser(new ParserConfiguration { ThrowValidationException = true }); var options = new OptionsWithCustomValidator(); try { parser.Parse(options, args); Assert.Fail("Expected exception"); } catch (ValidationException) { Assert.AreEqual(1, options.NumericValue); Assert.AreEqual("foo", options.StringValue); } }
public void ShouldRecreateUnparsedArgument7() { var args = new[] { "positional argument", "--port=8888", "--wrong-arg" }; var parser = new OptionsParser(); parser.WithOption <int>("port"); var options = new OptionsWithMultipleArguments(); parser.Parse(options, args); Assert.AreEqual("positional argument", options.Value); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual("port", parser.ParsedOptions.ToArray()[0].Flag.LongName); Assert.AreEqual(8888, parser.ParsedOptions.ToArray()[0].Value); Assert.AreEqual(1, parser.UnexpectedArguments.Count()); Assert.AreEqual("wrong-arg", parser.UnexpectedArguments.ElementAt(0).Value); Assert.AreEqual("--wrong-arg", parser.RecreateUnparsedArguments()); }
public void ShouldRecreateUnparsedArgument3() { var args = new[] { "positional argument", "-p8888", "--wrong-arg" }; var parser = new OptionsParser(); parser.WithOption <int>('p'); var options = new OptionsWithMultipleArguments(); parser.Parse(options, args); Assert.AreEqual("positional argument", options.Value); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual('p', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual(8888, parser.ParsedOptions.First().Value); Assert.AreEqual(1, parser.UnexpectedArguments.Count()); Assert.AreEqual("wrong-arg", parser.UnexpectedArguments.ElementAt(0).Value); Assert.AreEqual("--wrong-arg", parser.RecreateUnparsedArguments()); }
public void ShouldThrowAnExceptionForLongOptionRequiringValueWhenThereIsNone() { var args = new [] { "--long" }; var parser = new OptionsParser(new ParserConfiguration { ThrowValidationException = true }); parser.WithOption <int>("long"); try { parser.Parse(args); Assert.Fail("Should throw an exception"); } catch (ValidationException e) { Assert.IsTrue(e.Message.Contains("requires parameter of type")); } }
public static void Main(string[] args) { CommandLineLogger logger = new CommandLineLogger(); Dictionary<string, Type> commands = typeof(ICommand).Assembly .GetTypes() .Where(x => x.GetInterfaces().Contains(typeof(ICommand))) .ToDictionary(x => x.Name.Substring(0, x.Name.Length - "Command".Length)); if (args.Length > 0) { if (commands.ContainsKey(args[0])) { ICommand command = CreateCommandInstance(commands[args[0]]); OptionsParser optionsParser = new OptionsParser(command.OptionsType); object options; var commandArgs = args.Skip(1).Take(args.Length - 1).ToArray(); if (optionsParser.Parse(commandArgs, out options, logger) && command.EnsureOptions(options, logger)) { command.Execute(options, logger); } } else { Console.Error.WriteLine("ERROR: Unknown command \"{0}\".", args[0]); Console.Error.WriteLine(); ListCommands(commands); } } else { Console.Error.WriteLine("ERROR: Please prvoide a command to execute."); Console.Error.WriteLine(); ListCommands(commands); } }
public void ShouldAcceptExpectedValues() { var args = new [] { "-a", "-b", "value-1", "-c", "value-2", "-d", "value-3" }; var parser = new OptionsParser(); parser.WithValue("val1"); parser.WithValue("val2"); parser.WithOption<bool>('a'); parser.WithOption<bool>('b'); parser.WithOption<bool>('c'); parser.WithOption<bool>('d'); parser.Parse(args); Assert.AreEqual(4, parser.ParsedOptions.Count()); Assert.AreEqual('a', parser.ParsedOptions.ElementAt(0).Flag.ShortName); Assert.AreEqual('b', parser.ParsedOptions.ElementAt(1).Flag.ShortName); Assert.AreEqual('c', parser.ParsedOptions.ElementAt(2).Flag.ShortName); Assert.AreEqual('d', parser.ParsedOptions.ElementAt(3).Flag.ShortName); Assert.AreEqual(2, parser.Values.Count()); Assert.AreEqual("value-1", parser.Values.ElementAt(0).Value); Assert.AreEqual("value-2", parser.Values.ElementAt(1).Value); Assert.AreEqual("value-3", parser.RecreateUnparsedArguments()); }
public void ShouldThrowAnExceptionOnUnexpectedMultipleOccurencesOfArgument() { var args = new[] { "--value", "5", "--value", "6" }; var parser = new OptionsParser(new ParserConfiguration { ThrowValidationException = true }); var options = new OptionsWithInt(); parser.Parse(options, args); }
public static void Run(string[] args) { var options = new Options(); var optionsParser = new OptionsParser(); if(!optionsParser.Parse(options, args)) { return; } Plugins.XwtProviderPlugin.XwtProvider.StartXwtThread(); using(var context = ObjectCreator.Instance.OpenContext()) { var monitor = new Emul8.UserInterface.Monitor(); context.RegisterSurrogate(typeof(Emul8.UserInterface.Monitor), monitor); // we must initialize plugins AFTER registering monitor surrogate // as some plugins might need it for construction TypeManager.Instance.PluginManager.Init("CLI"); Logger.AddBackend(ConsoleBackend.Instance, "console"); EmulationManager.Instance.ProgressMonitor.Handler = new CLIProgressMonitor(); var crashHandler = new CrashHandler(); AppDomain.CurrentDomain.UnhandledException += (sender, e) => crashHandler.HandleCrash(e); Shell shell = null; Type preferredUARTAnalyzer = null; if(options.Port > 0) { var io = new IOProvider(new SocketIOSource(options.Port)); shell = ShellProvider.GenerateShell(io, monitor, true, false); } else { preferredUARTAnalyzer = typeof(UARTWindowBackendAnalyzer); var terminal = new UARTWindowBackendAnalyzer(); shell = ShellProvider.GenerateShell(terminal.IO, monitor); monitor.Quitted += shell.Stop; try { terminal.Show(); } catch(InvalidOperationException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine(ex.Message); Emulator.Exit(); } } shell.Quitted += Emulator.Exit; if(preferredUARTAnalyzer != null) { EmulationManager.Instance.CurrentEmulation.BackendManager.SetPreferredAnalyzer(typeof(UARTBackend), preferredUARTAnalyzer); EmulationManager.Instance.EmulationChanged += () => { EmulationManager.Instance.CurrentEmulation.BackendManager.SetPreferredAnalyzer(typeof(UARTBackend), preferredUARTAnalyzer); }; } monitor.Interaction = shell.Writer; monitor.MachineChanged += emu => shell.SetPrompt(emu != null ? new Prompt(string.Format("({0}) ", emu), ConsoleColor.DarkYellow) : null); if(options.Execute != null) { shell.Started += s => s.InjectInput(string.Format("{0}\n", options.Execute)); } else if(!string.IsNullOrEmpty(options.ScriptPath)) { shell.Started += s => s.InjectInput(string.Format("i {0}{1}\n", Path.IsPathRooted(options.ScriptPath) ? "@" : "$CWD/", options.ScriptPath)); } new Thread(x => shell.Start(true)) { IsBackground = true, Name = "Shell thread" }.Start(); Emulator.BeforeExit += () => { Emulator.DisposeAll(); }; Emulator.WaitForExit(); Plugins.XwtProviderPlugin.XwtProvider.StopXwtThread(); } }
public void ShouldThrowAnExceptionForShortOptionRequiringValueWhenThereIsNone() { var args = new [] { "-n" }; var parser = new OptionsParser(new ParserConfiguration { ThrowValidationException = true }); parser.WithOption<int>('n'); try { parser.Parse(args); Assert.Fail("Should throw an exception"); } catch (ValidationException e) { Assert.IsTrue(e.Message.Contains("requires parameter of type")); } }
public void ShouldParseShortSwitchWithValue() { var args = new [] { "-n123" }; var parser = new OptionsParser(); parser.WithOption<int>('n'); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual('n', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual(123, parser.ParsedOptions.First().Value); }
public void ShouldRemoveEmptyShortFlagPrefix() { var args = new [] { "-AB" }; var parser = new OptionsParser(); parser.WithOption<bool>('A'); parser.WithOption<bool>('B'); parser.Parse(args); Assert.AreEqual(2, parser.ParsedOptions.Count()); Assert.AreEqual('A', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual('B', parser.ParsedOptions.Last().Flag.ShortName); Assert.AreEqual(string.Empty, parser.RecreateUnparsedArguments()); }
public void ShouldRecreateUnparsedArguments() { var args = new [] { "--expected", "-x", "value", "-y1", "--another-expected", "-Aw", "-z'this was unexpected'" }; var parser = new OptionsParser(); parser.WithOption<bool>("expected"); parser.WithOption<bool>("another-expected"); parser.WithOption<bool>('A'); parser.Parse(args); Assert.AreEqual(3, parser.ParsedOptions.Count()); Assert.AreEqual("expected", parser.ParsedOptions.First().Flag.LongName); Assert.AreEqual("another-expected", parser.ParsedOptions.ElementAt(1).Flag.LongName); Assert.AreEqual(@"-x value -y1 -w ""-z'this was unexpected'""", parser.RecreateUnparsedArguments()); }
public static void Main(string[] args) { var basicOptions = new BasicOptions(); var optionsParser = new OptionsParser(new ParserConfiguration { GenerateHelp = false, AllowUnexpectedArguments = true }); // here we parse only one option - `root-directory` // the rest will be parsed in the second phase if(!optionsParser.Parse(basicOptions, args)) { return; } optionsParser = new OptionsParser(new ParserConfiguration { GenerateHelp = true, CustomFooterGenerator = () => "All unparsed options will be forwarded to launched application.", CustomUsageLineGenerator = usageLine => usageLine + " [script]", AllowUnexpectedArguments = true }); var addHelpSwitch = false; var possibleLaunchees = new List<LaunchDescriptorsGroup>(); var selectedLaunchees = new List<LaunchDescriptorsGroup>(); var interestingBinaries = Scanner.ScanForInterestingBinaries(basicOptions.RootPath).OrderBy(x => x.Priority).ThenBy(x => x.Name).ToArray(); for(var i = 0; i < interestingBinaries.Length; i++) { var j = i; possibleLaunchees.Add(interestingBinaries[i]); interestingBinaries[i].GenerateSwitches(optionsParser, i == 0); interestingBinaries[i].SwitchOption.Parsed += (option, value) => { selectedLaunchees.Add(interestingBinaries[j]); }; if(interestingBinaries[i].HelpOption != null) { interestingBinaries[i].HelpOption.Parsed += (option, value) => { addHelpSwitch = true; }; } } // here we parse all of the options again // as only now we know which launch targets // and configurations are available in the // system var options = new Options(); if(!optionsParser.Parse(options, args)) { return; } var conf = options.Debug ? LaunchDescriptor.Configuration.Debug : LaunchDescriptor.Configuration.Release; LaunchDescriptorsGroup selectedGroup = null; LaunchDescriptor selectedLaunchee = null; if(selectedLaunchees.Count == 0) { if(possibleLaunchees.Count == 0) { Console.Error.WriteLine("There is no launch target specified. Exiting"); Environment.Exit(1); } selectedGroup = possibleLaunchees.OrderBy(x => x.Priority).ThenBy(x => x.Name).First(); } else if(selectedLaunchees.Count > 1) { Console.Error.WriteLine("Only one launch target can be used. Exiting"); Environment.Exit(1); } else { selectedGroup = selectedLaunchees.First(); } selectedLaunchee = selectedGroup.ForConfiguration(conf); if(selectedLaunchee == null) { Console.Error.WriteLine("Selected target {0} is not available in {1} configuration.", selectedGroup.Name, conf); Environment.Exit(1); } var monoOptions = options.Debug ? "--debug" : string.Empty; if(options.DebuggerSocketPort != -1) { monoOptions += string.Format(" --debugger-agent=transport=dt_socket,address=127.0.0.1:{0},server=y", options.DebuggerSocketPort); Console.WriteLine("Listening on port {0}", options.DebuggerSocketPort); } var optionsToPass = optionsParser.RecreateUnparsedArguments(); if(addHelpSwitch) { Console.WriteLine("NOTE: showing help from binary: {0}", selectedLaunchee.Name); optionsToPass = "******"; } var process = new Process(); process.StartInfo.FileName = "mono"; process.StartInfo.Arguments = string.Format("{0} {1} {2}", monoOptions, selectedLaunchee.Path, optionsToPass); if(options.Quiet) { process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; } process.Start(); if(options.Quiet) { process.StandardError.Close(); } process.WaitForExit(); }
public void ShouldParseShortSwitchWithStringValue() { var args = new [] { "-nmValue" }; var parser = new OptionsParser(); parser.WithOption<bool>('n'); parser.WithOption<String>('m'); parser.Parse(args); Assert.AreEqual(2, parser.ParsedOptions.Count()); Assert.AreEqual('n', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual('m', parser.ParsedOptions.Skip(1).First().Flag.ShortName); Assert.AreEqual("Value", parser.ParsedOptions.Skip(1).First().Value); }
public void ShouldDetectOptionHavingBothShortAndLongName() { var argsShort = new [] { "-l" }; var argsLong = new [] { "--long" }; foreach(var args in new [] { argsShort, argsLong }) { var parser = new OptionsParser(); parser.WithOption<bool>('l', "long"); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); var flag = parser.ParsedOptions.First().Flag; Assert.AreEqual('l', flag.ShortName); Assert.AreEqual("long", flag.LongName); } }
public void ShoulNotParseOnMissingRequiredPositionalValues() { var args = new string [0]; var parser = new OptionsParser(); var options = new OptionsWithRequiredPositionalValues(); Assert.AreEqual(false, parser.Parse(options, args)); }
public void ShouldParseOptionWithSpacesInValue() { var args = new [] { "--option=Value with spaces" }; var parser = new OptionsParser(); parser.WithOption<string>("option"); parser.Parse(args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual("option", parser.ParsedOptions.First().Flag.LongName); Assert.AreEqual("Value with spaces", parser.ParsedOptions.First().Value); }
public PythonObject(string[] args) { ScriptRuntimeSetup runtimeSetup = ScriptRuntimeSetup.ReadConfiguration(); ConsoleHostOptions options = new ConsoleHostOptions(); _optionsParser = new ConsoleHostOptionsParser(options, runtimeSetup); string provider = GetLanguageProvider(runtimeSetup); LanguageSetup languageSetup = null; foreach (LanguageSetup language in runtimeSetup.LanguageSetups) { if (language.TypeName == provider) { languageSetup = language; } } if (languageSetup == null) { // the language doesn't have a setup -> create a default one: languageSetup = new LanguageSetup(Provider.AssemblyQualifiedName, Provider.Name); runtimeSetup.LanguageSetups.Add(languageSetup); } // inserts search paths for all languages (/paths option): InsertSearchPaths(runtimeSetup.Options, Options.SourceUnitSearchPaths); _languageOptionsParser = new OptionsParser<ConsoleOptions>(); try { _languageOptionsParser.Parse(Options.IgnoredArgs.ToArray(), runtimeSetup, languageSetup, PlatformAdaptationLayer.Default); } catch (InvalidOptionException e) { Console.Error.WriteLine(e.Message); } _runtime = new ScriptRuntime(runtimeSetup); try { _engine = _runtime.GetEngineByTypeName(provider); } catch (Exception e) { Console.Error.WriteLine(e.Message); } _runtime.LoadAssembly(System.Reflection.Assembly.GetExecutingAssembly()); _runtime.LoadAssembly(provider.GetType().Assembly); _runtime.LoadAssembly(PythonStringIO.StringIO().GetType().Assembly); _scope= _engine.CreateScope(); RunCommandLine(args); }
public void ShouldSetShortSwitchInClass() { var args = new [] { "-s" }; var options = new OptionsWithBool(); var parser = new OptionsParser(); parser.Parse(options, args); Assert.AreEqual(1, parser.ParsedOptions.Count()); Assert.AreEqual(options.Switch, true); }
public static void Run(string[] args) { var options = new Options(); var optionsParser = new OptionsParser(); if(!optionsParser.Parse(options, args)) { return; } using(var context = ObjectCreator.OpenContext()) { var monitor = new Emul8.UserInterface.Monitor(); context.RegisterSurrogate(typeof(Emul8.UserInterface.Monitor), monitor); // we must initialize plugins AFTER registering monitor surrogate // as some plugins might need it for construction TypeManager.Instance.PluginManager.Init("CLI"); Logger.AddBackend(ConsoleBackend.Instance, "console"); EmulationManager.Instance.ProgressMonitor.Handler = new CLIProgressMonitor(); var crashHandler = new CrashHandler(); AppDomain.CurrentDomain.UnhandledException += (sender, e) => crashHandler.HandleCrash(e); var resetEvent = new ManualResetEventSlim(); if(options.StdInOut) { Logger.AddBackend(new FileBackend("logger.log"), "file"); var world = new StreamIOSource(Console.OpenStandardInput(), Console.OpenStandardOutput()); var io = new DetachableIO(world); monitor.Quitted += resetEvent.Set; var handler = new StdInOutHandler(io, monitor, options.Plain); handler.Start(); } else { Shell shell = null; Type preferredUARTAnalyzer = null; if(options.Port > 0) { var io = new DetachableIO(new SocketIOSource(options.Port)); shell = ShellProvider.GenerateShell(io, monitor, true, false); shell.Quitted += resetEvent.Set; } else if(options.ConsoleMode) { preferredUARTAnalyzer = typeof(UARTMultiplexedBackendAnalyzer); var stream = new PtyUnixStream("/proc/self/fd/1"); var world = new StreamIOSource(stream, stream.Name); Logger.AddBackend(new FileBackend("logger.log"), "file"); var consoleTerm = new ConsoleTerminal(world); UARTMultiplexedBackendAnalyzer.Multiplexer = consoleTerm; monitor.Console = consoleTerm; shell = ShellProvider.GenerateShell(monitor); consoleTerm.AttachTerminal("shell", shell.Terminal); shell.Quitted += resetEvent.Set; } else { preferredUARTAnalyzer = typeof(UARTWindowBackendAnalyzer); var stream = new PtyUnixStream(); var dio = new DetachableIO(new StreamIOSource(stream, stream.Name)); var terminal = new UARTWindowBackendAnalyzer(dio); shell = ShellProvider.GenerateShell(dio, monitor); shell.Quitted += resetEvent.Set; monitor.Quitted += shell.Stop; try { terminal.Show(); } catch(InvalidOperationException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine(ex.Message); resetEvent.Set(); } } if(preferredUARTAnalyzer != null) { EmulationManager.Instance.CurrentEmulation.BackendManager.SetPreferredAnalyzer(typeof(UARTBackend), preferredUARTAnalyzer); EmulationManager.Instance.EmulationChanged += () => { EmulationManager.Instance.CurrentEmulation.BackendManager.SetPreferredAnalyzer(typeof(UARTBackend), preferredUARTAnalyzer); }; } monitor.Interaction = shell.Writer; monitor.UseConsole = options.ConsoleMode; monitor.MachineChanged += emu => shell.SetPrompt(emu != null ? new Prompt(string.Format("({0}) ", emu), ConsoleColor.DarkYellow) : null); if(options.Execute != null) { shell.Started += s => s.InjectInput(string.Format("{0}\n", options.Execute)); } else if(!string.IsNullOrEmpty(options.ScriptPath)) { shell.Started += s => s.InjectInput(string.Format("i $CWD/{0}\n", options.ScriptPath)); } new Thread(x => shell.Start(true)) { IsBackground = true, Name = "Shell thread" }.Start(); } resetEvent.Wait(); EmulationManager.Instance.Clear(); TypeManager.Instance.Dispose(); Logger.Dispose(); } }
public void ShouldRecreateMixedShortFlag() { var args = new [] { "-AwB" }; var parser = new OptionsParser(); parser.WithOption<bool>('A'); parser.WithOption<bool>('B'); parser.Parse(args); Assert.AreEqual(2, parser.ParsedOptions.Count()); Assert.AreEqual('A', parser.ParsedOptions.First().Flag.ShortName); Assert.AreEqual('B', parser.ParsedOptions.Last().Flag.ShortName); Assert.AreEqual("-w", parser.RecreateUnparsedArguments()); }