Beispiel #1
0
 /// <summary>
 /// Validates the specified <see cref="ICommandLineOption"/> against all the registered rules.
 /// </summary>
 /// <param name="commandLineOption">The <see cref="ICommandLineOption"/> to validate.</param>
 public void Validate(ICommandLineOption commandLineOption)
 {
     foreach (var rule in _rules)
     {
         rule.Validate(commandLineOption);
     }
 }
Beispiel #2
0
 /// <summary>
 /// Validates the specified <see cref="ICommandLineOption"/> against all the registered rules.
 /// </summary>
 /// <param name="commandLineOption">The <see cref="ICommandLineOption"/> to validate.</param>
 /// <param name="stringComparison"></param>
 public void Validate(ICommandLineOption commandLineOption, StringComparison stringComparison)
 {
     foreach (var rule in _rules)
     {
         rule.Validate(commandLineOption, stringComparison);
     }
 }
 /// <summary>
 /// Validates the specified <see cref="ICommandLineOption"/> against all the registered rules.
 /// </summary>
 /// <param name="commandLineOption">The <see cref="ICommandLineOption"/> to validate.</param>
 public void Validate(ICommandLineOption commandLineOption)
 {
     foreach (var rule in _rules)
     {
         rule.Validate(commandLineOption);
     }
 }
        ///// <summary>
        ///// Gets the <see cref="StringComparison"/> type used for duplicates.
        ///// </summary>
        //private StringComparison ComparisonType
        //{
        //    get { return _container.IsCaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; }
        //}

        /// <summary>
        /// Verifies that the specified <see cref="ICommandLineOption"/> will not cause any duplication.
        /// </summary>
        /// <param name="commandLineOption">The <see cref="ICommandLineOption"/> to validate.</param>
        /// <param name="stringComparison"></param>
        public void Validate(ICommandLineOption commandLineOption, StringComparison stringComparison)
        {
            foreach (var option in _container.Options)
            {
                if (option.HasCommand)
                {
                    if (CommandsAreEqual(option.Command, commandLineOption.Command, stringComparison))
                    {
                        if (string.IsNullOrEmpty(commandLineOption.ShortName) == false)
                        {
                            ValuesAreEqual(commandLineOption.ShortName, option.ShortName, stringComparison);
                        }

                        if (string.IsNullOrEmpty(commandLineOption.LongName) == false)
                        {
                            ValuesAreEqual(commandLineOption.LongName, option.LongName, stringComparison);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(commandLineOption.ShortName) == false)
                    {
                        ValuesAreEqual(commandLineOption.ShortName, option.ShortName, stringComparison);
                    }

                    if (string.IsNullOrEmpty(commandLineOption.LongName) == false)
                    {
                        ValuesAreEqual(commandLineOption.LongName, option.LongName, stringComparison);
                    }
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Verifies that the specified <see cref="ICommandLineOption"/> has a valid short/long name combination.
        /// </summary>
        /// <param name="commandLineOption">The <see cref="ICommandLineOption"/> to validate. This must not be null.</param>
        /// <exception cref="ArgumentNullException">if <paramref name="commandLineOption"/> is null.</exception>
        public void Validate(ICommandLineOption commandLineOption)
        {
            if (commandLineOption == null) throw new ArgumentNullException("commandLineOption");

            ValidateShortName(commandLineOption.ShortName);
            ValidateLongName(commandLineOption.LongName);
            ValidateShortAndLongName(commandLineOption.ShortName, commandLineOption.LongName);
        }
 protected static void SetupOptionWith(char shortName)
 {
     CatchAnyError(() =>
     {
         var ret = sut.Setup <TestType>(shortName);
         option  = sut.Options.SingleOrDefault(x => ReferenceEquals(x, ret));
     });
 }
 /// <summary>
 /// Initialises a new instance of the <see cref="CommandLineParserErrorBase"/> class.
 /// </summary>
 /// <param name="cmdOption">The <see cref="ICommandLineOption"/> this error relates too. This must not be <c>null</c>.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="cmdOption"/> is <c>null</c>.</exception>
 protected CommandLineParserErrorBase(ICommandLineOption cmdOption)
 {
     if (cmdOption == null)
     {
         throw new ArgumentNullException("cmdOption");
     }
     this.Option = cmdOption;
 }
			protected static void SetupOptionWith(char shortName)
			{
				CatchAnyError(() =>
				{
					var ret = sut.Setup<TestType>(shortName);
					option = sut.Options.SingleOrDefault(x => ReferenceEquals(x, ret));
				});
			}
Beispiel #9
0
            public void MarkOrderedOptionAsProcessed(ICommandLineOption option)
            {
                ProcessingOrderedOptions = true;
                orderedOptions.Remove(option);

                if (AllOrderedOptionsProcessed)
                {
                    ProcessingOrderedOptions = false;
                }
            }
Beispiel #10
0
 private IEnumerable <string> GetNamesRepresentation(ICommandLineOption option)
 {
     if (option.HasShortName)
     {
         yield return($"-{option.ShortName}");
     }
     if (option.HasLongName)
     {
         yield return($"--{option.LongName}");
     }
 }
Beispiel #11
0
        /// <summary>
        /// Verifies that the specified <see cref="ICommandLineOption"/> has a valid short/long name combination.
        /// </summary>
        /// <param name="commandLineOption">The <see cref="ICommandLineOption"/> to validate. This must not be null.</param>
        /// <param name="stringComparison"></param>
        /// <exception cref="ArgumentNullException">if <paramref name="commandLineOption"/> is null.</exception>
        public void Validate(ICommandLineOption commandLineOption, StringComparison stringComparison)
        {
            if (commandLineOption == null)
            {
                throw new ArgumentNullException("commandLineOption");
            }

            ValidateShortName(commandLineOption.ShortName);
            ValidateLongName(commandLineOption.LongName);
            ValidateShortAndLongName(commandLineOption.ShortName, commandLineOption.LongName);
        }
        private static string CreateMessage(ICommandLineOption option)
        {
            bool hasShort = option.HasShortName;
            bool hasLong  = option.HasLongName;
            bool hasBoth  = hasShort && hasLong;

            string hasBothSeperator = hasBoth ? "|" : string.Empty;
            string shortName        = hasShort ? $"{option.ShortName}" : string.Empty;
            string longName         = hasLong ? $"{option.LongName}" : string.Empty;

            return($"Required option '{shortName}{hasBothSeperator}{longName}' not found!");
        }
        private static string CreateMessage(ICommandLineOption option, ArgumentModel argModel)
        {
            bool hasShort = option.HasShortName;
            bool hasLong  = option.HasLongName;
            bool hasBoth  = hasShort && hasLong;

            string hasBothSeperator = hasBoth ? "|" : string.Empty;
            string shortName        = hasShort ? option.ShortName : string.Empty;
            string longName         = hasLong ? option.LongName : string.Empty;

            return($"Unable to parse option '{shortName}{hasBothSeperator}{longName}' value '{argModel.Value}' is invalid!");
        }
Beispiel #14
0
        private static string CreateMessage(ICommandLineOption option)
        {
            var hasShort = option.HasShortName;
            var hasLong  = option.HasLongName;
            var hasBoth  = hasShort && hasLong;

            var hasBothSeperator = hasBoth ? "|" : string.Empty;
            var shortName        = hasShort ? $"{option.ShortName}" : string.Empty;
            var longName         = hasLong ? $"{option.LongName}" : string.Empty;
            var optionString     = hasShort || hasLong ? string.Empty : option.ToString();

            return($"Required option '{shortName}{hasBothSeperator}{longName}{optionString}' not found!");
        }
Beispiel #15
0
        private bool ValidClusteredOption(ICommandLineOption option)
        {
            if (!option.HasShortName)
            {
                return(false);
            }

            if (results.ContainsKey(option))
            {
                return(false);
            }

            return(true);
        }
Beispiel #16
0
        /// <summary>
        /// Formats the short and long names into one <see cref="System.String"/>.
        /// </summary>
        static string FormatValue(ICommandLineOption cmdOption)
        {
            if (cmdOption.ShortName.IsNullOrWhiteSpace())
            {
                return(cmdOption.LongName);
            }

            if (cmdOption.LongName.IsNullOrWhiteSpace())
            {
                return(cmdOption.ShortName);
            }

            return(cmdOption.ShortName + ":" + cmdOption.LongName);
        }
Beispiel #17
0
        /// <summary>
        /// Verifies that the specified <see cref="ICommandLineOption"/> will not cause any duplication.
        /// </summary>
        /// <param name="commandLineOption">The <see cref="ICommandLineOption"/> to validate.</param>
        public void Validate(ICommandLineOption commandLineOption)
        {
            foreach (var option in _parser.Options)
            {
                if (string.IsNullOrEmpty(commandLineOption.ShortName) == false)
                {
                    ValuesAreEqual(commandLineOption.ShortName, option.ShortName);
                }

                if (string.IsNullOrEmpty(commandLineOption.LongName) == false)
                {
                    ValuesAreEqual(commandLineOption.LongName, option.LongName);
                }
            }
        }
		/// <summary>
		/// Verifies that the specified <see cref="ICommandLineOption"/> will not cause any duplication.
		/// </summary>
		/// <param name="commandLineOption">The <see cref="ICommandLineOption"/> to validate.</param>
		public void Validate(ICommandLineOption commandLineOption)
		{
			foreach (var option in _parser.Options)
			{
				if (string.IsNullOrEmpty(commandLineOption.ShortName) == false)
				{
					ValuesAreEqual(commandLineOption.ShortName, option.ShortName);
				}

				if (string.IsNullOrEmpty(commandLineOption.LongName) == false)
				{
					ValuesAreEqual(commandLineOption.LongName, option.LongName);
				}				
			}
		}
Beispiel #19
0
        private static string GetParametersString(ICommandLineOption option)
        {
            var b = new StringBuilder();

            if (!option.ShortName.IsNullOrEmpty())
            {
                b.Append("/").Append(option.ShortName);
            }
            if (!option.LongName.IsNullOrEmpty())
            {
                b.Append(option.ShortName.IsNullOrEmpty() ? "/" : ", /");
                b.Append(option.LongName);
            }
            return(b.ToString());
        }
        public static Dictionary <string, string> ToDictionary(this ICommandLineOption command, string prefix = "cmd_")
        {
            string GetKey(string key)
            {
                return($"{prefix}{key}");
            }

            var c = command.GetType()
                    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                    .ToDictionary(prop => GetKey(prop.Name.ToLowerInvariant()), prop => prop.GetValue(command, null)?.ToString());

            if (command is IVariableInteractivityCommand interactivityCommand)
            {
                c[GetKey("interactivity")] = GetInteractivityLevel(interactivityCommand).ToString().ToLowerInvariant();
                c.Remove(GetKey("interactive"));
                c.Remove(GetKey("passive"));
                c.Remove(GetKey("silent"));
            }

            return(c);
        }
Beispiel #21
0
        private string CreateOptionLine(ICommandLineOption option)
        {
            var optionLine = LinePadding;

            optionLine += string.Join(", ", GetNamesRepresentation(option));
            if (optionLine.Length * 2 > TextWidth)
            {
                optionLine += "\n" + LinePadding + LinePadding + WrapString(2 * LinePadding.Length, option.Description);
            }
            else
            {
                var separator = new string(' ', Math.Max(0, 20 - optionLine.Length)) + new string(' ', 5);
                optionLine += separator;
                optionLine += WrapString(optionLine.Length, option.Description);
            }
            if (optionLine.Length > TextWidth)
            {
                optionLine += "\n";
            }

            return(optionLine);
        }
 /// <summary>
 /// Initialises a new instance of the <see cref="CommandLineParserErrorBase"/> class.
 /// </summary>
 /// <param name="cmdOption">The <see cref="ICommandLineOption"/> this error relates too. This must not be <c>null</c>.</param>
 /// <param name="parsedOption">The parsed option that caused the error.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="cmdOption"/> is <c>null</c>.</exception>
 public OptionSyntaxParseError(ICommandLineOption cmdOption, ParsedOption parsedOption)
     : base(cmdOption)
 {
     ParsedOption = parsedOption;
 }
 /// <inheritdoc/>
 public virtual void PrintUsage(ICommandLineOption option)
 => PrintOptionUsage(option);
		/// <summary>
		/// Initialises a new instance of the <see cref="CommandLineParserErrorBase"/> class.
		/// </summary>
		/// <param name="cmdOption">The <see cref="ICommandLineOption"/> this error relates too. This must not be <c>null</c>.</param>
		/// <exception cref="ArgumentNullException">If <paramref name="cmdOption"/> is <c>null</c>.</exception>
		protected CommandLineParserErrorBase(ICommandLineOption cmdOption)
		{
			if (cmdOption == null) throw new ArgumentNullException("cmdOption");
			this.Option = cmdOption;
		}
 /// <inheritdoc/>
 public virtual void PrintOptionUsage(ICommandLineOption option)
 {
     Builder.AddOption(option);
     console.WriteLine(Builder.Build());
 }
Beispiel #26
0
 public void PrintUsage(ICommandLineOption option)
 {
     m_usageBuilder.PrintOption(option);
     m_usageBuilder.Print();
 }
        /// <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);
        }
Beispiel #28
0
 private static string GetLineForOption(ICommandLineOption option, int padding)
 {
     return(string.Format("\t{0}:{1}{2}", option.ShortName, option.LongName.PadRight(padding), option.Description));
 }
Beispiel #29
0
 private static string GetLineForOption(ICommandLineOption option, int padding)
 {
     return string.Format("\t{0}:{1}{2}", option.ShortName, option.LongName.PadRight(padding), option.Description);
 }
Beispiel #30
0
 /// <summary>
 /// Initialises a new instance of the <see cref="CommandLineParserErrorBase"/> class.
 /// </summary>
 /// <param name="cmdOption">The <see cref="ICommandLineOption"/> this error relates too. This must not be <c>null</c>.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="cmdOption"/> is <c>null</c>.</exception>
 public UnexpectedValueParseError(ICommandLineOption cmdOption) :
     base(cmdOption)
 {
 }
Beispiel #31
0
 /// <summary>
 /// Initialises a new instance of the <see cref="CommandLineParserErrorBase"/> class.
 /// </summary>
 /// <param name="cmdOption">The <see cref="ICommandLineOption"/> this error relates too. This must not be <c>null</c>.</param>
 /// <param name="parsedOption">The parsed option that caused the error.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="cmdOption"/> is <c>null</c>.</exception>
 public OptionSyntaxParseError(ICommandLineOption cmdOption, ParsedOption parsedOption) :
     base(cmdOption)
 {
     ParsedOption = parsedOption;
 }
Beispiel #32
0
 /// <summary>
 /// Creates a new <see cref="OptionNotFoundException"/> for a given <see cref="ICommandLineOption"/>
 /// </summary>
 /// <param name="option">The option that was not found</param>
 public OptionNotFoundException(ICommandLineOption option)
     : base(option, CreateMessage(option))
 {
 }
        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);
        }
 /// <summary>
 /// Initialises a new instance of the <see cref="CommandLineParserErrorBase"/> class.
 /// </summary>
 /// <param name="cmdOption">The <see cref="ICommandLineOption"/> this error relates too. This must not be <c>null</c>.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="cmdOption"/> is <c>null</c>.</exception>
 public UnexpectedValueParseError(ICommandLineOption cmdOption)
     : base(cmdOption)
 {
 }
		/// <summary>
		/// Initialises a new instance of the <see cref="CommandLineParserErrorBase"/> class.
		/// </summary>
		/// <param name="cmdOption">The <see cref="ICommandLineOption"/> this error relates too. This must not be <c>null</c>.</param>
		/// <exception cref="ArgumentNullException">If <paramref name="cmdOption"/> is <c>null</c>.</exception>
		public ExpectedOptionNotFoundParseError(ICommandLineOption cmdOption) :
			base(cmdOption)
		{
		}
 /// <summary>
 /// Formats the short and long names into one <see cref="System.String"/>.
 /// </summary>
 static string FormatValue(ICommandLineOption cmdOption)
 {
     return cmdOption.LongName.IsNullOrWhiteSpace()
                 ? cmdOption.ShortName
                 : cmdOption.ShortName + ":" + cmdOption.LongName;
 }
Beispiel #37
0
 /// <summary>
 /// Creates a new <see cref="OptionParseException"/>
 /// </summary>
 /// <param name="option">The failed option</param>
 /// <param name="argModel">The specified argument</param>
 public OptionParseException(ICommandLineOption option, ArgumentModel argModel)
     : base(option, CreateMessage(option, argModel))
 {
     ArgumentModel = argModel;
 }
 /// <summary>
 /// Initialises a new instance of the <see cref="CommandLineParserErrorBase"/> class.
 /// </summary>
 /// <param name="cmdOption">The <see cref="ICommandLineOption"/> this error relates too. This must not be <c>null</c>.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="cmdOption"/> is <c>null</c>.</exception>
 public ExpectedOptionNotFoundParseError(ICommandLineOption cmdOption) :
     base(cmdOption)
 {
 }