public void Parse_verbs_create_instance() { string invokedVerb = null; object invokedVerbInstance = null; var options = new OptionsWithVerbs(); options.AddVerb.Should().BeNull(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] {"add", "-p", "untracked.bin"} , options, (verb, subOptions) => { invokedVerb = verb; invokedVerbInstance = subOptions; }); result.Should().BeTrue(); invokedVerb.Should().Be("add"); invokedVerbInstance.Should().BeOfType<AddSubOptions>(); // Parser has built instance for us options.AddVerb.Should().NotBeNull(); options.AddVerb.CreationProof.Should().NotHaveValue(); options.AddVerb.Patch.Should().BeTrue(); options.AddVerb.FileName[0].Should().Be("untracked.bin"); }
public void Failed_verb_parsing_prints_particular_help_screen() { string invokedVerb = null; object invokedVerbInstance = null; var options = new OptionsWithVerbsHelp(); var testWriter = new StringWriter(); ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly(); var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter); var result = parser.ParseArguments(new string[] { "clone", "--no_hardlinks" }, options, (verb, subOptions) => { invokedVerb = verb; invokedVerbInstance = subOptions; }); result.Should().BeFalse(); var helpText = testWriter.ToString(); Console.WriteLine(helpText); var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Verify just significant output lines[5].Trim().Should().Be("--no-hardlinks Optimize the cloning process from a repository on a local"); lines[6].Trim().Should().Be("filesystem by copying files."); lines[7].Trim().Should().Be("-q, --quiet Suppress summary message."); invokedVerb.Should().Be("clone"); invokedVerbInstance.Should().Be(null); }
static void Main(string[] args) { Console.WriteLine("MetadataGenerator " + args.ToAggregateString(" ")); var parser = new CommandLine.Parser(ps => { ps.MutuallyExclusive = true; ps.HelpWriter = Console.Out; }); if (!parser.ParseArguments(args, Options)) { return; } var assemblyName = GetAssemblyName(Options.InputFile); if (!File.Exists(assemblyName)) { Console.WriteLine("The specified file {0} cannot be found", assemblyName); return; } var dbContextTypes = GetDbContextTypesFromAssembly(assemblyName); if (dbContextTypes.Length == 1 || Options.TypeName != null) { if (Options.TypeName != null) { try { var type = dbContextTypes.SingleOrDefault(t => t.Name == Options.TypeName || t.FullName == Options.TypeName); if (type != null) { ProcessType(type, Options.OutputFile ?? Options.TypeName + ".json"); } else { Console.WriteLine("The type specified {0} can not be found in the assembly {1}", Options.TypeName, assemblyName); } } catch (InvalidOperationException) { Console.WriteLine("There are several types named {0} in the assembly {1}", Options.TypeName, assemblyName); } catch (Exception ex) { Console.WriteLine(ex); } } else { var type = dbContextTypes.First(); ProcessType(type, Options.OutputFile ?? type.FullName + ".json"); } } else { // Hadle multitype scenario. //foreach (var type in dbContextTypes) { //} } }
public void Parsing_two_mutually_exclusive_options_fails() { var parser = new CommandLine.Parser(new ParserSettings { MutuallyExclusive = true }); var options = new OptionsWithDefaultSet(); var result = parser.ParseArguments(new string[] { "-i", "1", "--file=mystuff.xml" }, options); result.Should().BeFalse(); }
public void Parsing_mutually_exclusive_options_and_required_option_fails() { var options = new OptionsWithMultipleSetAndOneOption(); var parser = new CommandLine.Parser(new ParserSettings { MutuallyExclusive = true }); var result = parser.ParseArguments(new string[] { "-g167", "--hue", "205" }, options); result.Should().BeFalse(); }
public void Passing_no_value_to_a_nullable_integer_option_fails() { var options = new NullableTypesOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-int" }, options); result.Should().BeFalse(); }
public void Parse_string_array_option_using_short_name() { var options = new SimpleOptionsWithArray(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-z", "alfa", "beta", "gamma" }, options); result.Should().BeTrue(); base.ElementsShouldBeEqual(new string[] { "alfa", "beta", "gamma" }, options.StringArrayValue); }
public void Allow_single_dash_as_option_input_value() { var options = new SimpleOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "--string", "-" }, options); result.Should().BeTrue(); options.StringValue.Should().Be("-"); }
public void Parsing_one_mutually_exclusive_option_succeeds() { var options = new OptionsWithDefaultSet(); var parser = new CommandLine.Parser(new ParserSettings {MutuallyExclusive = true}); var result = parser.ParseArguments(new string[] { "--file=mystuff.xml" }, options); result.Should().BeTrue(); options.FileName.Should().Be("mystuff.xml"); }
public void Value_list_with_max_elem_outside_bounds() { var options = new OptionsWithValueListMaximumThree(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments( new string[] { "file.a", "file.b", "file.c", "file.d" }, options); result.Should().BeFalse(); }
public void Parse_string_array_option_using_long_name_with_equal_sign() { var options = new SimpleOptionsWithArray(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "--strarr=apple", "kiwi" }, options); result.Should().BeTrue(); base.ElementsShouldBeEqual(new string[] { "apple", "kiwi" }, options.StringArrayValue); }
public void Between_value_options_order_matters() { var options = new SimpleOptionsWithValueOptionAndValueList(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments( new string[] { "4321", "ofvalueoption", "-1234", "forvaluelist1", "forvaluelist2", "forvaluelist3" }, options); result.Should().BeFalse(); }
public void Default_parsing_is_case_sensitive() { var parser = new CommandLine.Parser(); var options = new MixedCaseOptions(); var result = parser.ParseArguments(new string[] { "-a", "alfa", "--beta-OPTION", "beta" }, options); result.Should().BeTrue(); options.AlfaValue.Should().Be("alfa"); options.BetaValue.Should().Be("beta"); }
public void Parse_string_option() { var options = new SimpleOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-s", "something" }, options); result.Should().BeTrue(); options.StringValue.Should().Be("something"); Console.WriteLine(options); }
public void Parsing_two_mutually_exclusive_options_in_two_set_succeeds() { var options = new OptionsWithMultipleSet(); var parser = new CommandLine.Parser(new ParserSettings { MutuallyExclusive = true }); var result = parser.ParseArguments(new string[] { "-g167", "--hue", "205" }, options); result.Should().BeTrue(); options.Green.Should().Be((byte)167); options.Hue.Should().Be((short)205); }
public void Parse_valid_unknown_arguments() { string[] args = { "--plugin", "addonX", "--filename", "input.dat" }; var appOptions = new OptionsForAppWithPlugIns(); var parser = new CommandLine.Parser(new ParserSettings { IgnoreUnknownArguments = true, CaseSensitive = true }); var result1 = parser.ParseArguments(args, appOptions); result1.Should().BeTrue(); appOptions.PlugInName.Should().Be("addonX"); var plugInXOptions = new OptionsOfPlugInX(); var result2 = parser.ParseArguments(args, plugInXOptions); result2.Should().BeTrue(); plugInXOptions.InputFileName.Should().Be("input.dat"); plugInXOptions.ReadOffset.Should().Be(10L); }
public void Parsing_mutually_exclusive_options_and_required_option_succeeds() { var options = new OptionsWithMultipleSetAndOneOption(); var parser = new CommandLine.Parser(new ParserSettings { MutuallyExclusive = true }); var result = parser.ParseArguments(new string[] { "-g100", "-h200", "-cRgbColorSet" }, options); result.Should().BeTrue(); options.Green.Should().Be((byte)100); options.Hue.Should().Be((short)200); options.DefaultColorSet.Should().Be(ColorSet.RgbColorSet); }
public void Correct_input_not_activates_help() { var options = new MockOptions(); var writer = new StringWriter(); var parser = new CommandLine.Parser(with => with.HelpWriter = writer); var result = parser.ParseArguments( new string[] { "-imath.xml", "-oresult.xml" }, options); result.Should().BeTrue();; writer.ToString().Length.Should().Be(0); }
public void Setting_help_writer_using_constructor() { var writer = new StringWriter(); var parser = new CommandLine.Parser(new ParserSettings(writer)); var options = new SimpleOptionsWithHelpOption(); bool success = parser.ParseArguments(new string[] {"--help"}, options); success.Should().BeFalse(); writer.ToString().Should().Be("MockOptions::GetUsage()"); }
public static int Main(string[] args) { var options = new Options(); var parser = new CommandLine.Parser(settings => { settings.CaseSensitive = true; settings.HelpWriter = System.Console.Out; }); try { if (parser.ParseArguments(args, options)) { // Validate the arguments. options.ValidateOptions(); try { var message = string.Format("Processing file {0}...", options.InputFile); System.Console.WriteLine(message); Trace.TraceInformation(message); var processor = new FileProcessor(options); processor.Process(); message = string.Format("Done processing file {0}.", options.InputFile); System.Console.WriteLine(message); Trace.TraceInformation(message); } catch (Exception ex) { Trace.TraceError(string.Format("Exception occurred while trying to process the file. Exception: {0} {1}", ex.Message, ex.StackTrace)); System.Console.Error.WriteLine("An error occurred while trying to process the file."); return (int)ExitCode.Errored; } } } catch (ArgumentNullException ex) { Trace.TraceError(string.Format("ArgumentNullException occurred while trying to parse arguments passed to the program. Exception: {0} {1}", ex.Message, ex.StackTrace)); System.Console.Error.WriteLine("An error occurred while trying to parse the arguments passed to the application."); return (int)ExitCode.ArgumentError; } catch (InvalidArgumentException ex) { Trace.TraceError(string.Format("InvalidArgumentException occurred while trying to parse arguments passed to the program. Exception: {0} {1}", ex.Message, ex.StackTrace)); System.Console.Error.WriteLine("The following argument is invalid: {0} Error: {1}", ex.InvalidParameterName, ex.Message); return (int)ExitCode.ArgumentError; } return (int)ExitCode.Success; }
public void Allow_single_dash_as_non_option_value() { var options = new SimpleOptionsWithValueList(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-sparser.xml", "-", "--switch" }, options); result.Should().BeTrue(); options.StringValue.Should().Be("parser.xml"); options.BooleanValue.Should().BeTrue(); options.Items.Count.Should().Be(1); options.Items[0].Should().Be("-"); }
public void Parse_string_integer_bool_options() { var options = new SimpleOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments( new string[] { "-s", "another string", "-i100", "--switch" }, options); result.Should().BeTrue(); options.StringValue.Should().Be("another string"); options.IntegerValue.Should().Be(100); options.BooleanValue.Should().BeTrue(); Console.WriteLine(options); }
public void Explicit_help_activation() { var options = new MockOptions(); var writer = new StringWriter(); var parser = new CommandLine.Parser(with => with.HelpWriter = writer); var result = parser.ParseArguments( new string[] { "--help" }, options); result.Should().BeFalse(); string helpText = writer.ToString(); (helpText.Length > 0).Should().BeTrue(); }
public void Value_option_attribute_values_are_not_mandatory() { var options = new SimpleOptionsWithValueOption(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments( new string[] { "--switch" }, options); result.Should().BeTrue(); options.BooleanValue.Should().BeTrue(); options.StringItem.Should().BeNull(); options.IntegerItem.Should().Be(0); options.NullableDoubleItem.Should().NotHaveValue(); }
public void Value_list_with_max_elem_inside_bounds() { var options = new OptionsWithValueListMaximumThree(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "file.a", "file.b", "file.c" }, options); result.Should().BeTrue(); options.InputFilenames[0].Should().Be("file.a"); options.InputFilenames[1].Should().Be("file.b"); options.InputFilenames[2].Should().Be("file.c"); options.OutputFile.Should().BeNull(); options.Overwrite.Should().BeFalse(); Console.WriteLine(options); }
public void Value_option_attribute_isolates_non_option_values() { var options = new SimpleOptionsWithValueOption(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments( new string[] { "--switch", "file.ext", "1000", "0.1234", "-s", "out.ext" }, options); result.Should().BeTrue(); options.BooleanValue.Should().BeTrue(); options.StringItem.Should().Be("file.ext"); options.IntegerItem.Should().Be(1000); options.NullableDoubleItem.Should().Be(0.1234D); options.StringValue.Should().Be("out.ext"); }
public void Bad_input_activates_help() { var options = new MockOptions(); var writer = new StringWriter(); var parser = new CommandLine.Parser(with => with.HelpWriter = writer); var result = parser.ParseArguments( new string[] { "math.xml", "-oresult.xml" }, options); result.Should().BeFalse(); string helpText = writer.ToString(); (helpText.Length > 0).Should().BeTrue(); Console.Write(helpText); }
public void Parse_nullable_double_option() { var options = new NullableTypesOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-d9.999" }, options); result.Should().BeTrue(); options.DoubleValue.Should().Be(9.999); options = new NullableTypesOptions(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { }, options); result.Should().BeTrue(); options.DoubleValue.Should().NotHaveValue(); }
public void Value_option_takes_precedence_on_value_list_regardless_declaration_order() { var options = new SimpleOptionsWithValueOptionAndValueList(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments( new string[] { "ofvalueoption", "-1234", "4321", "forvaluelist1", "forvaluelist2", "forvaluelist3" }, options); result.Should().BeTrue(); options.StringItem.Should().Be("ofvalueoption"); options.NullableInteger.Should().Be(-1234); options.UnsignedIntegerItem.Should().Be(4321U); options.Items[0].Should().Be("forvaluelist1"); options.Items[1].Should().Be("forvaluelist2"); options.Items[2].Should().Be("forvaluelist3"); }
public void Parse_nullable_enumeration_option() { var options = new NullableTypesOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "--enum=ReadWrite" }, options); result.Should().BeTrue(); options.EnumValue.Should().Be(FileAccess.ReadWrite); options = new NullableTypesOptions(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { }, options); result.Should().BeTrue(); options.EnumValue.Should().BeNull(); }
public void Parse_nullable_integer_option() { var options = new NullableTypesOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-i", "99" }, options); result.Should().BeTrue(); options.IntegerValue.Should().Be(99); options = new NullableTypesOptions(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { }, options); result.Should().BeTrue(); options.IntegerValue.Should().NotHaveValue(); }
public void Bad_input_activates_help() { var options = new MockOptions(); var writer = new StringWriter(); var parser = new CommandLine.Parser(with => with.HelpWriter = writer); var result = parser.ParseArguments( new string[] { "math.xml", "-oresult.xml" }, options); result.Should().BeFalse(); string helpText = writer.ToString(); (helpText.Length > 0).Should().BeTrue(); Console.Write(helpText); }
public void Value_list_attribute_isolates_non_option_values() { var options = new SimpleOptionsWithValueList(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments( new string[] { "--switch", "file1.ext", "file2.ext", "file3.ext", "-s", "out.ext" }, options); result.Should().BeTrue(); options.Items[0].Should().Be("file1.ext"); options.Items[1].Should().Be("file2.ext"); options.Items[2].Should().Be("file3.ext"); options.StringValue.Should().Be("out.ext"); options.BooleanValue.Should().BeTrue(); Console.WriteLine(options); }
public void Value_option_takes_precedence_on_value_list_regardless_declaration_order() { var options = new SimpleOptionsWithValueOptionAndValueList(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments( new string[] { "ofvalueoption", "-1234", "4321", "forvaluelist1", "forvaluelist2", "forvaluelist3" }, options); result.Should().BeTrue(); options.StringItem.Should().Be("ofvalueoption"); options.NullableInteger.Should().Be(-1234); options.UnsignedIntegerItem.Should().Be(4321U); options.Items[0].Should().Be("forvaluelist1"); options.Items[1].Should().Be("forvaluelist2"); options.Items[2].Should().Be("forvaluelist3"); }
public void Parse_nullable_enumeration_option() { var options = new NullableTypesOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "--enum=ReadWrite" }, options); result.Should().BeTrue(); options.EnumValue.Should().Be(FileAccess.ReadWrite); options = new NullableTypesOptions(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { }, options); result.Should().BeTrue(); options.EnumValue.Should().BeNull(); }
public void Should_use_property_name_as_long_name_if_omitted() { // Given var options = new OptionsWithImplicitLongName(); var parser = new CommandLine.Parser(); var arguments = new[] { "--offsets", "-2", "-1", "0", "1", "2" }; // When var result = parser.ParseArguments(arguments, options); // Than result.Should().Be(true); options.Offsets.Should().HaveCount(c => c == 5); options.Offsets.Should().ContainInOrder(new[] { -2, -1, 0, 1, 2 }); }
public void Should_use_property_name_as_long_name_if_omitted() { // Given var options = new OptionsWithImplicitLongName(); var parser = new CommandLine.Parser(); var arguments = new[] { "--segments", "header.txt:body.txt:footer.txt" }; // When var result = parser.ParseArguments(arguments, options); // Than result.Should().Be(true); options.Segments.Should().HaveCount(c => c == 3); options.Segments.Should().ContainInOrder(new[] { "header.txt", "body.txt", "footer.txt" }); }
static void Main(string[] args) { var procname = System.Diagnostics.Process.GetCurrentProcess().ProcessName; Console.WriteLine(procname + ' ' + string.Join(" ", args)); var parser = new CommandLine.Parser(ps => { ps.MutuallyExclusive = true; ps.HelpWriter = Console.Out; }); if (!parser.ParseArguments(args, Options)) { return; } var assemblyName = GetAssemblyName(Options.InputFile); if (!File.Exists(assemblyName)) { Console.WriteLine("The specified file {0} cannot be found", assemblyName); return; } string outfile = GetFilePath(); // TODO: how to get this from the command line? EntityDescriptor descriptor; if (assemblyName.Contains("Northwind")) { descriptor = new NorthwindEntityDescriptor(); } else { descriptor = new EntityDescriptor(); } var metadata = Generator.Generate(assemblyName, descriptor); var json = ToJson(metadata); if (outfile != null) { Console.WriteLine("Writing to " + outfile); File.WriteAllText(outfile, json); } else { Console.WriteLine(json); } Console.WriteLine("Done"); }
public void Parse_option_list() { var options = new SimpleOptionsWithOptionList(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-k", "string1:stringTwo:stringIII", "-s", "test-file.txt" }, options); result.Should().BeTrue(); options.SearchKeywords[0].Should().Be("string1"); Console.WriteLine(options.SearchKeywords[0]); options.SearchKeywords[1].Should().Be("stringTwo"); Console.WriteLine(options.SearchKeywords[1]); options.SearchKeywords[2].Should().Be("stringIII"); Console.WriteLine(options.SearchKeywords[2]); options.StringValue.Should().Be("test-file.txt"); Console.WriteLine(options.StringValue); }
public void TestPrintHelpThrowParsExceptionIfBadVerb() { // https://github.com/commandlineparser/commandline/blob/master/src/CommandLine/Error.cs var commandLineParser = new CommandLine.Parser(); var parser = commandLineParser.ParseArguments <Options.DefaultJob>(new string[] { }); CommandLineParser parserObj = new CommandLineParser(new OptionConverter(new JsonDeserializer()), commandLineParser, new ParserUsage(), new VerbFormater()); ParserUsage helpUsage = new ParserUsage(); List <CommandLine.Error> errs = new List <CommandLine.Error>(); CommandLine.Error err = new CommandLineWrapError(CommandLine.ErrorType.BadVerbSelectedError); errs.Add(err); ParseException ex = Assert.Throws <ParseException>(() => helpUsage.PrintHelp(parser, errs, new string[] {})); Assert.IsNotNull(ex); commandLineParser.Dispose(); }
public void Should_fail_gracefully_when_no_getusage_is_defined() { string invokedVerb = null; object invokedVerbInstance = null; var options = new OptionsWithVerbsNoHelp2(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new[] { "with", "--must" }, options, (verb, subOptions) => { invokedVerb = verb; invokedVerbInstance = subOptions; }); result.Should().BeFalse(); invokedVerb.Should().Be("with"); invokedVerbInstance.Should().BeNull(); }
public void Should_use_property_name_as_long_name_if_omitted() { // Given var options = new OptionsWithImplicitLongName(); var parser = new CommandLine.Parser(); var arguments = new[] { "--download", "something", "--up-load", "this", "-b", "1024" }; // When var result = parser.ParseArguments(arguments, options); // Than result.Should().Be(true); options.Download.Should().Be("something"); options.Upload.Should().Be("this"); options.Bytes.Should().Be(1024); }
public void Should_correctly_parse_two_consecutive_arrays() { // Given var options = new OptionsWithTwoArrays(); var parser = new CommandLine.Parser(); var argumets = new[] { "--source", @"d:/document.docx", "--output", @"d:/document.xlsx", "--headers", "1", "2", "3", "4", // first array "--content", "5", "6", "7", "8", "--verbose" // second array }; // When var result = parser.ParseArguments(argumets, options); // Than result.Should().BeTrue(); options.Headers.Should().HaveCount(c => c == 4); options.Headers.Should().ContainInOrder(new uint[] { 1, 2, 3, 4 }); options.Content.Should().HaveCount(c => c == 4); options.Content.Should().ContainInOrder(new uint[] { 5, 6, 7, 8 }); }
public void Parse_string_option_and_nullable_value_types() { var options = new NullableTypesOptions(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "--string", "alone" }, options); result.Should().BeTrue(); options.StringValue.Should().Be("alone"); options = new NullableTypesOptions(); parser = new CommandLine.Parser(); result = parser.ParseArguments( new string[] { "-d1.789", "--int", "10099", "-stogether", "--enum", "Read" }, options); result.Should().BeTrue(); options.DoubleValue.Should().Be(1.789D); options.IntegerValue.Should().Be(10099); options.StringValue.Should().Be("together"); options.EnumValue.Should().Be(FileAccess.Read); }
public void Parse_different_arrays_together__combination_one() { var options = new SimpleOptionsWithArray(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-z", "one", "two", "three", "four", "-y", "1", "2", "3", "4", "-q", "0.1", "0.2", "0.3", "0.4" }, options); result.Should().BeTrue(); base.ElementsShouldBeEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue); base.ElementsShouldBeEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue); base.ElementsShouldBeEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue); options = new SimpleOptionsWithArray(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { "-y", "1", "2", "3", "4", "-z", "one", "two", "three", "four", "-q", "0.1", "0.2", "0.3", "0.4" }, options); result.Should().BeTrue(); base.ElementsShouldBeEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue); base.ElementsShouldBeEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue); base.ElementsShouldBeEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue); options = new SimpleOptionsWithArray(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { "-q", "0.1", "0.2", "0.3", "0.4", "-y", "1", "2", "3", "4", "-z", "one", "two", "three", "four" }, options); result.Should().BeTrue(); base.ElementsShouldBeEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue); base.ElementsShouldBeEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue); base.ElementsShouldBeEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue); }
public void Invoke_render_parsing_errors_text() { var sw = new StringWriter(); var options = new OptionsForErrorsScenario(); var parser = new CommandLine.Parser(new ParserSettings { MutuallyExclusive = true, CaseSensitive = true, HelpWriter = sw }); var result = parser.ParseArguments(new string[] { "--option-b", "hello", "-cWORLD" }, options); result.Should().BeFalse(); var outsw = sw.ToString(); Console.WriteLine(outsw); var lines = outsw.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); lines[0].Should().Be("--option-b option violates format."); lines[1].Should().Be("-c/--option-c option violates format."); lines[2].Should().Be("-a required option is missing."); }
static int Main(string[] args) { var options = new Options(); var parser_options = new CommandLine.ParserSettings { MutuallyExclusive = true }; var parser = new CommandLine.Parser(parser_options); var isValid = parser.ParseArguments(args, options); if (!isValid) { Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString()); return -1; } DataUtils.PrintHubLabel( options.SMTSerial, options.ZPLFile, options.PrinterAddres ); return 0; }
private void DoCoreTestForIndex(string[] args) { var options = new OptionsWithVerbsHelp(); var testWriter = new StringWriter(); ReflectionHelper.AssemblyFromWhichToPullInformation = Assembly.GetExecutingAssembly(); var parser = new CommandLine.Parser(with => with.HelpWriter = testWriter); var result = parser.ParseArguments(args, options, (_, __) => { }); result.Should().BeFalse(); var helpText = testWriter.ToString(); Console.WriteLine(helpText); var lines = helpText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Verify just significant output lines[5].Trim().Should().Be("add Add file contents to the index."); lines[6].Trim().Should().Be("commit Record changes to the repository."); lines[7].Trim().Should().Be("clone Clone a repository into a new directory."); }
static void Main(string[] args) { var parser = new CommandLine.Parser(opt => { opt.MutuallyExclusive = true; opt.HelpWriter = Console.Error; }); var options = new Options(); if (parser.ParseArguments(args, options)) { if (string.IsNullOrEmpty(options.Pattern) && string.IsNullOrEmpty(options.PatternFile)) { Console.Error.WriteLine(options.GetUsage()); Environment.Exit(-1); } string pattern = !string.IsNullOrEmpty(options.Pattern) ? options.Pattern : File.ReadAllText(options.PatternFile); Regex re = new Regex(pattern); using (TextReader tr = (!string.IsNullOrEmpty(options.InputFile) ? new StreamReader(options.InputFile) : Console.In)) { using (TextWriter tw = (!string.IsNullOrEmpty(options.OutputFile) ? new StreamWriter(options.OutputFile) : Console.Out)) { string line; while (null != (line = tr.ReadLine())) { bool matchResult = re.IsMatch(line); matchResult = options.InvertResults ? !matchResult : matchResult; if (matchResult) { tw.WriteLine(line); } } } } } }
static int Main(string[] args) { var options = new Options(); var parser_options = new CommandLine.ParserSettings { MutuallyExclusive = true }; var parser = new CommandLine.Parser(parser_options); var isValid = parser.ParseArguments(args, options); if (!isValid) { Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString()); return(-1); } Console.WriteLine("Parameters used:"); string propname = "com_dut"; save_property(propname, options.Com_DUT); string valuestr = Properties.Settings.Default[propname].ToString(); if (valuestr == null || valuestr == string.Empty) { Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString()); Console.WriteLine(propname.ToUpper() + " not specified"); return(-1); } Console.WriteLine(propname.ToUpper() + ": " + valuestr); string com_dut = valuestr; propname = "com_ble"; save_property(propname, options.com_ble); valuestr = Properties.Settings.Default[propname].ToString(); if (valuestr == null || valuestr == string.Empty) { Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString()); Console.WriteLine(propname.ToUpper() + " not specified"); return(-1); } Console.WriteLine(propname.ToUpper() + ": " + valuestr); string com_ble = valuestr; // Don't allow lower case serials options.SMT_Serial = options.SMT_Serial.ToUpper(); Console.WriteLine("SMT Serial: " + options.SMT_Serial); Diags.Customers customer = Diags.Customers.IRIS; if (options.Customer_Amazon) { customer = Diags.Customers.Amazon; } else if (options.Customer_Centralite) { customer = Diags.Customers.Centralite; } Console.WriteLine("Costumer: " + customer.ToString()); Console.WriteLine("HW Version: " + options.HW_Version); string tester = DataUtils.OperatorName(options.Tester); int tester_id = DataUtils.OperatorId(tester); Console.WriteLine("Tester: " + tester); Console.WriteLine(); // For debug //Console.WriteLine("Press Enter to continue"); //Console.ReadLine(); Console.WriteLine("Run Tests..."); try { using ( Diags diags = new Diags ( dut_port_name: com_dut, ble_port_name: com_ble, smt_serial: options.SMT_Serial, customer: customer, hw_version: options.HW_Version, tester: tester, hub_ip_addr: options.Hub_IP ) ) { diags.LogFolder = Properties.Settings.Default.Log_Folder; Directory.CreateDirectory(diags.LogFolder); diags.Status_Event += Diags_Status_Event; diags.Program_Radios = options.Program_Radios; diags.BLETestDisable = options.BLETestDisabeld; diags.Run(); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine(ex.Message); Console.WriteLine(); Console.WriteLine(ex.StackTrace); if (ex is System.Data.Entity.Validation.DbEntityValidationException) { var exd = (System.Data.Entity.Validation.DbEntityValidationException)ex; foreach (var eves in exd.EntityValidationErrors) { Console.WriteLine(eves.Entry.Entity.ToString()); foreach (var eve in eves.ValidationErrors) { Console.WriteLine(eve.ErrorMessage); } } } else if (ex is System.Data.Entity.Infrastructure.DbUpdateException) { var exd = (System.Data.Entity.Infrastructure.DbUpdateException)ex; Console.WriteLine(exd.InnerException.InnerException.Message); } return(-1); } finally { Diags.Set_all_relays(false); } Console.WriteLine("All Tests Passed"); return(0); }
public static int Main(string[] args) { try { ArgumentOptions options = new ArgumentOptions(); var parser = new CommandLine.Parser(config => config.HelpWriter = Console.Out); if (parser.ParseArguments(args, options)) { if (!string.IsNullOrEmpty(options.Config)) { configPath = options.Config; } if (Directory.Exists(configPath)) { Config config = Config.Load(configPath); Output(string.Format("[{0}] Started Server Maintenance Process.", DateTime.Now)); using (TeknikEntities db = new TeknikEntities()) { // Scan all the uploads for viruses, and remove the bad ones if (options.ScanUploads && config.UploadConfig.VirusScanEnable) { ScanUploads(config, db); } // Warns all the invalid accounts via email if (options.WarnAccounts) { WarnInvalidAccounts(config, db); } // Cleans all inactive users if (options.CleanUsers) { CleanAccounts(config, db, options.DaysBeforeDeletion); } // Cleans the email for unused accounts if (options.CleanEmails) { CleanEmail(config, db); } // Cleans all the git accounts that are unused if (options.CleanGit) { CleanGit(config, db); } // Generates a file for all of the user's last seen dates if (options.GenerateLastSeen) { GenerateLastSeen(config, db, options.LastSeenFile); } // Generates a file for all of the invalid accounts if (options.GenerateInvalid) { GenerateInvalidAccounts(config, db, options.InvalidFile); } // Generates a file for all of the accounts to be cleaned if (options.GenerateCleaning) { GenerateCleaningList(config, db, options.CleaningFile, options.DaysBeforeDeletion); } } Output(string.Format("[{0}] Finished Server Maintenance Process.", DateTime.Now)); return(0); } else { string msg = string.Format("[{0}] Config File does not exist.", DateTime.Now); File.AppendAllLines(errorFile, new List <string> { msg }); Output(msg); } } else { Output(options.GetUsage()); } } catch (Exception ex) { string msg = string.Format("[{0}] Exception: {1}", DateTime.Now, ex.GetFullMessage(true)); File.AppendAllLines(errorFile, new List <string> { msg }); Output(msg); } return(-1); }
public void Parse_different_arrays_together__combination_two() { var options = new SimpleOptionsWithArray(); var parser = new CommandLine.Parser(); var result = parser.ParseArguments(new string[] { "-z", "one", "two", "three", "four", "-y", "1", "2", "3", "4", "-q", "0.1", "0.2", "0.3", "0.4", "--string=after" }, options); result.Should().BeTrue(); base.ElementsShouldBeEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue); base.ElementsShouldBeEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue); base.ElementsShouldBeEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue); options.StringValue.Should().Be("after"); options = new SimpleOptionsWithArray(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { "--string", "before", "-y", "1", "2", "3", "4", "-z", "one", "two", "three", "four", "-q", "0.1", "0.2", "0.3", "0.4" }, options); result.Should().BeTrue(); options.StringValue.Should().Be("before"); base.ElementsShouldBeEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue); base.ElementsShouldBeEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue); base.ElementsShouldBeEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue); options = new SimpleOptionsWithArray(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { "-q", "0.1", "0.2", "0.3", "0.4", "-y", "1", "2", "3", "4", "-s", "near-the-center", "-z", "one", "two", "three", "four" }, options); result.Should().BeTrue(); base.ElementsShouldBeEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue); base.ElementsShouldBeEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue); options.StringValue.Should().Be("near-the-center"); base.ElementsShouldBeEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue); options = new SimpleOptionsWithArray(); parser = new CommandLine.Parser(); result = parser.ParseArguments(new string[] { "--switch", "-z", "one", "two", "three", "four", "-y", "1", "2", "3", "4", "-i", "1234", "-q", "0.1", "0.2", "0.3", "0.4", "--string", "I'm really playing with the parser!" }, options); result.Should().BeTrue(); options.BooleanValue.Should().BeTrue(); base.ElementsShouldBeEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue); base.ElementsShouldBeEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue); options.IntegerValue.Should().Be(1234); base.ElementsShouldBeEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue); options.StringValue.Should().Be("I'm really playing with the parser!"); }
static void Main(string[] args) { var options = new Parameters.Options(); var parser = new CommandLine.Parser(); if (!parser.ParseArguments(args, options)) { System.Console.WriteLine("Command line parameters wrong..."); System.Console.WriteLine(options.GetUsage()); System.Environment.Exit(1); } var parseOptions = new Options { MinifyJson = options.Minify, ExcludeUntisIdZero = options.ExcludeZero, DateThreshold = options.UseThreshold ? new DateTimeOffset(DateTime.Today, DateTimeOffset.Now.Offset) : null as DateTimeOffset? }; var input = Path.GetFullPath(options.InputFile); var output = string.IsNullOrEmpty(options.OutputFile) ? null : Path.GetFullPath(options.OutputFile); var csv = string.Empty; if (!File.Exists(input)) { System.Console.WriteLine(string.Format("File {0} does not exist", input)); System.Environment.Exit(1); } if (options.Verbose) { System.Console.WriteLine(string.Format("reading file {0}", input)); } using (var reader = new StreamReader(input, Encoding.Default)) // Untis files are stored in ANSI format { csv = reader.ReadToEnd(); } if (options.Verbose) { System.Console.WriteLine("parsing file..."); } var json = string.Empty; if (options.Type == "substitutions") { json = UntisJson.ParseSubstitutionsAsJson(csv, parseOptions); } else if (options.Type == "exams") { json = UntisJson.ParseExamAsJson(csv, parseOptions); } else { System.Console.WriteLine("Unknown input type specified"); System.Environment.Exit(1); } if (options.Verbose) { System.Console.WriteLine("Parsing finished."); System.Console.WriteLine("Writing output..."); } if (!string.IsNullOrEmpty(output)) { using (var writer = new StreamWriter(output)) { writer.Write(json); } } else { System.Console.WriteLine(json); } if (options.Verbose) { System.Console.WriteLine("Finished."); } }
static void Main(string[] args) { Console.WriteLine("MetadataGenerator " + args.ToAggregateString(" ")); var parser = new CommandLine.Parser(ps => { ps.MutuallyExclusive = true; ps.HelpWriter = Console.Out; }); if (!parser.ParseArguments(args, Options)) { return; } var assemblyName = GetAssemblyName(Options.InputFile); if (!File.Exists(assemblyName)) { Console.WriteLine("The specified file {0} cannot be found", assemblyName); return; } var dbContextTypes = GetDbContextTypesFromAssembly(assemblyName); if (dbContextTypes.Length == 1 || Options.TypeName != null) { if (Options.TypeName != null) { try { var type = dbContextTypes.SingleOrDefault(t => t.Name == Options.TypeName || t.FullName == Options.TypeName); if (type != null) { ProcessType(type, Options.OutputFile ?? Options.TypeName + ".json"); } else { Console.WriteLine("The type specified {0} can not be found in the assembly {1}", Options.TypeName, assemblyName); } } catch (InvalidOperationException) { Console.WriteLine("There are several types named {0} in the assembly {1}", Options.TypeName, assemblyName); } catch (Exception ex) { Console.WriteLine(ex); } } else { var type = dbContextTypes.First(); ProcessType(type, Options.OutputFile ?? type.FullName + ".json"); } } else { // Handle multitype scenario. foreach (var type in dbContextTypes) { //if (type.FullName.Contains("BaseCtx")) continue; ProcessType(type, Options.OutputFile ?? $"{type.FullName}.json"); } } }
static int Main(string[] args) { //Console.WriteLine("Press Enter to continue"); //Console.Read(); _log.Info("App started"); var options = new Options(); var parser_options = new CommandLine.ParserSettings { MutuallyExclusive = true }; var parser = new CommandLine.Parser(parser_options); var isValid = parser.ParseArguments(args, options); if (!isValid) { Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString()); return(-1); } // Don't allow lower case serial options.SMT_Serial = options.SMT_Serial.ToUpper(); Console.WriteLine("SMT Serial: " + options.SMT_Serial); Console.WriteLine("Host: " + options.Host); Console.WriteLine(); // Check board was passed diags try { using (CLStoreEntities cx = new CLStoreEntities()) { LowesHub h = cx.LowesHubs.Where(lh => lh.smt_serial == options.SMT_Serial).OrderByDescending(lh => lh.date).First(); string info = string.Format("Hub {0} last diags {1}", h.MacAddress.MAC.ToString("X"), h.date.ToString()); _log.Info(info); } } catch (Exception ex) { _log.Fatal("Problem retrieving Hub diag info\r\n\r\n" + ex.Message + "\r\n" + ex.StackTrace); return(-3); } if (options.CalibrateLEDs) { BatteryTest batcal = new BatteryTest(options.Host, options.SMT_Serial); char save_option = 'n'; while (true) { Console.WriteLine("Getting LEDs values...\r\n"); double[] values = batcal.GetLEDsValues(); int i = 0; Console.WriteLine("Red On : {0}", values[i++].ToString("G2")); Console.WriteLine("Green On : {0}", values[i++].ToString("G2")); Console.WriteLine("Yellow On: {0}", values[i++].ToString("G2")); Console.WriteLine(); Console.WriteLine("Red Off : {0}", values[i++].ToString("G2")); Console.WriteLine("Green Off : {0}", values[i++].ToString("G2")); Console.WriteLine("Yellow Off: {0}", values[i++].ToString("G2")); i = 0; Properties.Settings.Default.LED_Red_On_Val = values[i++]; Properties.Settings.Default.LED_Green_On_Val = values[i++]; Properties.Settings.Default.LED_Yellow_On_Val = values[i++]; Properties.Settings.Default.LED_Red_Off_Val = values[i++]; Properties.Settings.Default.LED_Green_Off_Val = values[i++]; Properties.Settings.Default.LED_Yellow_Off_Val = values[i++]; Console.WriteLine("Save Values? (y/n/r):"); save_option = Convert.ToChar(Console.Read()); if (save_option != 'r') { break; } } if (save_option == 'y') { Properties.Settings.Default.Save(); } } try { if (!options.NoJigMode) { BatteryTest battery_test = new BatteryTest(options.Host, options.SMT_Serial); battery_test.InvalidateEnabled = !options.DisableInvalidate; battery_test.Status_Event += Battery_test_Status_Event; battery_test.LogFolder = Properties.Settings.Default.Log_Folder; Directory.CreateDirectory(battery_test.LogFolder); battery_test.LED_Red.OnVal = Properties.Settings.Default.LED_Red_On_Val; battery_test.LED_Red.OffVal = Properties.Settings.Default.LED_Red_Off_Val; battery_test.LED_Green.OnVal = Properties.Settings.Default.LED_Green_On_Val; battery_test.LED_Green.OffVal = Properties.Settings.Default.LED_Green_Off_Val; battery_test.LED_Yellow.OnVal = Properties.Settings.Default.LED_Yellow_On_Val; battery_test.LED_Yellow.OffVal = Properties.Settings.Default.LED_Yellow_Off_Val; battery_test.Run(); } else { BatteryTestNoJig batery_test = new BatteryTestNoJig(options.Host, options.SMT_Serial); batery_test.InvalidateEnabled = !options.DisableInvalidate; batery_test.Status_Event += Baterytest_Status_Event; batery_test.LogFolder = Properties.Settings.Default.Log_Folder; Directory.CreateDirectory(batery_test.LogFolder); batery_test.Run(); } } catch (Exception ex) { _log.Fatal(ex.Message + "\r\n" + ex.StackTrace); return(-2); } finally { if (!options.NoJigMode) { BatteryJig.Set_all_relays(false); } } _log.Info("All Tests Passed"); if (!options.PrintLabelDisabled) { _log.Info("Printing label..."); try { DataUtils.PrintHubLabel( options.SMT_Serial, Properties.Settings.Default.ZPL_Lable_File, Properties.Settings.Default.Printer_Address); } catch (Exception ex) { _log.Fatal(ex.Message + "\r\n" + ex.StackTrace); return(-2); } finally { } } return(0); }
static int Main(string[] args) { var options = new Options(); var parser = new CommandLine.Parser(s => { s.MutuallyExclusive = false; }); var isValid = parser.ParseArguments(args, options); if (!isValid) { Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString()); return(-1); } try { _board_serial = options.BoardSerial; _top_margin = options.TopMargin; _left_margin = options.LeftMargin; _font_name = options.FontName; _font_size = options.FontSize; // Set printer string name = ""; foreach (string printer in PrinterSettings.InstalledPrinters) { if (printer == options.PrinterName) { name = printer; break; } } if (string.IsNullOrEmpty(name)) { Console.WriteLine(options.PrinterName + " printer not found. Make sure printer is installed..."); return(-1); } PrintDocument pdoc = new PrintDocument(); pdoc.PrinterSettings.PrinterName = name; pdoc.PrintPage += Pdoc_PrintPage; // Set Paper pdoc.PrintController = new StandardPrintController(); name = ""; foreach (PaperSize ps in pdoc.PrinterSettings.PaperSizes) { //string sz = string.Format("{0} ({1:0.000} x {2:0.000})", ps.PaperName, (float)ps.Width / 100, (float)ps.Height / 100); if (ps.PaperName == options.PaperName) { name = ps.PaperName; pdoc.DefaultPageSettings.PaperSize = ps; break; } } if (string.IsNullOrEmpty(name)) { Console.WriteLine(options.PaperName + " paper not found"); return(-1); } pdoc.Print(); } catch (Exception ex) { Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace); return(-2); } return(0); }