Exemplo n.º 1
0
        static async Task Main(string[] args)
        {
            var services = ConfigureServices();
            var options  = new CommandLineParserOptions
            {
                AppName = "UsersManagementApp.exe"
            };

            var parser = new CommandLineParser <GlobalOptions>(options, services);

            parser.DiscoverCommands(Assembly.GetExecutingAssembly());

            parser.UseFluentValidations(config =>
            {
                config.AddValidator <RegisterOptions, RegisterValidator>();
            });

            var result = await parser.ParseAsync(args);

            if (result.HasErrors)
            {
                return;
            }

            if (result.Result.Verbose)
            {
                Console.WriteLine("Verbose specified!");
            }
        }
Exemplo n.º 2
0
        static async Task Main(string[] args)
        {
            var options = new CommandLineParserOptions
            {
                AppName = "cra"
            };
            var parser         = new CommandLineParser <ProgramOptions>();
            var result         = parser.Parse(args);
            var programOptions = result.Result;

            projectName = programOptions.Name;
            Console.WriteLine(projectName);


            Console.WriteLine("Location:" + location);
            string repoURL = @"https://github.com/lazyDefender/cra";

            CloneRepo($"{repoURL}.git");
            Directory.Move($@"{location}/cra", $@"{location}/{projectName}");
            RepoRemoveRemote($"origin");
            CreateRepo(projectName);
            string gitUsername = GetGitUsername();
            string newUrl      = $@"https://github.com/{gitUsername}/{projectName}.git";

            RepoSetRemote(newUrl);
            RepoPush();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="argSet">Argument set to create parser for.</param>
        /// <param name="options">Parser options.</param>
        public ArgumentSetParser(ArgumentSetDefinition argSet, CommandLineParserOptions options)
        {
            if (argSet == null)
            {
                throw new ArgumentNullException(nameof(argSet));
            }

            // Clone the argument set definition, as parsing may mutate it.
            ArgumentSet = argSet.DeepClone();

            // Save off the options provided; if none were provided, construct some quiet defaults.
            _options = options?.DeepClone() ?? CommandLineParserOptions.Quiet();

            // If no reporter was provided, use a no-op one.
            if (_options.Reporter == null)
            {
                _options.Reporter = err => { };
            }

            // If no file-system reader was provided, use our default implementation.
            if (_options.FileSystemReader == null)
            {
                _options.FileSystemReader = FileSystemReader.Create();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Executes one iteration of the loop.
        /// </summary>
        /// <returns>The result of executing.</returns>
        public CommandResult ExecuteOnce()
        {
            Client.DisplayPrompt();

            var args = ReadInput();

            if (args == null)
            {
                return(CommandResult.Terminate);
            }
            if (args.Length == 0)
            {
                return(CommandResult.Success);
            }

            var options = new CommandLineParserOptions
            {
                Reporter = error => Client.OnError(error.ToString().TrimEnd())
            };

            var commandGroup = new CommandGroup <TCommandType>();

            if (!CommandLineParser.Parse(args, commandGroup, options))
            {
                Client.OnError(Strings.InvalidUsage);
                return(CommandResult.UsageError);
            }

            return(commandGroup.Execute());
        }
Exemplo n.º 5
0
        public void TestSplitOnPostFixWorksCorrectly()
        {
            var settings = new CommandLineParserOptions();

            var mockTestOption1 = CreateMock(settings, "test").Object;
            var mockTestOption2 = CreateMock(settings, "test2", "test2").Object;
            var mockTestOption3 = CreateMock(settings, "test3").Object;
            var mockTestOption4 = CreateMock(settings, "blabla", "blabla").Object;

            var options = new[]
            {
                mockTestOption1,
                mockTestOption2,
                mockTestOption3,
                mockTestOption4
            };

            var input  = new[] { "--test=1", "-test2=\"some value\"", "--test3=some value", "-blabla", "third" };
            var output = input.SplitOnPostfix(settings, options).ToArray();

            Assert.Equal("--test", output[0]);
            Assert.Equal("1", output[1]);
            Assert.Equal("-test2", output[2]);
            Assert.Equal("\"some value\"", output[3]);
            Assert.Equal("--test3", output[4]);
            Assert.Equal("some value", output[5]);
            Assert.Equal("-blabla", output[6]);
            Assert.Equal("third", output[7]);
        }
        public CommandLineCommand(CommandLineParserOptions parserOptions, IArgumentResolverFactory resolverFactory, IContainerResolver containerResolver, TOption option)
        {
            m_parserOptions = parserOptions;
            m_commandOption = new TCommandOption();

            m_containerResolver = containerResolver;
            m_resolverFactory   = resolverFactory;
            m_baseOption        = option;

            if (m_parserOptions.EnableHelpOption)
            {
                var tokens = m_parserOptions.HelpOptionName.Split('|');

                if (tokens.Length > 1)
                {
                    m_helpOptionName     = $"{m_parserOptions.PrefixShortOption}{tokens[0]}";
                    m_helpOptionNameLong = $"{m_parserOptions.PrefixLongOption}{tokens[1]}";
                }
                else
                {
                    m_helpOptionName     = $"{m_parserOptions.PrefixLongOption}{tokens[0]}";
                    m_helpOptionNameLong = null;
                }
            }

            InitialzeModel();
        }
Exemplo n.º 7
0
        public UsagePrinter(CommandLineParserOptions parserOptions, ICommandLineCommandContainer container, IUsageBuilder builder)
        {
            m_parserOptions    = parserOptions;
            m_commandContainer = container;

            m_usageBuilder = builder;
        }
Exemplo n.º 8
0
        private static ExecutionParams GetExecutionParams(string[] args)
        {
            var options = new CommandLineParserOptions()
            {
                AppName = "Stone Test - Crawler", AutoPrintUsageAndErrors = true, EnableHelpOption = true
            };
            var parser = new CommandLineParser <ExecutionParams>(options);

            var parameters = parser.Parse(args);

            if (parameters.HasErrors)
            {
                Console.WriteLine($"The command line has {parameters.Errors.Count} erros...");
                return(null);
            }

            return(parameters.Result);
            //try
            //{
            //    try { parameters.DestinyFilePath = args[0].ToString(); } catch { Console.WriteLine($"The mandatory parameter: \"File path\" has missed.");Console.ReadKey();throw; }
            //    try { parameters.BufferLimit = Convert.ToInt32(args[1]);}catch { return parameters; }
            //    try { parameters.FileSizeLimit = Convert.ToInt32(args[2]); } catch { return parameters; }
            //    try { parameters.HeadLessModeActivated = Convert.ToInt32(args[3]) ==0?false:true; } catch { return parameters; }

            //    return parameters;
            //}
            //catch (Exception)
            //{
            //    Console.WriteLine("The mandatory file path parameter not specified. Example: \"C:\\temp\"");
            //    Console.ReadKey();
            //    throw;
            //}
        }
Exemplo n.º 9
0
 public CommandLineOptionBase(CommandLineParserOptions parserOptions, object source, LambdaExpression selector, IArgumentResolverFactory resolver)
 {
     m_parserOptions   = parserOptions ?? throw new ArgumentNullException(nameof(source));
     m_source          = source ?? throw new ArgumentNullException(nameof(source));
     m_selector        = selector ?? throw new ArgumentNullException(nameof(selector));
     m_resolverFactory = resolver ?? throw new ArgumentNullException(nameof(resolver));
 }
Exemplo n.º 10
0
        public CommandLineParser(Type commandType, CommandLineParserOptions parserOptions = CommandLineParserOptions.NONE)
        {
            _parserOptions = parserOptions;

            _options = new OptionGroupParser(commandType);

            _arguments = (from x in
                          from p in commandType.GetProperties()
                          select new { Property = p, Attribute = p.GetCustomAttribute <ArgumentsAttribute>() }
                          where x.Attribute != null
                          select new Arguments(x.Property, x.Attribute)).FirstOrDefault();

            _argumentsVerification = (from m in commandType.GetMethods()
                                      from a in m.GetCustomAttributes <ArgumentsVerificationAttribute>()
                                      select m).SingleOrDefault();
            if (_argumentsVerification != null)
            {
                // Check the return and parameter types
                if (_argumentsVerification.ReturnType != typeof(void))
                {
                    throw new NotSupportedException("Arguments Verification method does not return void.");
                }
                if (_argumentsVerification.GetParameters().Length != 0)
                {
                    throw new NotSupportedException("Arguments Verification method does not take parameters.");
                }
            }
        }
Exemplo n.º 11
0
        static int Main(string[] args)
        {
            Console.WriteLine("Parsing...");

            // Set up help options the way we want them.
            var helpOptions = new ArgumentSetHelpOptions()
                              .With()
                              .BlankLinesBetweenArguments(1)
                              .ShortNames(ArgumentShortNameHelpMode.IncludeWithLongName)
                              .DefaultValues(ArgumentDefaultValueHelpMode.PrependToDescription)
                              .TwoColumnLayout();

            // Wrap help options in general parsing options.
            var options = new CommandLineParserOptions {
                HelpOptions = helpOptions
            };

            // Try to parse.
            if (!CommandLineParser.TryParse(args, options, out ProgramArguments programArgs))
            {
                return(1);
            }

            Console.WriteLine("Successfully parsed.");

            return(0);
        }
        public async Task TestHelpOptionGetsParsedCorrectly(string helpOption, string[] args, bool fires)
        {
            bool calledFlag = false;

            var usagePrinterMock = new Mock <IUsagePrinter>();

            usagePrinterMock.Setup(mock => mock.PrintUsage()).Callback(() => calledFlag = true);
            usagePrinterMock.Setup(mock => mock.PrintCommandUsage(It.IsAny <ICommandLineCommand>())).Callback(() => calledFlag = true);
            usagePrinterMock.Setup(mock => mock.PrintOptionUsage(It.IsAny <ICommandLineOption>())).Callback(() => calledFlag   = true);

            Services.AddSingleton(usagePrinterMock.Object);

            var options = new CommandLineParserOptions
            {
                HelpOptionName = helpOption
            };

            var parser = new CommandLineParser <Options>(options, Services);

            var cmd = parser.AddCommand <CommandOptions>()
                      .Name("db")
                      .Description("Database commands");

            await parser.ParseAsync(args);

            Assert.Equal(fires, calledFlag);
        }
Exemplo n.º 13
0
        //Function name: ProcessCommandLineArguments
        //Function parameters => Return type: String[] => Void
        //Function Purpose: To handle passed in command line arguments
        public static Dictionary <string, string> ProcessComandLineArguments(string[] args)
        {
            Dictionary <string, string> arguments = new Dictionary <string, string>();
            bool submittedJSON = false;

            var options = new CommandLineParserOptions
            {
                AppName = "HARPOCRATES",
                AutoPrintUsageAndErrors = true
            };
            var parser = new CommandLineParser <CLIArgs>(options);

            var result = parser.Parse(args);

            if (result.HasErrors)
            {
                Console.Error.WriteLine("Error in command line arguments");
                System.Environment.Exit(1);
            }
            if (result.Result.JSONProfile != null)
            {
                submittedJSON = true;
                if (args.Length > 2)
                {
                    Console.Error.WriteLine("Too many arguments. If you are uploading a file. Only use -p command.");
                    System.Environment.Exit(2);
                }
            }

            return(HandleJSON(submittedJSON, result.Result, arguments));
        }
Exemplo n.º 14
0
        private static ArgumentDefinition CreateArgumentDescriptor(
            IMutableMemberInfo member,
            ArgumentBaseAttribute attribute,
            object defaultValues,
            ArgumentSetAttribute setAttribute,
            CommandLineParserOptions options,
            object fixedDestination)
        {
            if (!member.IsReadable || !member.IsWritable)
            {
                var declaringType = member.MemberInfo.DeclaringType;

                throw new InvalidArgumentSetException(member, string.Format(
                                                          CultureInfo.CurrentCulture,
                                                          Strings.MemberNotSupported,
                                                          member.MemberInfo.Name,
                                                          declaringType?.Name));
            }

            var defaultFieldValue = (defaultValues != null) ? member.GetValue(defaultValues) : null;

            return(new ArgumentDefinition(member,
                                          attribute,
                                          setAttribute,
                                          options,
                                          defaultFieldValue,
                                          fixedDestination: fixedDestination));
        }
Exemplo n.º 15
0
 /// <summary>
 /// Constructs an argument set from a type with reflection-based argument attributes.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="defaultValues">Optionally provides an object with default values.</param>
 /// <param name="options">Optionally provides additional options
 /// controlling how parsing proceeds.</param>
 public ArgumentSetDefinition(Type type, object defaultValues = null, CommandLineParserOptions options = null) :
     // Try to grab attributes from type.
     this(options, type.GetTypeInfo().GetSingleAttribute <ArgumentSetAttribute>())
 {
     // Scan the provided type for argument definitions.
     AddArgumentsFromTypeWithAttributes(type, defaultValues);
 }
Exemplo n.º 16
0
        public static void ParseCommand(string[] args)
        {
            var options = new CommandLineParserOptions
            {
                AppName = "TCP Tracker",
            };

            var parser = new CommandLineParser <ScriptOptions>(options);

            var result = parser.Parse(args);

            if (result.HasErrors)
            {
                ParseCommand(Console.ReadLine().Split(" "));
                return;
            }

            var programOptions = result.Result;

            //RunCommand();
            commandLocation = programOptions.commandLocation;
            outputLocation  = programOptions.outputLocation;
            ip = programOptions.IpAdress;
            var timer = new Timer(test, null, 0, programOptions.time * 1000 * 60);

            Console.Read();
        }
Exemplo n.º 17
0
        public void CommandLineParserUsesCorrectOptions()
        {
            var opt = new CommandLineParserOptions();

            var parser = new CommandLineParser(opt);

            Assert.Equal(opt, parser.ParserOptions);
        }
        public void TestThatRequiredPropertiesArePresentInQuietOptions()
        {
            var options = CommandLineParserOptions.Quiet();

            options.HelpOptions.Should().NotBeNull();
            options.Reporter.Should().NotBeNull();
            options.FileSystemReader.Should().NotBeNull();
        }
 public CommandLineOptionBase(CommandLineParserOptions parserOptions, object source, LambdaExpression selector, ICommandLineArgumentResolver resolver, ILogger logger)
 {
     m_parserOptions = parserOptions ?? throw new ArgumentNullException(nameof(source));
     m_source        = source ?? throw new ArgumentNullException(nameof(source));
     m_selector      = selector ?? throw new ArgumentNullException(nameof(selector));
     Resolver        = resolver ?? throw new ArgumentNullException(nameof(resolver));
     this.logger     = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Exemplo n.º 20
0
        /// <summary>
        /// Primary constructor.
        /// </summary>
        /// <param name="member">Field to describe.</param>
        /// <param name="attribute">Argument attribute on the field.</param>
        /// <param name="setAttribute">Attribute on the containing argument set.</param>
        /// <param name="options">Provides parser options.</param>
        /// <param name="defaultFieldValue">Default value for the field.</param>
        /// <param name="parentMember">Parent member under which this field sits.</param>
        /// <param name="fixedDestination">Optionally provides fixed parse destination object.</param>
        public ArgumentDefinition(IMutableMemberInfo member,
                                  ArgumentBaseAttribute attribute,
                                  ArgumentSetAttribute setAttribute,
                                  CommandLineParserOptions options,
                                  object defaultFieldValue        = null,
                                  IMutableMemberInfo parentMember = null,
                                  object fixedDestination         = null)
        {
            Debug.Assert(attribute != null);
            Debug.Assert(member != null);

            Member                = member;
            ParentMember          = parentMember;
            Attribute             = attribute;
            _setAttribute         = setAttribute;
            FixedDestination      = fixedDestination;
            _isPositional         = attribute is PositionalArgumentAttribute;
            _reporter             = options?.Reporter ?? (s => { });
            ArgumentType          = Attribute.GetArgumentType(member.MemberType);
            _collectionArgType    = AsCollectionType(ArgumentType);
            HasDefaultValue       = attribute.ExplicitDefaultValue || attribute.DynamicDefaultValue;
            _validationAttributes = GetValidationAttributes(ArgumentType, Member);
            _argumentParseContext = CreateParseContext(attribute, _setAttribute, options);

            LongName          = GetLongName(attribute, setAttribute, member.MemberInfo);
            ExplicitShortName = HasExplicitShortName(attribute);
            ShortName         = GetShortName(attribute, setAttribute, member.MemberInfo);
            DefaultValue      = GetDefaultValue(attribute, member, defaultFieldValue);

            var nullableBase = Nullable.GetUnderlyingType(member.MemberType);

            if (_collectionArgType != null)
            {
                _collectionValues = new ArrayList();
                _valueType        = _collectionArgType.ElementType;
            }
            else if (nullableBase != null)
            {
                // For nullable arguments, we use the wrapped type (T in
                // Nullable<T>) as the value type. Parsing an enum or int is the
                // same as parsing an enum? or int?, for example, since null can
                // only arise if the value was not provided at all.
                _valueType = Attribute.GetArgumentType(nullableBase);
            }
            else
            {
                _valueType = ArgumentType;
            }

            Debug.Assert(_valueType != null);

            if (Unique && !IsCollection)
            {
                throw new InvalidArgumentSetException(member, Strings.UniqueUsedOnNonCollectionArgument);
            }

            Debug.Assert(!string.IsNullOrEmpty(LongName));
        }
        public void InvalidOptionsThrowException(string shortOption, string longOption)
        {
            var options = new CommandLineParserOptions
            {
                PrefixShortOption = shortOption,
                PrefixLongOption  = longOption
            };

            Assert.Throws <ArgumentException>(() => new CommandLineParser(options, Services));
            Assert.Throws <ArgumentException>(() => new CommandLineParser <OrderModel>(options, Services));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Checks if the empty string is a valid value for this argument.
        /// </summary>
        /// <param name="parserOptions">Parser options.</param>
        /// <returns>true if it is valid; false otherwise.</returns>
        internal bool IsEmptyStringValid(CommandLineParserOptions parserOptions)
        {
            var options    = parserOptions.DeepClone().With().Quiet().Apply();
            var parseState = new ArgumentParser(ContainingSet, this, options, /*destination=*/ null);

            return(ArgumentType.TryParse(parseState.ParseContext, string.Empty, out object parsedEmptyString) &&
                   parseState.TryValidateValue(
                       parsedEmptyString,
                       new ArgumentValidationContext(parseState.ParseContext.FileSystemReader),
                       reportInvalidValue: false));
        }
Exemplo n.º 23
0
        /// <summary>
        /// Constructs an empty argument set.
        /// </summary>
        /// <param name="options">Optionally provides additional options
        /// controlling how parsing proceeds.</param>
        /// <param name="setAttribute">Optionally provides attribute information
        /// describing the attribute set.</param>
        public ArgumentSetDefinition(CommandLineParserOptions options = null, ArgumentSetAttribute setAttribute = null)
        {
            // Save off the options provided; if none were provided, construct some defaults.
            _options = options?.Clone() ?? new CommandLineParserOptions();

            // Save off set attributes; if none were provided, construct some defaults.
            Attribute = setAttribute ?? new ArgumentSetAttribute();

            // Set up private fields dependent on the ArgumentSetAttribute.
            _namedArgumentsByName = new Dictionary <string, ArgumentDefinition>(StringComparerToUse);
        }
        public void CustomInvokedPrinterWorksCorrectly(string[] args, bool cmdPassed, bool optPassed)
        {
            var builderMock = new Mock <IUsageBuilder>();

            var parserOptions = new CommandLineParserOptions
            {
                AutoPrintUsageAndErrors = false
            };

            Services.AddSingleton(builderMock.Object);

            Services.AddCommandLineParser <UsagePrinterGetsCalledOptions>(parserOptions);
            var parser = ResolveParser <UsagePrinterGetsCalledOptions>();

            parser.AddCommand <UsagePrinterCommandOptions>()
            .Name("cmd")
            .Required();

            var result = parser.Parse(args);

            builderMock.Verify(mock => mock.Build(), Times.Never());
            builderMock.Verify(mock => mock.AddCommand(It.IsAny <string>(), It.IsAny <ICommandLineCommandContainer>()), Times.Never());
            builderMock.Verify(mock => mock.AddOption(It.IsAny <ICommandLineOption>()), Times.Never());

            if (result.HelpRequested)
            {
                parser.Printer.PrintUsage(result.HelpRequestedFor);
            }

            if (result.HasErrors)
            {
                foreach (var err in result.Errors)
                {
                    if (!(err is BaseParserException baseParserException))
                    {
                        continue;
                    }

                    parser.Printer.PrintUsage(baseParserException.Argument);
                }
            }

            builderMock.Verify(
                mock => mock.Build(),
                ToTimes(result.HelpRequested || result.HasErrors));

            builderMock.Verify(
                mock => mock.AddCommand(It.IsAny <string>(), It.IsAny <ICommandLineCommand>()),
                ToTimes(cmdPassed));

            builderMock.Verify(
                mock => mock.AddOption(It.IsAny <ICommandLineOption>()),
                ToTimes(optPassed));
        }
Exemplo n.º 25
0
        static int Main(string[] args)
        {
            var cliParserOptions = new CommandLineParserOptions
            {
                AppName = "VCDiff.Core.Cli"
            };

            var result = VCDiffResult.NOOP;

            var parser = new CommandLineParser <ProgramOptions>();

            parser.AddCommand <CreateOptions>()
            .Name("create")
            .Required(false)
            .Description("Creates a delta patch from the given input")
            .OnExecuting((o, opt) => result = Create(opt));

            parser.AddCommand <PatchOptions>()
            .Name("patch")
            .Required(false)
            .Description("Appplies the give patch to the file")
            .OnExecuting((o, opt) => result = Patch(opt));

            var parserResult = parser.Parse(args);

            if (parserResult.HasErrors && !parserResult.HelpRequested)
            {
                result = VCDiffResult.Error;
            }

            switch (result)
            {
            case VCDiffResult.NOOP:
                parser.Printer.PrintUsage();
                break;

            case VCDiffResult.Succes:
            default:
                break;

            case VCDiffResult.Error:
                Console.Error.WriteLine("Unexpected error occured");

                return(-1);

            case VCDiffResult.EOD:
                Console.Error.WriteLine("Unexpected end of data");

                return(-2);
            }

            return(0);
        }
Exemplo n.º 26
0
        public void CommandLinerParserPassesResolverCorreclty()
        {
            var resolverMock = new Mock <IArgumentResolverFactory>();
            var options      = new CommandLineParserOptions();
            var parser       = new CommandLineParser(resolverMock.Object);

            Assert.Equal(resolverMock.Object, parser.ArgumentResolverFactory);

            parser = new CommandLineParser(options, resolverMock.Object);

            Assert.Equal(resolverMock.Object, parser.ArgumentResolverFactory);
            Assert.Equal(options, parser.ParserOptions);
        }
Exemplo n.º 27
0
        public void CommandLinerParserPassesContainerCorreclty()
        {
            var containerResolver = new Mock <IContainerResolver>();
            var options           = new CommandLineParserOptions();
            var parser            = new CommandLineParser(containerResolver.Object);

            Assert.Equal(containerResolver.Object, parser.ContainerResolver);

            parser = new CommandLineParser(options, containerResolver.Object);

            Assert.Equal(containerResolver.Object, parser.ContainerResolver);
            Assert.Equal(options, parser.ParserOptions);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Constructs a new stateful parser for the given argument.
        /// </summary>
        /// <param name="argSet">The argument set containing the argument to be parsed.</param>
        /// <param name="arg">The definition of the argument.</param>
        /// <param name="options">General options for parsing this argument set.</param>
        /// <param name="destination">The destination object into which the parsed result should go,
        /// if so desired; null otherwise to parse without saving results.</param>
        public ArgumentParser(ArgumentSetDefinition argSet, ArgumentDefinition arg, CommandLineParserOptions options,
                              object destination = null)
        {
            ArgumentSet       = argSet ?? throw new ArgumentNullException(nameof(argSet));
            Argument          = arg ?? throw new ArgumentNullException(nameof(arg));
            Reporter          = options?.Reporter ?? (s => { });
            DestinationObject = arg.FixedDestination ?? destination;
            ParseContext      = CreateParseContext(Argument, ArgumentSet.Attribute, options, DestinationObject);

            if (Argument.IsCollection)
            {
                CollectionValues = GenericCollectionFactory.CreateList(Argument.CollectionArgumentType.ElementType.Type);
            }
        }
Exemplo n.º 29
0
        public ArgumentManager(string[] args, CommandLineParserOptions parserOptions, string shortHelpOption, string longHelpOption, ICollection <CommandLineCommandBase> commands, ICollection <ICommandLineOption> options)
        {
            resultCache = new Dictionary <IArgument, ArgumentModel>(commands.Count + options.Count);

            this.parserOptions      = parserOptions;
            this.helpOptionsEnabled = parserOptions.EnableHelpOption;
            this.shortHelpOption    = shortHelpOption;
            this.longHelpOption     = longHelpOption;
            this.hasPostfixDefined  = !string.IsNullOrWhiteSpace(parserOptions.PostfixOption);

            this.args = new List <ArgumentValueHolder>(
                args.SplitOnPostfix(parserOptions, GetCommandLineOptions(options, commands))
                .Select(arg => new ArgumentValueHolder
            {
                Argument = arg
            }));

            ParseCommands(commands);

            ParseOptions(options);

            CheckHelpCommands();

            // pre cache results
            foreach (var item in this.args)
            {
                if (item.ArgModel == null)
                {
                    continue;
                }

                int nextIndex = item.Index + 1;

                var argValue = nextIndex < this.args.Count ? this.args[nextIndex] : null;

                var argModel = new ArgumentModel
                {
                    Key = item.Argument,
                    // this checks if the argument is used in an other command/option.
                    Value = (argValue?.Used ?? true) ? null : argValue.Argument
                };

                if (resultCache.ContainsKey(item.ArgModel))
                {
                    continue;
                }

                resultCache.Add(item.ArgModel, argModel);
            }
        }
Exemplo n.º 30
0
        public void FileDoesNotExist()
        {
            var reader  = CreateReaderThatThrows(new FileNotFoundException());
            var options = new CommandLineParserOptions {
                FileSystemReader = reader
            };

            CommandLineParser.Parse(
                new[] { "@foo" },
                new Arguments(),
                options).Should().BeFalse();

            reader.Received().GetLines("foo");
        }