Пример #1
0
        public void Parse(string[] args)
        {
            if ((args.Length == 0))
            {
                myResult = CommandLineParserResult.Usage;
                return;
            }

            bool parseOk = true;

            foreach (string item in args)
            {
                if ((item.StartsWith("-", StringComparison.InvariantCulture) && (item.Length >= 2) && parseOk))
                {
                    switch (item.Substring(1, 1).ToUpper(System.Globalization.CultureInfo.InvariantCulture))
                    {
                    case "P":
                        myPlaybackDeviceName = item.Substring(2);
                        break;

                    case "R":
                        myRecordingDeviceName = item.Substring(2);
                        break;

                    case "?":
                    case "H":
                        myResult = CommandLineParserResult.Usage;
                        break;

                    default:
                        parseOk      = false;
                        myParseError = item;
                        myResult     = CommandLineParserResult.Fail;
                        break;
                    }
                }
                else
                {
                    parseOk      = false;
                    myParseError = item;
                    myResult     = CommandLineParserResult.Fail;
                }
            }

            if (((myResult != CommandLineParserResult.Fail) && (myResult != CommandLineParserResult.Usage) && parseOk))
            {
                myResult = CommandLineParserResult.OK;
            }
        }
        /// <summary>
        /// Parses the specified <see><cref>T:System.String[]</cref></see> using the setup Options.
        /// </summary>
        /// <param name="args">The <see><cref>T:System.String[]</cref></see> to parse.</param>
        /// <returns>An <see cref="ICommandLineParserResult"/> representing the results of the parse operation.</returns>
        public ICommandLineParserResult Parse(string[] args)
        {
            if (SkipTheFirstArg)
            {
                args = args.Skip(1).ToArray();
            }

            var parserEngineResult = this.ParserEngine.Parse(args, HasCommands);
            var parsedOptions      = parserEngineResult.ParsedOptions.ToList();

            var result = new CommandLineParserResult {
                EmptyArgs = parsedOptions.IsNullOrEmpty(), RawResult = parserEngineResult
            };

            if (this.HelpOption.ShouldShowHelp(parsedOptions, StringComparison))
            {
                result.HelpCalled = true;
                this.HelpOption.ShowHelp(this.Options);
                return(result);
            }

            if (parserEngineResult.HasCommand)
            {
                var match = Commands.SingleOrDefault(cmd => cmd.Name.Equals(parserEngineResult.Command, this.StringComparison));
                if (match != null)
                {
                    var result2 = ParseOptions(match.Options, parsedOptions, result);
                    if (result2.HasErrors == false)
                    {
                        match.ExecuteOnSuccess();
                    }
                    return(result2);
                }
            }

            return(ParseOptions(this.Options, parsedOptions, result));
        }
        /// <summary>
        /// Parses the specified <see><cref>T:System.String[]</cref></see> using the setup Options.
        /// </summary>
        /// <param name="args">The <see><cref>T:System.String[]</cref></see> to parse.</param>
        /// <returns>An <see cref="ICommandLineParserResult"/> representing the results of the parse operation.</returns>
        public ICommandLineParserResult Parse(string[] args)
        {
            var parserEngineResult = this.ParserEngine.Parse(args);
            var parsedOptions      = parserEngineResult.ParsedOptions.ToList();

            var result = new CommandLineParserResult {
                EmptyArgs = parsedOptions.IsNullOrEmpty()
            };

            if (this.HelpOption.ShouldShowHelp(parsedOptions, StringComparison))
            {
                result.HelpCalled = true;
                this.HelpOption.ShowHelp(this.Options);
                return(result);
            }

            foreach (var setupOption in this.Options)
            {
                /*
                 * Step 1. match the setup Option to one provided in the args by either long or short names
                 * Step 2. if the key has been matched then bind the value
                 * Step 3. if the key is not matched and it is required, then add a new error
                 * Step 4. the key is not matched and optional, bind the default value if available
                 */

                // Step 1
                ICommandLineOption option = setupOption;
                var match = parsedOptions.FirstOrDefault(pair =>
                                                         pair.Key.Equals(option.ShortName, this.StringComparison) || // tries to match the short name
                                                         pair.Key.Equals(option.LongName, this.StringComparison)); // or else the long name

                if (match != null)                                                                                 // Step 2
                {
                    try
                    {
                        option.Bind(match);
                    }
                    catch (OptionSyntaxException)
                    {
                        result.Errors.Add(new OptionSyntaxParseError(option, match));
                        if (option.HasDefault)
                        {
                            option.BindDefault();
                        }
                    }

                    parsedOptions.Remove(match);
                }
                else
                {
                    if (option.IsRequired)                     // Step 3
                    {
                        result.Errors.Add(new ExpectedOptionNotFoundParseError(option));
                    }
                    else if (option.HasDefault)
                    {
                        option.BindDefault();                         // Step 4
                    }
                    result.UnMatchedOptions.Add(option);
                }
            }

            parsedOptions.ForEach(item => result.AdditionalOptionsFound.Add(new KeyValuePair <string, string>(item.Key, item.Value)));

            result.ErrorText = ErrorFormatter.Format(result.Errors);

            return(result);
        }
        private ICommandLineParserResult ParseOptions(IEnumerable <ICommandLineOption> options, List <ParsedOption> parsedOptions, CommandLineParserResult result)
        {
            /*
             * Step 1. match the setup Option to one provided in the args by either long or short names
             * Step 2. if the key has been matched then bind the value
             * Step 3. if the key is not matched and it is required, then add a new error
             * Step 4. the key is not matched and optional, bind the default value if available
             */
            var matchedOptions = new HashSet <ParsedOption>();
            var optionIndex    = 0;

            foreach (var setupOption in options)
            {
                // Step 1
                ICommandLineOption option = setupOption;
                var matchIndex            = parsedOptions.FindIndex(pair =>
                                                                    !matchedOptions.Contains(pair) &&
                                                                    (pair.Key.Equals(option.ShortName, this.StringComparison) || // tries to match the short name
                                                                     pair.Key.Equals(option.LongName, this.StringComparison))// or else the long name
                                                                    );

                if (matchIndex > -1) // Step 2
                {
                    var match = parsedOptions[matchIndex];

                    match.SetupCommand = option;
                    match.SetupOrder   = optionIndex++;
                    matchedOptions.Add(match);
                }
                else if (setupOption.UseForOrphanArgs && result.RawResult.AdditionalValues.Any())
                {
                    try
                    {
                        var parser      = new OptionArgumentParser(SpecialCharacters);
                        var blankOption = new ParsedOption();
                        parser.ParseArguments(result.RawResult.AdditionalValues, blankOption);
                        setupOption.Bind(blankOption);
                    }
                    catch (OptionSyntaxException)
                    {
                        result.Errors.Add(new OptionSyntaxParseError(option, null));
                        if (option.HasDefault)
                        {
                            option.BindDefault();
                        }
                    }
                }
                else
                {
                    if (option.IsRequired) // Step 3
                    {
                        result.Errors.Add(new ExpectedOptionNotFoundParseError(option));
                    }
                    else if (option.HasDefault)
                    {
                        option.BindDefault(); // Step 4
                    }
                    result.UnMatchedOptions.Add(option);
                }
            }

            foreach (var match in ParseSequence == ParseSequence.SameAsSetup ? matchedOptions.OrderBy(o => o.SetupOrder) : matchedOptions.OrderBy(o => o.Position))
            {
                try
                {
                    match.SetupCommand.Bind(match);
                }
                catch (OptionSyntaxException)
                {
                    result.Errors.Add(new OptionSyntaxParseError(match.SetupCommand, match));
                    if (match.SetupCommand.HasDefault)
                    {
                        match.SetupCommand.BindDefault();
                    }
                }
            }

            parsedOptions
            .Where(item => matchedOptions.Contains(item) == false)
            .ForEach(item => result.AdditionalOptions.Add(item));

            result.ErrorText = ErrorFormatter.Format(result.Errors);

            return(result);
        }