public void ArgumentsCopyTo(CommandLineArgument[] array, int arrayIndex)
 {
     lock (_lock)
     {
         _arguments.CopyTo(array, arrayIndex);
     }
 }
 // Arguments
 public void AddArgument(CommandLineArgument item)
 {
     lock (_lock)
     {
         InsertArgument(_arguments.Count, item);
     }
 }
Exemple #3
0
 private static CommandLineArgument CreateCommandLineArgument(string param)
 {
     if (string.IsNullOrEmpty(param))
         return null;
     param = param.TrimStart('/');
     string[] pr = param.Split(new[] {'='}, 2);
     if (pr.Length < 1)
         return null;
     CommandLineArgument result = new CommandLineArgument();
     result.Key = pr[0];
     if (pr.Length > 1)
         result.Value = pr[1];
     return result;
 }
Exemple #4
0
        public void TestConflictingAliasDefinitions()
        {
            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            var argument = new CommandLineArgument(typeof(int), "somenumber");
            argument.Metadata.Add(new ArgShortcut("some"));

            try
            {
                argument.Aliases.Add("some");
                Assert.Fail("An exception should have been thrown");
            }
            catch (InvalidArgDefinitionException ex)
            {
                Assert.AreEqual(ex.Message, "The alias 'some' has already been added");
            }
        }
        public override bool TryComplete(bool shift, CommandLineArgument context, string soFar, out string completion)
        {
            if (context.ArgumentType.IsEnum == false)
            {
                completion = null;
                return false;
            }

            return manager.Cycle(shift, ref soFar, () =>
            {
                var options = Enum.GetNames(context.ArgumentType).Union(context.ArgumentType.GetEnumShortcuts());
                options = options.Where(o => o.StartsWith(soFar, context.IgnoreCase, CultureInfo.CurrentCulture)).ToArray();

                return options.ToList();
            }, out completion);
        }
Exemple #6
0
 public void TestConflictingOverride(Action<CommandLineArgument> variation, string errorMessageExpectedContents)
 {
     CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
     var argument = new CommandLineArgument(typeof(int), "somenumber");
     definition.Arguments.Add(argument);
     variation(argument);
     try
     {
         Args.Parse(definition, "-somenumber", "100");
         Assert.Fail("An exception should have been thrown");
     }
     catch (InvalidArgDefinitionException ex)
     {
         Assert.IsTrue(ex.Message.Contains(errorMessageExpectedContents));
     }
 }
Exemple #7
0
        /// <summary>
        /// Validates that the user actually specified a value and optionally prompts them when it is missing.
        /// </summary>
        /// <param name="argument">The argument being populated.  This validator doesn't do anything with it.</param>
        /// <param name="arg">The value specified on the command line or null if it wasn't specified</param>
        public override void ValidateAlways(CommandLineArgument argument, ref string arg)
        {
            if (arg == null && PromptIfMissing)
            {
                var value = "";
                while (string.IsNullOrWhiteSpace(value))
                {
                    Console.Write("Enter value for " + argument.DefaultAlias + ": ");
                    value = Console.ReadLine();
                }

                arg = value;
            }
            if (arg == null)
            {
                throw new MissingArgException("The argument '" + argument.DefaultAlias + "' is required", new ArgumentNullException(argument.DefaultAlias));
            }
        }
Exemple #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandLineParser" /> class
        /// using possible arguments deducted from the specific <see cref="Type" />.
        /// </summary>
        /// <param name="argumentSpecification">The <see cref="Type" /> from which the possible command-line arguments should be retrieved.</param>
        /// <param name="supportsResponseFile">A <see cref="bool" /> value indicating whether or not a response file is able to be used. </param>
        /// <exception cref="ArgumentNullException"><paramref name="argumentSpecification" /> is a null reference.</exception>
        public CommandLineParser(Type argumentSpecification, bool supportsResponseFile ) {
            if (argumentSpecification == null) {
                throw new ArgumentNullException("argumentSpecification");
            }

            _argumentCollection = new CommandLineArgumentCollection();

            foreach (PropertyInfo propertyInfo in argumentSpecification.GetProperties(BindingFlags.Instance | BindingFlags.Public)) {
                if (propertyInfo.CanWrite || typeof(ICollection).IsAssignableFrom(propertyInfo.PropertyType)) {
                    CommandLineArgumentAttribute attribute = GetCommandLineAttribute(propertyInfo);
                    if (attribute is DefaultCommandLineArgumentAttribute) {
                        Debug.Assert(_defaultArgument == null);
                        _defaultArgument = new CommandLineArgument(attribute, propertyInfo);
                    } else if (attribute != null) {
                        _argumentCollection.Add(new CommandLineArgument(attribute, propertyInfo));
                    }
                }
            }

            _argumentSpecification = argumentSpecification;
            _supportsResponseFile = supportsResponseFile;
        }
Exemple #9
0
        internal object CreateTabCompletionSource(CommandLineArgumentsDefinition definition, CommandLineArgument argument)
        {
            ITabCompletionSource ret;
            if(this.CompletionSourceType.GetInterfaces().Contains(typeof(ISmartTabCompletionSource)))
            {
                var source = Activator.CreateInstance(CompletionSourceType) as ISmartTabCompletionSource;
                return new ArgumentAwareWrapperSmartTabCompletionSource(definition, argument, source);
            }
            else if (this.CompletionSourceType.IsSubclassOf(typeof(ArgumentAwareTabCompletionSource)))
            {
                ret = (ITabCompletionSource)Activator.CreateInstance(this.CompletionSourceType, definition, argument);
            }
            else if (this.CompletionSourceType.GetInterfaces().Contains(typeof(ITabCompletionSource)))
            {
                var toWrap = (ITabCompletionSource)Activator.CreateInstance(this.CompletionSourceType);
                ret = new ArgumentAwareWrapperTabCompletionSource(definition, argument, toWrap);
            }
            else
            {
                throw new InvalidArgDefinitionException("The type " + this.CompletionSourceType.FullName + " does not implement ITabCompletionSource or ITabCompletionSource.  The target argument was " + argument.DefaultAlias);
            }

            return ret;
        }
Exemple #10
0
        public void TestNullableFriendlyTypeName()
        {
            var arg = new CommandLineArgument(typeof(Nullable <int>), "someInt");

            Assert.AreEqual("integer", arg.FriendlyTypeName);
        }
Exemple #11
0
        /// <summary>
        /// Is the given command a valid command for this switch (i.e. is this switch used by this command)
        /// </summary>
        /// <param name="argument"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        private bool IsValidForCommand(CommandLineArgument argument, string command)
        {
            if (argument.IsValidForCommand(command))
                return true;

            // check the command attributes instead if they contain this switch name
            EnsureCommandSwitches();

            return Array.Exists(commandSwitches[command],
                delegate(string s) { return string.CompareOrdinal(s, argument.Name) == 0; });
        }
Exemple #12
0
 /// <summary>
 /// Makes sure the target is a boolean
 /// </summary>
 /// <param name="context">Context passed by the parser</param>
 public override void BeforePopulateProperty(ArgHook.HookContext context)
 {
     base.BeforePopulateProperty(context);
     this.target = context.CurrentArgument;
     if (context.CurrentArgument.ArgumentType != typeof(bool))
     {
         throw new InvalidArgDefinitionException(typeof(HelpHook).Name +" attributes can only be used with boolean properties or parameters");
     }
 }
 public abstract bool TryComplete(bool shift, CommandLineArgument context, string soFar, out string completion);
 /// <summary>
 /// Removes a member from the collection.
 /// </summary>
 /// <param name="item">The <see cref="CommandLineArgument"/> to remove from the collection.</param>
 public void Remove(CommandLineArgument item)
 {
     base.List.Remove(item);
 }
 /// <summary>
 /// Retrieves the index of a specified <see cref="CommandLineArgument"/> object in the collection.
 /// </summary>
 /// <param name="item">The <see cref="CommandLineArgument"/> object for which the index is returned.</param> 
 /// <returns>
 /// The index of the specified <see cref="CommandLineArgument"/>. If the <see cref="CommandLineArgument"/> is not currently a member of the collection, it returns -1.
 /// </returns>
 public int IndexOf(CommandLineArgument item)
 {
     return base.List.IndexOf(item);
 }
 /// <summary>
 /// Determines whether a <see cref="CommandLineArgument"/> is in the collection.
 /// </summary>
 /// <param name="item">The <see cref="CommandLineArgument"/> to locate in the collection.</param> 
 /// <returns>
 /// <see langword="true" /> if <paramref name="item"/> is found in the 
 /// collection; otherwise, <see langword="false" />.
 /// </returns>
 public bool Contains(CommandLineArgument item)
 {
     return base.List.Contains(item);
 }
Exemple #17
0
        public void TestTheTestIsValidAndRevivableMethod()
        {
            var arg = new CommandLineArgument(typeof(int), "TheInt");
            Assert.IsTrue(arg.TestIsValidAndRevivable("100"));

            // this should fail on the revive test
            Assert.IsFalse(arg.TestIsValidAndRevivable("abc"));

            Assert.IsTrue(arg.TestIsValidAndRevivable("2000"));
            arg.Metadata.Add(new ArgRegex("1000"));

            // this should fail the validation test
            Assert.IsFalse(arg.TestIsValidAndRevivable("2000"));
        }
Exemple #18
0
        public void TestPowerArgsRichCommandLineReaderFindCurrentTokenArgument()
        {
            bool expect;
            try
            {
                PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, null, out expect);
            }
            catch (NullReferenceException ex)
            {
                Assert.IsTrue(ex.Message.Contains("ambient"));
            }

            CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition();
            var globalArg = new CommandLineArgument(typeof(int), "TheInt");
            def.Arguments.Add(globalArg);
            Assert.IsNull(PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, null, out expect, def));
            Assert.IsFalse(expect);

            var found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, "-TheInt", out expect, def);
            Assert.AreSame(globalArg, found);
            Assert.IsTrue(expect);

            found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, "/TheInt", out expect, def);
            Assert.AreSame(globalArg, found);
            Assert.IsTrue(expect);

            found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, "TheInt", out expect, def);
            Assert.IsNull(found);
            Assert.IsFalse(expect);

            found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(null, "-ActionInt", out expect, def);
            Assert.IsNull(found);
            Assert.IsTrue(expect);

            var action = new CommandLineAction((d) => { });
            action.Aliases.Add("TheAction");
            var actionArg = new CommandLineArgument(typeof(int), "ActionInt");
            action.Arguments.Add(actionArg);
            def.Actions.Add(action);

            found = PowerArgsRichCommandLineReader.FindCurrentTokenArgument(action, "-ActionInt", out expect, def);
            Assert.AreSame(actionArg, found);
            Assert.IsTrue(expect);
        }
Exemple #19
0
        public void TestPowerArgsRichCommandLineReaderFindContextualArgument()
        {
            try
            {
                PowerArgsRichCommandLineReader.FindContextualArgument("-TheString", null);
                Assert.Fail("An exception should have been thrown");
            }
            catch(NullReferenceException ex)
            {
                Assert.IsTrue(ex.Message.Contains("ambient"));
            }

            CommandLineArgumentsDefinition def = new CommandLineArgumentsDefinition();
            var globalArg = new CommandLineArgument(typeof(string), "TheString");

            def.Arguments.Add(globalArg);
            var found = PowerArgsRichCommandLineReader.FindContextualArgument("-TheString", null, def);
            Assert.AreSame(globalArg, found);

            found = PowerArgsRichCommandLineReader.FindContextualArgument("/TheString", null, def);
            Assert.AreSame(globalArg, found);

            Assert.IsNull(PowerArgsRichCommandLineReader.FindContextualArgument("-ActionInt", null, def));
            Assert.IsNull(PowerArgsRichCommandLineReader.FindContextualArgument(null, null, def));

            var action = new CommandLineAction((d) => { });
            action.Aliases.Add("TheAction");

            var actionArg = new CommandLineArgument(typeof(int), "ActionInt");
            action.Arguments.Add(actionArg);
            def.Actions.Add(action);

            found = PowerArgsRichCommandLineReader.FindContextualArgument("-TheString", action, def);
            Assert.AreSame(globalArg, found);

            found = PowerArgsRichCommandLineReader.FindContextualArgument("-ActionInt", action, def);
            Assert.AreSame(actionArg, found);
        }
Exemple #20
0
        /// <summary>
        /// Validates that the user actually specified a value and optionally prompts them when it is missing.
        /// </summary>
        /// <param name="argument">The argument being populated.  This validator doesn't do anything with it.</param>
        /// <param name="arg">The value specified on the command line or null if it wasn't specified</param>
        public override void ValidateAlways(CommandLineArgument argument, ref string arg)
        {
            if (IsConditionallyRequired)
            {
                var matchingHook = (from h in argument.Metadata.Metas<ArgRequiredConditionalHook>() where h.parent == this select h).SingleOrDefault();
                if(matchingHook == null)
                {
                    argument.Metadata.Add(new ArgRequiredConditionalHook(this));
                }
            }

            if (IsConditionallyRequired == false && arg == null && PromptIfMissing && ArgHook.HookContext.Current.Definition.IsNonInteractive == false)
            {
                var cli = new Cli();

                ITabCompletionHandler tabHandler;
                IHighlighterConfigurator highlighterConfigurator;

                if (TabCompletionHandlerType.TryCreate<ITabCompletionHandler>(out tabHandler))
                {
                    cli.Reader.TabHandler.TabCompletionHandlers.Add(tabHandler);
                }

                if (HighlighterConfiguratorType.TryCreate<IHighlighterConfigurator>(out highlighterConfigurator))
                {
                    cli.Reader.Highlighter = new SimpleSyntaxHighlighter();
                    highlighterConfigurator.Configure(cli.Reader.Highlighter);
                }

                arg = cli.PromptForLine("Enter value for " + argument.DefaultAlias);
            }

            if (arg == null && IsConditionallyRequired == false)
            {
                throw new MissingArgException("The argument '" + argument.DefaultAlias + "' is required", new ArgumentNullException(argument.DefaultAlias));
            }
        }
 /// <summary>
 /// Adds a <see cref="CommandLineArgument"/> to the end of the collection.
 /// </summary>
 /// <param name="item">The <see cref="CommandLineArgument"/> to be added to the end of the collection.</param> 
 /// <returns>The position into which the new element was inserted.</returns>
 public int Add(CommandLineArgument item)
 {
     return base.List.Add(item);
 }
 /// <summary>
 /// Adds the elements of a <see cref="CommandLineArgument"/> array to the end of the collection.
 /// </summary>
 /// <param name="items">The array of <see cref="CommandLineArgument"/> elements to be added to the end of the collection.</param> 
 public void AddRange(CommandLineArgument[] items)
 {
     for (int i = 0; (i < items.Length); i = (i + 1)) {
         Add(items[i]);
     }
 }
Exemple #23
0
        static void Main(string[] args)
        {
            var specOne   = new CommandLineSpecification(0, "--");
            var specTwo   = new CommandLineSpecification(1, "-");
            var specThree = new CommandLineSpecification(2, "#");

            var argOne   = new CommandLineArgument("one", specOne);
            var argTwo   = new CommandLineArgument("two", specOne);
            var argThree = new CommandLineArgument("three", specOne);
            var argFour  = new CommandLineArgument("four", specTwo);
            var argFive  = new CommandLineArgument("five", specTwo);
            var argSix   = new CommandLineArgument("six", specTwo);
            var argSeven = new CommandLineArgument("seven", specThree);
            var argEight = new CommandLineArgument("eight", specThree);
            var argNine  = new CommandLineArgument("nine", specThree);

            var groupingOne = new CommandLineGrouping(argOne, new[] { argFour });
            var groupingTwo = new CommandLineGrouping(new[] { argOne, argFour }, new[] { argEight, argNine });

            var flags = new []
            {
                CmdLineSearchOptions.None,
                CmdLineSearchOptions.WithChildren,
                CmdLineSearchOptions.WithoutChildren,
                CmdLineSearchOptions.WithoutSiblings,
                CmdLineSearchOptions.WithSiblings,
                CmdLineSearchOptions.WithParams,
                CmdLineSearchOptions.WithoutParams,
                CmdLineSearchOptions.WithoutChildren | CmdLineSearchOptions.WithoutSiblings,
                CmdLineSearchOptions.WithoutChildren | CmdLineSearchOptions.WithSiblings,
                CmdLineSearchOptions.WithoutChildren | CmdLineSearchOptions.WithParams,
                CmdLineSearchOptions.WithoutChildren | CmdLineSearchOptions.WithoutParams,
                CmdLineSearchOptions.WithChildren | CmdLineSearchOptions.WithoutSiblings,
                CmdLineSearchOptions.WithChildren | CmdLineSearchOptions.WithSiblings,
                CmdLineSearchOptions.WithChildren | CmdLineSearchOptions.WithParams,
                CmdLineSearchOptions.WithChildren | CmdLineSearchOptions.WithoutParams,
                CmdLineSearchOptions.WithoutChildren | CmdLineSearchOptions.WithoutSiblings | CmdLineSearchOptions.WithoutParams,
                CmdLineSearchOptions.WithoutChildren | CmdLineSearchOptions.WithoutSiblings | CmdLineSearchOptions.WithParams,
                CmdLineSearchOptions.WithoutChildren | CmdLineSearchOptions.WithSiblings | CmdLineSearchOptions.WithoutParams,
                CmdLineSearchOptions.WithoutChildren | CmdLineSearchOptions.WithSiblings | CmdLineSearchOptions.WithParams,
                CmdLineSearchOptions.WithChildren | CmdLineSearchOptions.WithSiblings | CmdLineSearchOptions.WithoutParams,
                CmdLineSearchOptions.WithChildren | CmdLineSearchOptions.WithSiblings | CmdLineSearchOptions.WithParams,
            };

            var callChain = new [] { argOne };

            foreach (var flag in flags)
            {
                Console.WriteLine($"{callChain.Found(flag).ToString().PadRight(5)} => {flag}");
            }

            Console.WriteLine();
            Console.WriteLine($"{argOne.Command} => {string.Join(" | ", argOne.GetParams())}");
            Console.WriteLine($"{argOne.Command} => {string.Join(" | ", new[] { argOne, argFour }.GetParams())}");
            Console.WriteLine($"{argOne.Command} => {string.Join(" | ", new[] { argOne, argFour, argNine }.GetParams())}");

            Console.WriteLine();

            CommandLine.GetParams(new[] { argOne, argFour }).First();

            Console.WriteLine();

            foreach (var violation in new ICommandLineRestriction <CommandLineViolation>[]
            {
                new CommandLineRestrictions.FirstArgMustBeRootRestriction(CommandLine.RootSpecification),
                new CommandLineRestrictions.UnknownArgumentsRestriction(CommandLine.KnownArguments, CommandLine.KnownSpecifications),
                new CommandLineRestrictions.MustContainAtLeastOneArgumentRestriction(),
            })
            {
                if (violation.IsViolated)
                {
                    foreach (var violationResult in violation.GetViolations())
                    {
                        Console.WriteLine($"{violationResult.Violation} => {violationResult.Message}");
                    }
                }
            }
        }
 /// <summary>
 /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array.        
 /// </summary>
 /// <param name="array">The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing.</param> 
 /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
 public void CopyTo(CommandLineArgument[] array, int index)
 {
     base.List.CopyTo(array, index);
 }
Exemple #25
0
        public void TestModelDrivenUsage()
        {
            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            var argument1 = new CommandLineArgument(typeof(int), "somenumber");
            argument1.Description = "INT Description";

            var argument2 = new CommandLineArgument(typeof(Uri), "someuri");
            argument2.Description = "URI Description";

            definition.Arguments.Add(argument1);
            definition.Arguments.Add(argument2);

            var usage = ArgUsage.GetUsage(definition, "test");

            Assert.IsTrue(usage.Contains("INT Description"));
            Assert.IsTrue(usage.Contains("URI Description"));
        }
 /// <summary>
 /// Inserts a <see cref="CommandLineArgument"/> into the collection at the specified index.
 /// </summary>
 /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
 /// <param name="item">The <see cref="CommandLineArgument"/> to insert.</param>
 public void Insert(int index, CommandLineArgument item)
 {
     base.List.Insert(index, item);
 }
Exemple #27
0
        public void TestModeledAction()
        {
            bool invoked = false;

            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();

            var action = new CommandLineAction((d) =>
            {
                Assert.AreEqual("go", d.SpecifiedAction.DefaultAlias);
                Assert.AreEqual("Hawaii", d.SpecifiedAction.Arguments[0].RevivedValue);
                invoked = true;
            });

            action.Aliases.Add("go");
            action.Description = "A simple action";

            definition.Actions.Add(action);

            var actionString = action.ToString(); // Make sure it doesn't throw

            var destination  = new CommandLineArgument(typeof(string),"destination");
            destination.Metadata.Add(new ArgRequired());
            destination.Description = "The place to go to";

            action.Arguments.Add(destination);

            Args.InvokeAction(definition, "go", "-destination", "Hawaii");
            Assert.IsTrue(invoked);

            var usage = ArgUsage.GetUsage(definition, "test");
            Assert.IsTrue(usage.Contains("A simple action"));
            Assert.IsTrue(usage.Contains("The place to go to"));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandLineArgumentCollection"/> class
 /// with the specified array of <see cref="CommandLineArgument"/> instances.
 /// </summary>
 public CommandLineArgumentCollection(CommandLineArgument[] value)
 {
     AddRange(value);
 }
Exemple #29
0
 private bool IsArgPresent(CommandLineArgument eArgument)
 {
     return(Arguments.Contains("-" + eArgument.ToString().ToLower()));
 }
        public void TestModeledActionREPL()
        {
            int invokeCount = 0;

            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            definition.Metadata.Add(new TabCompletion() { REPL = true, Indicator = "$" });

            var action = new CommandLineAction((d) =>
            {
                Assert.AreEqual("go", d.SpecifiedAction.DefaultAlias);
                if (invokeCount == 0)
                {
                    Assert.AreEqual("Hawaii", d.SpecifiedAction.Arguments[0].RevivedValue);
                }
                else if (invokeCount == 1)
                {
                    Assert.AreEqual("Mexico", d.SpecifiedAction.Arguments[0].RevivedValue);
                }
                invokeCount++;
            });

            action.Aliases.Add("go");
            action.Description = "A simple action";

            definition.Actions.Add(action);

            var destination = new CommandLineArgument(typeof(string), "destination");
            destination.Metadata.Add(new ArgRequired());
            destination.Description = "The place to go to";

            action.Arguments.Add(destination);

            var provider = TestConsoleProvider.SimulateConsoleInput("g\t -dest\t Hawaii{enter}go -dest\t Mexico{enter}quit");
            Args.InvokeAction(definition, "$");
            Assert.AreEqual(2, invokeCount);
        }
Exemple #31
0
        public void TestSimpleModel()
        {
            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            var argument = new CommandLineArgument(typeof(int), "somenumber");
            definition.Arguments.Add(argument);

            var argumentString = argument.ToString(); // Make sure it doesn't throw

            Args.Parse(definition, new string[] { "-somenumber", "100" });
            Assert.AreEqual(100, definition.Arguments[0].RevivedValue);

            definition.Arguments[0].RevivedValue = null;
            Args.Parse(definition, new string[] { "/somenumber:100" });
            Assert.AreEqual(100, definition.Arguments[0].RevivedValue);
        }
Exemple #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandLineParser" /> class.  Provides a resource reader for localization of the command 
        /// line arguments.  String specified in the command line attributes are used to look up corresponding localized strings in the resources.
        /// Also provides flags to control parsing.
        /// </summary>
        /// <param name="argumentSpecificationType">The <see cref="Type" />  in which the command line arguments are defined.</param>
        /// <param name="resourceReaderType">A resource reader object with a <code>GetString</code> method</param>
        /// <param name="flags">See <see cref="CommandLineParserFlags"/>.</param>
        /// <exception cref="ArgumentNullException"><paramref name="argumentSpecificationType" /> is a null reference.</exception>
        public CommandLineParser(Type argumentSpecificationType, Type resourceReaderType, CommandLineParserFlags flags)
        {
            if (argumentSpecificationType == null)
            {
                throw new ArgumentNullException("argumentSpecificationType");
            }

            this.argumentSpecificationType = argumentSpecificationType;
            this.resourceReaderType = resourceReaderType;
            this.flags= flags;
            this.responseFiles = new Stack<string>();

            argumentCollection = new List<CommandLineArgument>();

            // Look ONLY for public instance properties.  NOTE: Don't change this behavior!
            foreach (PropertyInfo propertyInfo in argumentSpecificationType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                object[] attributes = propertyInfo.GetCustomAttributes(typeof(CommandLineArgumentAttribute), true);
                CommandLineArgumentAttribute attribute;

                // Ignore properties that don't have a CommandLineArgumentAttribute
                if (attributes.Length == 1)
                    attribute = (CommandLineArgumentAttribute)attributes[0];
                else
                    continue;

                // Ensure that the property is readable and writeable
                if (!(propertyInfo.CanWrite && propertyInfo.CanRead))
                    throw new ArgumentException(
                        CommandLineParserResources.PropertyShouldBeReadableAndWriteable(propertyInfo.Name));

                attribute.ValueHint = ExternalGetString(attribute.ValueHint);

                if (attribute is DefaultCommandLineArgumentAttribute)
                {
                    if (HasDefaultArgument)
                        throw new ArgumentException(CommandLineParserResources.DefaultArgumentAlreadyDefined);

                    defaultArgument = new CommandLineArgument(attribute, propertyInfo);
                }
                else if (attribute is UnprocessedCommandLineArgumentAttribute)
                {
                    if (HasUnprocessedArgument)
                        throw new ArgumentException(CommandLineParserResources.UnprocessedArgumentAlreadyDefined);

                    unprocessedArgument = new CommandLineArgument(attribute, propertyInfo);

                    if (!unprocessedArgument.AllowMultiple)
                        throw new ArgumentException(CommandLineParserResources.UnprocessedArgumentMustBeArrayOrCollection);
                }
                else if (attribute is CommandCommandLineArgumentAttribute)
                {
                    if (HasCommandArgument)
                        throw new ArgumentException(CommandLineParserResources.CommandArgumentAlreadyDefined);

                    commandArgument = new CommandLineArgument(attribute, propertyInfo);
                }
                else
                {
                    attribute.Description = ExternalGetString(attribute.Description);

                    if (attribute.Description == null)
                    {
                        throw new ArgumentException(
                            CommandLineParserResources.PropertyDoesNotHaveAValueForDescription(propertyInfo.Name));
                    }

                    // If not being case sensitive, make everything lower case.
                    if (!CaseSensitive)
                    {
                        attribute.Name = attribute.Name.ToLower(CultureInfo.InvariantCulture);

                        if (attribute.ShortName != null)
                            attribute.ShortName = attribute.ShortName.ToLower(CultureInfo.InvariantCulture);
                    }

                    argumentCollection.Add(new CommandLineArgument(attribute, propertyInfo));
                }
            }

            if (HasUnprocessedArgument && !HasDefaultArgument)
            {
                throw new ArgumentException(CommandLineParserResources.UnprocessedRequiresDefaultArguments);
            }
        }
Exemple #33
0
        public void TestSimpleModelWithSimpleValidator()
        {
            CommandLineArgumentsDefinition definition = new CommandLineArgumentsDefinition();
            var definitionString = definition.ToString(); // Make sure it doesn't throw

            var argument = new CommandLineArgument(typeof(int), "somenumber");
            definition.Arguments.Add(argument);
            argument.Metadata.Add(new ArgRequired());

            try
            {
                Args.Parse(definition, new string[] { });
                Assert.Fail("An exception should have been thrown");
            }
            catch (MissingArgException ex)
            {
                Assert.IsTrue(ex.Message.Contains("somenumber"));
            }
        }
Exemple #34
0
 public static string GetFullArgumentName(this CommandLineArgument argument)
 {
     return($"--{argument.Name}");
 }
Exemple #35
0
        public void TestGenericFriendlyTypeName()
        {
            var arg = new CommandLineArgument(typeof(List <int>), "someInt");

            Assert.AreEqual("List<integer>", arg.FriendlyTypeName);
        }