public bool RemoveOption(string OptionName) { CommandLineOption OptionToRemove = null; foreach (CommandLineOption CurrentOption in RegisteredOptions) { if (IgnoreCase) { if (CurrentOption.OptionName.ToLowerInvariant() == OptionName.ToLowerInvariant()) { OptionToRemove = CurrentOption; break; } } else { if (CurrentOption.OptionName == OptionName) { OptionToRemove = CurrentOption; break; } } } if (OptionToRemove != null) { RegisteredOptions.Remove(OptionToRemove); return(true); } else { return(false); } }
public void Should_support_multiple_options() { // Arrange var valueOption = new CommandLineOption { Name = "with-value", Description = "Element with value", Required = true }; var noValueOption = new CommandLineOption { Name = "novalue", Description = "Element with no value", Required = true, HasValue = false }; var parser = new CommandLineParser(valueOption, noValueOption); // Act var values = parser.Parse(new[] { "--with-value", "value", "--novalue" }).ToList(); // Assert values.Should() .ContainSingle(v => v.HasValue && v.Option == valueOption && v.Value == "value"); values.Should().ContainSingle(v => !v.HasValue && v.Option == noValueOption); values.Should().HaveCount(2); }
private static void ExecuteMain(string[] args) { Environment.ExitCode = EXIT_SUCCESS; try { CommandLineOption cmd = new CommandLineOption(args); if (cmd.HasHelpSwitch()) { Console.WriteLine(CommandLineOption.GetHelpMessage()); System.Environment.Exit(EXIT_HELP); } CsvDivConfig config = cmd.CreateConfig(); ValidationResult valid = config.Valid(); if (valid == ValidationResult.Success) { ConsoleExecutor.Execute(config); } else { Console.WriteLine(CommandLineOption.GetHelpMessage()); Console.WriteLine(valid.ErrorMessage); System.Environment.Exit(EXIT_ERROR); } } catch (Exception ex) { Console.WriteLine(ex.Message); Environment.ExitCode = EXIT_ERROR; } }
/// <summary> /// Called by Rhino when the user wants to run the command. /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { GetOption go = new GetOption(); go.SetCommandPrompt("Select command option"); int add_index = go.AddOption("Add"); int delete_index = go.AddOption("Delete"); int list_index = go.AddOption("List"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } CommandLineOption option = go.Option(); if (null == option) { return(Result.Failure); } int index = option.Index; if (index == add_index) { string str = string.Empty; Result rc = RhinoGet.GetString("String to add", false, ref str); if (rc == Result.Success) { SampleCsStringTableHelpers.Add(str); } } else if (index == delete_index) { string str = string.Empty; Result rc = RhinoGet.GetString("String to delete", false, ref str); if (rc == Result.Success) { SampleCsStringTableHelpers.Remove(str); } } else if (index == list_index) { int count = SampleCsStringTableHelpers.Count(); if (0 == count) { RhinoApp.WriteLine("0 string items to list."); } else { for (int i = 0; i < count; i++) { RhinoApp.WriteLine(SampleCsStringTableHelpers.GetAt(i)); } } } return(Result.Success); }
static void Main(string[] args) { CommandLineOption options = new CommandLineOption(); ICommandLineParser parser = new CommandLineParser(new CommandLineParserSettings { MutuallyExclusive = true, CaseSensitive = true, HelpWriter = Console.Error }); bool success = parser.ParseArguments(args, options); if (true == success) { Run(options.FileName, options.Overwrite); } else { if (args.Length != 0 && args[0] != "-h") { NotifyAndExit("Input arguments are invalid. Type PostBuild.exe -h for help. Press any key to exit."); } } }
private FamiliarCommandLineArguments ResolveArguments(CommandLineArgument[] parsedArgs) { var result = new FamiliarCommandLineArguments(); if (parsedArgs.Length == 0) { return(result); } CommandLineOption.ValidateMutuallyExclusive(parsedArgs, _testFileOpt, _connectOpt, _infoOpt, _helpOpt); _testFileOpt.ValidateThisForbidsOthers(parsedArgs, _selectOpt, _databaseOpt); _connectOpt.ValidateThisForbidsOthers(parsedArgs, _selectOpt); _infoOpt.ValidateThisForbidsOthers(parsedArgs, _selectOpt); _helpOpt.ValidateThisForbidsOthers(parsedArgs, _selectOpt, _databaseOpt); result.Verbose = _verboseOpt.ExtractOrNull(parsedArgs) != null; result.ShowHelp = _helpOpt.ExtractOrNull(parsedArgs) != null; result.TestFile = _testFileOpt.ExtractOrNull(parsedArgs)?.Value; result.Connect = _connectOpt.ExtractOrNull(parsedArgs)?.Value; result.ShowInfo = _infoOpt.ExtractOrNull(parsedArgs) != null; result.SelectWindow = _selectOpt.ExtractOrNull(parsedArgs) != null; result.Database = _databaseOpt.ExtractOrNull(parsedArgs)?.Value; return(result); }
internal int GetIndex(IList<CommandLineOption> options, CommandLineOption @delegate) { foreach (var item in options.Where(item => item.Name == @delegate.Name)) { return options.IndexOf(item); } return -1; }
public async Task Process(CommandLineOption option) { await LoadGlobalVariables(option); var creatorConfig = await GetCreatorConfig(option); await CreateTemplates(creatorConfig); }
public void Exists_ShouldBeFalse_WhenEmptyArgs() { var option = new CommandLineOption("zero", new string[0]); var result = option.Exists(); result.Should().BeFalse(); }
public BaseCommand(string name, string description, bool useLog) : base(name, description) { if (useLog) { this.logFileName = this.AddOption("log", "log file", "path to log file", CommandLineOptionTypes.PathMustExist); } }
public void Exists_ShouldBeTrue_WhenOptionInArgs_PrecededWithDoubleMinus() { var args = new[] { "one", "-two", "--three", "--zero" }; var option = new CommandLineOption("zero", args); var result = option.Exists(); result.Should().BeTrue(); }
public void Params_ShouldBe_Empty() { var args = new[] { "one", "-two", "--zero" }; var option = new CommandLineOption("zero", args); var result = option.Params(); result.Should().BeEmpty(); }
public void Exists_ShouldBeFalse_WhenNoOptionInArgs() { var args = new [] { "zero", "one", "-two", "--three", "--h", "z", "-z", "--z", "0", "\"day.com\"" }; var option = new CommandLineOption("zero", args); var result = option.Exists(); result.Should().BeFalse(); }
public CommandLineArgument(CommandLineParser parser, CommandLineOption option, int argIndex, string argText, int charIndex, string value) { Parser = parser; Option = option; ArgIndex = argIndex; ArgText = argText; CharIndex = charIndex; Value = value; }
/// <summary> /// Called by Rhino when the user wants to run the command. /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { System.Guid panel_id = SampleCsMainPanel.PanelId; bool visible = Panels.IsPanelVisible(panel_id); string prompt = (visible) ? "Main panel is visible. New value" : "Main Manager panel is hidden. New value"; GetOption go = new GetOption(); int hide_index = go.AddOption("Hide"); int show_index = go.AddOption("Show"); int toggle_index = go.AddOption("Toggle"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } CommandLineOption option = go.Option(); if (null == option) { return(Result.Failure); } int index = option.Index; if (index == hide_index) { if (visible) { Panels.ClosePanel(panel_id); } } else if (index == show_index) { if (!visible) { Panels.OpenPanel(panel_id); } } else if (index == toggle_index) { if (visible) { Panels.ClosePanel(panel_id); } else { Panels.OpenPanel(panel_id); } } return(Result.Success); }
/// <summary> /// Parse a string array for command line args. Will throw exceptions if parsing fails. /// </summary> /// <param name="ArrayToParse"></param> public void Parse(string[] ArrayToParse) { List <Tuple <string, string> > ActiveOptionsList = new List <Tuple <string, string> >(); // Happy fun logic time for (int OptionIndex = 0; OptionIndex < ArrayToParse.Length; OptionIndex++) { string CurrentOptionString = ArrayToParse[OptionIndex]; if (CurrentOptionString.Length <= 1) { continue; } if (CurrentOptionString.StartsWith("-")) // All valid options must start with a - or + character. Ignore current option if it doesn't contain this. { CurrentOptionString = CurrentOptionString.Substring(1); // Chop off the initial - } else //+command line arguments are stored but are not processed { if (CurrentOptionString.StartsWith("+")) { ActiveOptionsList.Add(ParsePlusOption(ref OptionIndex, ref ArrayToParse)); } continue; } CommandLineOption Option = GetOptionByName(CurrentOptionString); if (Option == null) { continue; // Option isn't registered or invalid casing. Ignore. } if (Option.ArgumentRequired) // Unconditionally grab the next argument and skip it for the purposes of parsing. { string OptionArg = ArrayToParse[++OptionIndex]; Option.Callback?.Invoke(OptionArg); ActiveOptionsList.Add(new Tuple <string, string>(Option.OptionName, OptionArg)); } else { if (ArrayToParse.Length > OptionIndex + 1) { string NextOptionString = ArrayToParse[OptionIndex + 1]; if (!(NextOptionString.StartsWith("+") || NextOptionString.StartsWith("-"))) { //Next option is available and is not an option ActiveOptionsList.Add(new Tuple <string, string>(Option.OptionName, NextOptionString)); Option.Callback?.Invoke(NextOptionString); OptionIndex++; //Skip next option since we consumed it continue; } } ActiveOptionsList.Add(new Tuple <string, string>(Option.OptionName, "")); Option.Callback?.Invoke(""); // Call the option's callback with an empty string since no args were found } } ActiveOptions = ActiveOptionsList.ToArray(); }
public void Ensure_Can_Be_Constructed_With_Empty_ShortName_And_Valid_LongName() { const string expectedShortName = ""; const string expectedLongName = "My long name"; var mockParser = Mock.Of <ICommandLineOptionParser <object> >(); var cmdOption = new CommandLineOption <object>(expectedShortName, expectedLongName, mockParser); Assert.AreEqual(expectedShortName, cmdOption.ShortName, "Could not instantiate with empty ShortName"); }
public void Ensure_Can_Be_Constructed_With_Whitespace_Only_LongName() { const string expectedShortName = "My short name"; const string expectedLongName = " "; var mockParser = Mock.Of <ICommandLineOptionParser <object> >(); var cmdOption = new CommandLineOption <object>(expectedShortName, expectedLongName, mockParser); Assert.AreEqual(expectedLongName, cmdOption.LongName, "Could not instantiate with whitespace only LongName"); }
public void Ensure_Can_Be_Constructed_With_Null_LongName() { const string expectedShortName = "My short name"; const string expectedLongName = null; var mockParser = Mock.Of <ICommandLineOptionParser <object> >(); var cmdOption = new CommandLineOption <object>(expectedShortName, expectedLongName, mockParser); Assert.IsNull(cmdOption.LongName, "Could not instantiate with null LongName"); }
public void Ensure_Can_Be_Constructed_With_Null_LongName() { const string expectedShortName = "My short name"; const string expectedLongName = null; var mockParser = Mock.Of<ICommandLineOptionParser<object>>(); var cmdOption = new CommandLineOption<object>(expectedShortName, expectedLongName, mockParser); Assert.IsNull(cmdOption.LongName, "Could not instantiate with null LongName"); }
public async Task ProcessAsync(CommandLineOption option) { await LoadGlobalVariables(option); var deploymentDefinition = await GetDeploymentDefinitionAsync(option); var resources = new ArmTemplateCreator(deploymentDefinition, mapper).Create(); await GenerateArmTemplateFile(resources, deploymentDefinition); }
public void Ensure_Can_Be_Constructed_With_Empty_LongName() { const string expectedShortName = "My short name"; const string expectedLongName = ""; var mockParser = Mock.Of<ICommandLineOptionParser<object>>(); var cmdOption = new CommandLineOption<object>(expectedShortName, expectedLongName, mockParser); Assert.AreEqual(expectedLongName, cmdOption.LongName, "Could not instantiate with empty LongName"); }
public void Params_ShouldBe_ArgsAfterOption_TillEnd() { var args = new[] { "--zero", "three", "\"http://daily.com\"" }; var expected = new[] { "three", "\"http://daily.com\"" }; var option = new CommandLineOption("zero", args); var result = option.Params(); result.Should().ContainInOrder(expected); }
private static void HandleIntentionalCrash(Application app, string[] args) { var option = new CommandLineOption("crash", args); if (!option.Exists()) { return; } app.Deactivated += (sender, ea) => throw new StackOverflowException("Intentional crash test"); }
private ICommand CreateCommand(string[] args) { if (CommandLine.Parser.Default.ParseArguments(args, CommandLineOption)) { StoreOption(); CommandLineOption.ConvertToFullPath(); return(CommandFactory.Create(CommandLineOption)); } throw new Exceptions.ExcelMergeException(true, $"Invalid argument.\nargument:\n{string.Join(" ", args)}"); }
public void Ensure_Can_Be_Constructed() { const string expectedShortName = "My short name"; const string expectedLongName = "My long name"; var mockParser = Mock.Of <ICommandLineOptionParser <object> >(); var cmdOption = new CommandLineOption <object>(expectedShortName, expectedLongName, mockParser); Assert.AreEqual(expectedShortName, cmdOption.ShortName, "Specified ShortName was not as expected"); Assert.AreEqual(expectedLongName, cmdOption.LongName, "Specified LongName was not as expected"); }
internal override void AddOption(CommandLineOption newOption) { if (!_helper.DelegateExists(_commandLineOptions, newOption)) { _commandLineOptions.Add(newOption); } else { _commandLineOptions[_helper.GetIndex(_commandLineOptions, newOption)] = newOption; } }
private IOptionBuilder <T> ConfigureInternal <T>(LambdaExpression selector, string key) { if (!m_options.ContainsKey(key)) { var option = new CommandLineOption <T>(ParserOptions, m_option, selector, ArgumentResolverFactory); m_options.Add(key, option); } return(m_options[key] as IOptionBuilder <T>); }
private async Task <DeploymentDefinition> GetCreatorConfig(CommandLineOption option) { var fileReader = new FileReader(); var creatorConfig = await fileReader.GetCreatorConfigFromYaml(option.YamlConfigPath); creatorConfig.PrefixFileName = option.FileNamePrefix; creatorConfig.MasterTemplateName = option.MasterFileName; return(creatorConfig); }
public void Ensure_Can_Be_Constructed() { const string expectedShortName = "My short name"; const string expectedLongName = "My long name"; var mockParser = Mock.Of<ICommandLineOptionParser<object>>(); var cmdOption = new CommandLineOption<object>(expectedShortName, expectedLongName, mockParser); Assert.AreEqual(expectedShortName, cmdOption.ShortName, "Specified ShortName was not as expected"); Assert.AreEqual(expectedLongName, cmdOption.LongName, "Specified LongName was not as expected"); }
public void Ensure_That_If_Value_Is_Whitespace_Cannot_Be_Parsed_And_No_Default_Set_Then_optionSyntaxException_Is_Thrown() { var option = new ParsedOption(); const string value = " "; var mockParser = new Mock <ICommandLineOptionParser <string> >(); mockParser.Setup(x => x.CanParse(option)).Returns(false); var target = new CommandLineOption <string>("s", "long name", mockParser.Object); target.Bind(option); }
private static void OutputHelpText(CliOptions options) { List <CommandLineOption> list = new List <CommandLineOption>() { options.Game, options.Setup, options.Verbose }; for (int i = 0; i < list.Count; i++) { CommandLineOption item = list[i]; Console.WriteLine(item.HelpText); } }
public static ICommand Create(CommandLineOption option) { switch (option.MainCommand) { case CommandType.None: return(new DiffCommand(option)); case CommandType.Diff: return(new DiffCommand(option)); } throw new Exceptions.ExcelMergeException(true, $"{option.MainCommand} is unkown command"); }
private async Task LoadGlobalVariables(CommandLineOption option) { await VariableReplacer.Instance.LoadFromFile(option.VariableFilePath); VariableReplacer.Instance.LoadFromString(option.VariableString); if (option.PrintVariables) { foreach (var variable in VariableReplacer.Instance.Variables) { Console.WriteLine($"variable is loaded: {variable.Key}={variable.Value}"); } } }
private static Task ProcessCommand(CommandLineOption option) { try { var createCommand = new CreateCommand(); createCommand.Process(option).Wait(); } catch (Exception e) { errorCode = -1; Console.WriteLine(e.ToString()); } return(Task.CompletedTask); }
private async Task LoadGlobalVariables(CommandLineOption option) { await VariableReplacer.Instance.LoadFromFile(option.VariableFilePath); VariableReplacer.Instance.Load(option.VariableString); if (option.PrintVariables) { var keyValuePairs = VariableReplacer.Instance.GetVariables(); foreach (var kv in keyValuePairs) { Console.WriteLine($"{kv.Key}={kv.Value}"); } } }
protected CommandLineArgsBase(string[] args, string keyPrefixOverride = null, string[] separatorsOverride = null) { var options = new List<CommandLineOption>(); foreach (var property in this.GetType().GetProperties()) { var attr = property.GetCustomAttributes(typeof(CommandLineOptionAttribute), true) .OfType<CommandLineOptionAttribute>() .FirstOrDefault(); if (attr == null) continue; var dic = args .Select(x => x.Split(separatorsOverride ?? attr.Separators, StringSplitOptions.RemoveEmptyEntries)) .GroupBy(xs => xs[0], (k, ys) => ys.Last()) // 重複の場合は後ろの引数を優先 .ToDictionary(xs => xs[0].ToLower(), xs => xs.Length == 1 ? null : xs[1]); var prefix = keyPrefixOverride ?? attr.KeyPrefix; string valueString; if ((!string.IsNullOrEmpty(attr.Key) && dic.TryGetValue(prefix + attr.Key.ToLower(), out valueString)) || (!string.IsNullOrEmpty(attr.ShortKey) && dic.TryGetValue(prefix + attr.ShortKey.ToLower(), out valueString))) { var option = new CommandLineOption(attr.Key, property.PropertyType, valueString, attr.KeyPrefix, attr.Separators.First()); if (option.ConvertException != null) { System.Diagnostics.Debug.WriteLine(option.ConvertException); continue; } property.SetValue(this, option.Value); options.Add(option); } } this.OriginalArgs = args; this.Options = options.ToArray(); }
internal abstract void AddOption(CommandLineOption newOption);
internal bool DelegateExists(IList<CommandLineOption> options, CommandLineOption @delegate) { return options.Any(item => item.Name == @delegate.Name); }
internal bool OptionMatchesDelegate(string option, CommandLineOption del) { return del.Name == option || del.ShortName == option; }
private int CountParametersInDelegate(CommandLineOption @delegate) { return @delegate.ParameterDisplayNames == null ? 0 : @delegate.ParameterDisplayNames.Count(); }
private bool SwitchExists(CommandLineOption @delegate, IList<OptionPair> switches) { return switches.Any(item => item.Option == @delegate.ShortName || item.Option == @delegate.Name); }
private string GetOptionLine(int exprLength, CommandLineOption command) { return string.Format("{0}, {1}", GetOptionString(command.ShortName), GetOptionString(command.Name)) .PadRight(exprLength + 5, ' ') + command.Description; }
public void Ensure_Can_Be_Constructed_With_Null_ShortName_And_Valid_LongName() { const string expectedShortName = null; const string expectedLongName = "My long name"; var mockParser = Mock.Of<ICommandLineOptionParser<object>>(); var cmdOption = new CommandLineOption<object>(expectedShortName, expectedLongName, mockParser); Assert.AreEqual(expectedShortName, cmdOption.ShortName, "Could not instantiate with null ShortName"); }
public void Ensure_Returns_False_If_Empty_LongName_Provided() { ICommandLineOption cmdOption = new CommandLineOption<string>("s", string.Empty, Mock.Of<ICommandLineOptionParser<string>>()); Assert.IsFalse(cmdOption.HasLongName); }
public void Ensure_Returns_True_If_LongName_Provided() { ICommandLineOption cmdOption = new CommandLineOption<string>("s", "long name", Mock.Of<ICommandLineOptionParser<string>>()); Assert.IsTrue(cmdOption.HasLongName); }
public void Ensure_That_If_Value_Is_Whitespace_Cannot_Be_Parsed_And_No_Default_Set_Then_optionSyntaxException_Is_Thrown() { var option = new ParsedOption(); const string value = " "; var mockParser = new Mock<ICommandLineOptionParser<string>>(); mockParser.Setup(x => x.CanParse(option)).Returns(false); var target = new CommandLineOption<string>("s", "long name", mockParser.Object); target.Bind(option); }