コード例 #1
0
 /// <summary>Initializes a new instance of the <see cref="OptionPropertyBase"/> class.</summary>
 /// <param name="option">Option this property is for</param>
 /// <param name="allowSpaceDelimitedValue">Flag indicating if this property allows a space delimited value</param>
 /// <param name="isCollection">Flag to indicate if the property is a collection</param>
 /// <param name="requiresValue">Flag to indicate if the property requires a value</param>
 protected OptionPropertyBase(CommandlineOption option, bool allowSpaceDelimitedValue, bool isCollection, bool requiresValue)
 {
     Option = option;
     AllowSpaceDelimitedValue = allowSpaceDelimitedValue;
     IsCollection             = isCollection;
     RequiresValue            = requiresValue;
 }
        /// <inheritdoc/>
        public IOptionProperty GetPropertyForOption(object instance, CommandlineOption option)
        {
            string name = option.Name;

            foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(instance))
            {
                var    argsAttribute            = prop.Attributes.OfType <CommandlineArgAttribute>( ).SingleOrDefault( );
                string longName                 = argsAttribute?.LongName ?? prop.Name;
                string shortName                = argsAttribute?.ShortName ?? string.Empty;
                bool   isCollection             = prop.PropertyType.IsCollection( );
                bool   allowSpaceDelimitedValue = argsAttribute?.AllowSpaceDelimitedValue ?? false;
                bool   requiresValue            = prop.PropertyType != typeof(bool);

                // Check the short and long names of the CommandLineArgAttribute, if there is one
                if (!DashesDistinct || (DashesDistinct && option.Delimiter == "-") || (AllowSlash && option.Delimiter == "/"))
                {
                    if (Comparer.Compare(shortName, name) == 0)
                    {
                        return(new ReflectionOptionProperty(instance, prop, option, allowSpaceDelimitedValue, isCollection, requiresValue));
                    }
                }

                if (!DashesDistinct || (DashesDistinct && option.Delimiter == "--") || (AllowSlash && option.Delimiter == "/"))
                {
                    if (Comparer.Compare(longName, name) == 0)
                    {
                        return(new ReflectionOptionProperty(instance, prop, option, allowSpaceDelimitedValue, isCollection, requiresValue));
                    }
                }
            }

            // property for the argument wasn't found
            throw new CommandlineParseException(CultureInfo.CurrentUICulture, Resources.UnknownOption_0, name);
        }
コード例 #3
0
 /// <summary>
 /// Returns whether there's a value defined for the specified <see cref="CommandlineOption"/>.
 /// </summary>
 /// <param name="option"><see cref="CommandlineOption"/> to check for an associated value.</param>
 /// <returns></returns>
 public bool IsDefined(CommandlineOption option)
 {
     if (_options == null)
     {
         Parse();
     }
     return(_options != null && _options.ContainsKey(option));
 }
コード例 #4
0
 /// <summary>
 /// Returns the associated value for the specified <see cref="CommandlineOption"/>.
 /// </summary>
 /// <exception cref="ArgumentException">
 /// An <see cref="ArgumentException"/> is thrown when no value is associated to <paramref name="option"/>.
 /// </exception>
 /// <param name="option"><see cref="CommandlineOption"/> to return the associated value for.</param>
 /// <returns>The value associated to the specified <see cref="CommandlineOption"/>.</returns>
 public string GetOption(CommandlineOption option)
 {
     if (!IsDefined(option))
     {
         throw new ArgumentException("There is no value associated to " + option);
     }
     return(_options[option]);
 }
コード例 #5
0
        public void OptionTests( )
        {
            CommandlineOption option = Option.Parse("-f0");

            Assert.IsNotNull(option);
            Assert.AreEqual("-f0", option.Text);
            Assert.AreEqual("-", option.SwitchLeader);
            Assert.AreEqual("f0", option.Name);
            Assert.IsNull(option.Delimiter);
            Assert.IsNull(option.Value);
        }
コード例 #6
0
 internal ReflectionOptionProperty(object instance
                                   , PropertyDescriptor prop
                                   , CommandlineOption option
                                   , bool allowSpaceDelimitedValue
                                   , bool isCollection
                                   , bool requiresValue
                                   )
     : base(option, allowSpaceDelimitedValue, isCollection, requiresValue)
 {
     Instance = instance;
     Prop     = prop;
 }
        public void GetMultiPropertyTest( )
        {
            var options  = new TestOptions( );
            var provider = new ReflectionOptionPropertyProvider( );

            Assert.IsNotNull(provider);
            var             option = new CommandlineOption("-", "m", ":", new CommandlineValue("'Multi 1'"));
            IOptionProperty prop   = provider.GetPropertyForOption(options, option);

            Assert.IsNotNull(prop);
            Assert.AreSame(prop.Option, option);
            Assert.IsFalse(prop.AllowSpaceDelimitedValue);
            Assert.IsFalse(prop.IsSet);
            Assert.IsTrue(prop.IsCollection);
        }
        public void SetMultiPropertyTest( )
        {
            var options  = new TestOptions( );
            var provider = new ReflectionOptionPropertyProvider( );

            Assert.IsNotNull(provider);
            var             option = new CommandlineOption("-", "m", ":", new CommandlineValue("'Multi 1'"));
            IOptionProperty prop   = provider.GetPropertyForOption(options, option);

            Assert.IsNotNull(prop);
            Assert.AreSame(prop.Option, option);
            Assert.IsFalse(prop.IsSet);
            prop.BindValue( );
            Assert.IsFalse(prop.IsSet);
            Assert.AreEqual(1, options.MultiOption.Count, "Expected count of 1 since item should have been added");
            Assert.AreEqual(option.Value.Text, options.MultiOption[0]);
        }
コード例 #9
0
        /// <summary>
        /// Defines the options you require for your program. You should
        /// pass if the options as a string array. There are two modifiers
        /// you can use to specify option arguments. Use "=" at the end of
        /// your option to specify that this option has to have an argument,
        /// and use =? at the end of your option to specify that an argument
        /// is optional.
        /// </summary>
        /// <example>
        /// <code>
        /// GetOpt.SetOpts(new string[] {"a", "b", "foo=", "bar=?"})
        /// </code>
        /// </example>
        /// <param name="options">
        /// A string  array of the options without the preceding
        /// "-", "--" or "/".
        /// </param>
        public void SetOpts(string[] options)
        {
            foreach (string option in options)
            {
                CommandlineOption optionStruct = new CommandlineOption();

                // Argument required
                if (option.EndsWith("="))
                {
                    optionStruct.option      = option.Substring(0, option.Length - 1);
                    optionStruct.argRequired = true;

                    // Argument optional
                }
                else if (option.EndsWith("=?"))
                {
                    optionStruct.option      = option.Substring(0, option.Length - 2);
                    optionStruct.argOptional = true;

                    // No argument
                }
                else
                {
                    optionStruct.option = option;
                }

                if (optionStruct.option.Length == 1)
                {
                    this.shortOpts.Add(optionStruct.option, optionStruct);
                }
                else
                {
                    this.longOpts.Add(optionStruct.option, optionStruct);
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Initiates the parsing of the options/arguments supplied
        /// to the program.
        /// </summary>
        /// <exception cref="System.ArgumentException">
        /// Thrown when: 1) an option is supplied with an argument and
        /// it shouldn't be, 2) an option is required to have an argument
        /// and it isn't supplied with one and 3) an option is supplied
        /// that has not been defined.
        /// </exception>
        public void Parse()
        {
            this.parsed = true;

            for (int i=0; i<this.args.Length; ++i) {

                CommandlineOption optionStruct = new CommandlineOption();
                int idx;

                string arg = this.args[i];

                // Long option
                if (arg.StartsWith("--")) {

                    // Option has an argument (eg --foo=bar)
                    if ((idx = arg.IndexOf("=")) != -1) {
                        optionStruct.option = arg.Substring(2, idx - 2);
                        optionStruct.arg = arg.Substring(idx + 1);
                        optionStruct.argPresent = true;

                        // Option doesn't have an argument
                    } else {
                        optionStruct.option = arg.Substring(2);
                    }

                    // Checks
                    if (!this.longOpts.ContainsKey(optionStruct.option)) {
                        throw new ArgumentException("Unknown option specified", optionStruct.option);

                    } else if (((CommandlineOption)this.longOpts[optionStruct.option]).argRequired && optionStruct.argPresent == false) {
                        throw new ArgumentException("Option requires an argument", optionStruct.option);

                    } else if (((CommandlineOption)this.longOpts[optionStruct.option]).argOptional == false
                               && ((CommandlineOption)this.longOpts[optionStruct.option]).argRequired == false
                               && optionStruct.argPresent == true) {
                                   throw new ArgumentException("No argument permitted for this option", optionStruct.option);
                               }

                    // Add to defined options hashtable
                    this.givenOpts.Add(optionStruct.option, optionStruct);

                    // Short option(s)
            //                } else if (arg.StartsWith("-") || arg.StartsWith("/")) {
                } else if (arg.StartsWith("-")) {

                    optionStruct.option = arg.Substring(1, 1);

                    // Is this option defined?
                    if (this.shortOpts.ContainsKey(optionStruct.option)) {

                        CommandlineOption definedOption = (CommandlineOption)this.shortOpts[optionStruct.option];

                        // Check for arguments to the option
                        if (definedOption.argOptional || definedOption.argRequired) {
                            if (arg.Length > 2) {
                                optionStruct.argPresent = true;
                                optionStruct.arg = arg.Substring(2);
                            } else if ((i + 1) < args.Length) {
                                optionStruct.argPresent = true;
                                optionStruct.arg = this.args[++i];

                                // No option, but one was required
                            } else if (definedOption.argRequired) {
                                throw new ArgumentException("Option requires an argument", optionStruct.option);
                            }

                            // No argument optional or required, so if arg is more
                            // than just one letter, it could be multiple consolidated
                            // options.
                        } else if (arg.Length > 2) {
                            this.args[i] = "-" + arg.Substring(2);
                            --i;
                        }

                        // Add to defined options hashtable
                        this.givenOpts.Add(optionStruct.option, optionStruct);

                    } else {
                        throw new ArgumentException("Unknown option specified", optionStruct.option);
                    }

                    // Not an option, an argument
                } else {
                    this.givenArgs.Add(arg);
                }
            }
        }
コード例 #11
0
 private static Tuple<CommandlineOption, String> MakeTuple(CommandlineOption option, String value)
 {
     return Tuple.Create(option, value);
 }
コード例 #12
0
        /// <summary>
        /// Initiates the parsing of the options/arguments supplied
        /// to the program.
        /// </summary>
        /// <exception cref="System.ArgumentException">
        /// Thrown when: 1) an option is supplied with an argument and
        /// it shouldn't be, 2) an option is required to have an argument
        /// and it isn't supplied with one and 3) an option is supplied
        /// that has not been defined.
        /// </exception>
        public void Parse()
        {
            this.parsed = true;

            for (int i = 0; i < this.args.Length; ++i)
            {
                CommandlineOption optionStruct = new CommandlineOption();
                int idx;

                string arg = this.args[i];

                // Long option
                if (arg.StartsWith("--"))
                {
                    // Option has an argument (eg --foo=bar)
                    if ((idx = arg.IndexOf("=")) != -1)
                    {
                        optionStruct.option     = arg.Substring(2, idx - 2);
                        optionStruct.arg        = arg.Substring(idx + 1);
                        optionStruct.argPresent = true;

                        // Option doesn't have an argument
                    }
                    else
                    {
                        optionStruct.option = arg.Substring(2);
                    }

                    // Checks
                    if (!this.longOpts.ContainsKey(optionStruct.option))
                    {
                        throw new ArgumentException("Unknown option specified", optionStruct.option);
                    }
                    else if (((CommandlineOption)this.longOpts[optionStruct.option]).argRequired && optionStruct.argPresent == false)
                    {
                        throw new ArgumentException("Option requires an argument", optionStruct.option);
                    }
                    else if (((CommandlineOption)this.longOpts[optionStruct.option]).argOptional == false &&
                             ((CommandlineOption)this.longOpts[optionStruct.option]).argRequired == false &&
                             optionStruct.argPresent == true)
                    {
                        throw new ArgumentException("No argument permitted for this option", optionStruct.option);
                    }

                    // Add to defined options hashtable
                    this.givenOpts.Add(optionStruct.option, optionStruct);

                    // Short option(s)
//                } else if (arg.StartsWith("-") || arg.StartsWith("/")) {
                }
                else if (arg.StartsWith("-"))
                {
                    optionStruct.option = arg.Substring(1, 1);

                    // Is this option defined?
                    if (this.shortOpts.ContainsKey(optionStruct.option))
                    {
                        CommandlineOption definedOption = (CommandlineOption)this.shortOpts[optionStruct.option];

                        // Check for arguments to the option
                        if (definedOption.argOptional || definedOption.argRequired)
                        {
                            if (arg.Length > 2)
                            {
                                optionStruct.argPresent = true;
                                optionStruct.arg        = arg.Substring(2);
                            }
                            else if ((i + 1) < args.Length)
                            {
                                optionStruct.argPresent = true;
                                optionStruct.arg        = this.args[++i];

                                // No option, but one was required
                            }
                            else if (definedOption.argRequired)
                            {
                                throw new ArgumentException("Option requires an argument", optionStruct.option);
                            }

                            // No argument optional or required, so if arg is more
                            // than just one letter, it could be multiple consolidated
                            // options.
                        }
                        else if (arg.Length > 2)
                        {
                            this.args[i] = "-" + arg.Substring(2);
                            --i;
                        }

                        // Add to defined options hashtable
                        this.givenOpts.Add(optionStruct.option, optionStruct);
                    }
                    else
                    {
                        throw new ArgumentException("Unknown option specified", optionStruct.option);
                    }


                    // Not an option, an argument
                }
                else
                {
                    this.givenArgs.Add(arg);
                }
            }
        }
コード例 #13
0
 /// <summary>
 /// Returns the associated value for the specified <see cref="CommandlineOption"/>.
 /// </summary>
 /// <exception cref="ArgumentException">
 /// An <see cref="ArgumentException"/> is thrown when no value is associated to <paramref name="option"/>.
 /// </exception>
 /// <param name="option"><see cref="CommandlineOption"/> to return the associated value for.</param>
 /// <returns>The value associated to the specified <see cref="CommandlineOption"/>.</returns>
 public string GetOption(CommandlineOption option)
 {
   if (!IsDefined(option))
     throw new ArgumentException("There is no value associated to " + option);
   return _options[option];
 }
コード例 #14
0
 /// <summary>
 /// Dispatches the command.
 /// </summary>
 /// <param name="option">The commmandline argument.</param>
 /// <param name="parameter">The paramater.</param>
 /// <returns>null</returns>
 protected void DispatchOption(CommandlineOption option, string parameter)
 {
     option.Action(this, parameter.Trim());
 }
コード例 #15
0
 /// <summary>
 /// Returns whether there's a value defined for the specified <see cref="CommandlineOption"/>.
 /// </summary>
 /// <param name="option"><see cref="CommandlineOption"/> to check for an associated value.</param>
 /// <returns></returns>
 public bool IsDefined(CommandlineOption option)
 {
   if (_options == null)
     Parse();
   return _options != null && _options.ContainsKey(option);
 }
コード例 #16
0
        /// <summary>
        /// Gets the long name of the command; used to display the help message.
        /// </summary>
        /// <param name="option">The option to get the long name for.</param>
        /// <returns></returns>
        protected virtual string GetOptionLongName(CommandlineOption option)
        {
            if (option.RequiredPosition == int.MaxValue)
              {
            var sb = new StringBuilder();

            sb.Append(OptionPrefixes[0]);
            sb.Append(OptionPrefixes[0]);
            sb.Append(option.LongName);

            return sb.ToString();
              }

              return option.LongName;
        }
コード例 #17
0
        private void BindOptionValue(object instance, IImmutableList <ICommandlineArgument> parsedResults, CommandlineOption option, ref int i)
        {
            var prop = PropertyProvider.GetPropertyForOption(instance, option);

            if (option.Value != null || !prop.RequiresValue)
            {
                prop.BindValue( );
                return;
            }

            if (prop.AllowSpaceDelimitedValue)
            {
                // peek ahead to see if the next item is a usable value
                if (((i < parsedResults.Count - 2) && (parsedResults[i + 1] is CommandlineValue value)))
                {
                    // OK, it's valid so use it and advanced to the next item so it isn't consumed as positional
                    prop.BindValue(value.Text);
                    ++i;
                    return;
                }
            }

            throw new CommandlineParseException(CultureInfo.CurrentUICulture, Resources.MissingValueForOption_0, option.Text);
        }
コード例 #18
0
 protected override string GetOptionLongName(CommandlineOption commandLineArgument)
 {
     return commandLineArgument.RequiredPosition == int.MaxValue
        ? OptionPrefixes[0] + commandLineArgument.LongName
        : commandLineArgument.LongName;
 }
コード例 #19
0
 /// <summary>
 /// Gets the commandline option short and long name.
 /// </summary>
 /// <param name="option">The commandline option to get the short and long names from.</param>
 /// <returns></returns>
 protected virtual string GetOptionNames(CommandlineOption option)
 {
     return !string.IsNullOrEmpty(option.LongName)
        ? GetOptionShortName(option) + ", " + GetOptionLongName(option)
        : GetOptionShortName(option);
 }
コード例 #20
0
 /// <summary>
 /// Gets the short name of the option; used to display the help message.
 /// </summary>
 /// <returns>The string prepended with the first ArgumentPrefixList item.</returns>
 protected virtual string GetOptionShortName(CommandlineOption option)
 {
     return option.RequiredPosition == int.MaxValue
        ? OptionPrefixes[0] + option.Name
        : option.Name;
 }
コード例 #21
0
 private static Tuple <CommandlineOption, String> MakeTuple(CommandlineOption option, String value)
 {
     return(Tuple.Create(option, value));
 }
コード例 #22
0
        /// <summary>
        /// Defines the options you require for your program. You should
        /// pass if the options as a string array. There are two modifiers
        /// you can use to specify option arguments. Use "=" at the end of
        /// your option to specify that this option has to have an argument,
        /// and use =? at the end of your option to specify that an argument
        /// is optional.
        /// </summary>
        /// <example>
        /// <code>
        /// GetOpt.SetOpts(new string[] {"a", "b", "foo=", "bar=?"})
        /// </code>
        /// </example>
        /// <param name="options">
        /// A string  array of the options without the preceding
        /// "-", "--" or "/".
        /// </param>
        public void SetOpts(string[] options)
        {
            foreach (string option in options) {

                CommandlineOption optionStruct = new CommandlineOption();

                // Argument required
                if (option.EndsWith("=")) {
                    optionStruct.option = option.Substring(0, option.Length - 1);
                    optionStruct.argRequired = true;

                    // Argument optional
                } else if (option.EndsWith("=?")) {
                    optionStruct.option = option.Substring(0, option.Length - 2);
                    optionStruct.argOptional = true;

                    // No argument
                } else {
                    optionStruct.option = option;
                }

                if (optionStruct.option.Length == 1) {
                    this.shortOpts.Add(optionStruct.option, optionStruct);
                } else {
                    this.longOpts.Add(optionStruct.option, optionStruct);
                }
            }
        }