Base class for all types of command-line arguments. Each argument must have a key that will be used to access the value in the returned Dictionary, and a description that is shown when help is displayed.
Beispiel #1
0
 public bool IsValid(Argument arg, string value, out string errorMsg)
 {
     var ok = true;
     errorMsg = null;
     if(Values != null) {
         var values = PermitMultipleValues ? value.SplitCSV() : new string[] { value };
         foreach(var val in values) {
             ok = ok && (CaseSensitive ? Values.Contains(val) :
                     Values.Contains(val, StringComparer.OrdinalIgnoreCase));
         }
     }
     if(!ok) {
         errorMsg = String.Format("Value must be {0} of: {1}{2}",
                                  PermitMultipleValues ? "any" : "one",
                                  String.Join(", ", Values.ToArray()),
                                  PermitMultipleValues ? " (Use a comma to separate multiple values)" : "");
     }
     return ok;
 }
 private static ArgumentHelpStrings GetHelpStrings(Argument arg)
 {
     return new ArgumentHelpStrings(arg.SyntaxHelp, arg.FullHelpText);
 }
Beispiel #3
0
 /// <summary>
 /// Adds an Argument definition to the list of arguments this command-line
 /// supports.
 /// </summary>
 public Argument AddArgument(Argument arg)
 {
     Arguments.Add(arg.Key, arg);
     if(arg is PositionalArgument) {
         _positionalArgumentOrder.Add(arg.Key);
     }
     return arg;
 }
Beispiel #4
0
		/// <summary>
		/// Creates a new command line argument parser.
		/// </summary>
		/// <param name="argumentSpecification"> The type of object to  parse. </param>
		/// <param name="reporter"> The destination for parse errors. </param>
		public Parser(Type argumentSpecification, ReportError reporter)
		{
			this.reporter = reporter;
			arguments = new ArrayList();
			argumentMap = new Hashtable();

			foreach (FieldInfo field in argumentSpecification.GetFields())
			{
				if (!field.IsStatic && !field.IsInitOnly && !field.IsLiteral)
				{
					ArgumentAttribute attribute = GetAttribute(field);
					if (attribute is DefaultArgumentAttribute)
					{
						Debug.Assert(defaultArgument == null);
						defaultArgument = new Argument(attribute, field, reporter);
					}
					else
					{
						arguments.Add(new Argument(attribute, field, reporter));
					}
				}
			}

			// add explicit names to map
			foreach (Argument argument in arguments)
			{
				Debug.Assert(!argumentMap.ContainsKey(argument.LongName));
				argumentMap[argument.LongName] = argument;
				if (argument.ExplicitShortName)
				{
					if (argument.ShortName != null && argument.ShortName.Length > 0)
					{
						Debug.Assert(!argumentMap.ContainsKey(argument.ShortName));
						argumentMap[argument.ShortName] = argument;
					}
					else
					{
						argument.ClearShortName();
					}
				}
			}

			// add implicit names which don't collide to map
			foreach (Argument argument in arguments)
			{
				if (!argument.ExplicitShortName)
				{
					if (argument.ShortName != null && argument.ShortName.Length > 0 &&
						!argumentMap.ContainsKey(argument.ShortName))
					{
						argumentMap[argument.ShortName] = argument;
					}
					else
					{
						argument.ClearShortName();
					}
				}
			}
		}
Beispiel #5
0
        /// Processes a single argument value, ensuring it passes validation,
        /// calling any OnParse handlers etc.
        protected string ProcessArgumentValue(Dictionary<string, object> result, Argument arg, object val, string set)
        {
            // Validate value, if argument specifies validation
            string errorMsg;
            var valArg = arg as ValueArgument;
            var sVal = val as string;

            if(set != null) {
                // Argument must be a member of the same set, or a member of no set
                _log.DebugFormat("Checking argument {0} is valid for argument set {1}", arg.Key, set);
                if(arg.Set != null && arg.Set != set) {
                   throw new ParseException(string.Format("Cannot mix arguments from sets {0} and {1}",
                                arg.Set, set));
                }
            }
            else if(arg.Set != null) {
                set = arg.Set;
                _log.DebugFormat("Argument set is {0}", set);
            }

            if(valArg != null) {
                if(valArg.Validate != null && sVal != null) {
                    _log.DebugFormat("Validating argument {0}", valArg.Key);
                    foreach(ValueArgument.ValidateHandler validate in valArg.Validate.GetInvocationList()) {
                        if(!validate(arg, sVal, out errorMsg)) {
                            throw new ParseException(string.Format("The value '{0}' for argument {1} is not valid. {2}.",
                                                     sVal, arg.Key, errorMsg));
                        }
                    }
                    _log.TraceFormat("Argument {0} validated", valArg.Key);
                }
                _log.TraceFormat("Setting {0} to '{1}'", arg.Key, valArg.IsSensitive ? "******" : val);
            }
            else {
                _log.TraceFormat("Setting flag {0} to true", arg.Key);
            }

            result.Add(arg.Key, val);

            // Call OnParse event, if handler specified
            if(arg.OnParse != null) {
                arg.OnParse(arg, val as string);
            }
            return set;
        }
Beispiel #6
0
 /// Outputs a single argument definition
 protected void OutputArg(Argument arg, TextWriter console)
 {
     if(arg is FlagArgument) {
         console.Write("    --{0,-14}  {1}", arg.Key, arg.Description);
     }
     else {
         console.Write("    {0,-16}  {1}", arg.Key, arg.Description);
     }
     var valArg = arg as ValueArgument;
     if(valArg != null) {
         if(valArg.DefaultValue != null) {
             console.Write(" (Default: {0})", valArg.DefaultValue);
         }
         else if(valArg.IsRequired) {
             console.Write(" (Required)");
         }
     }
     console.WriteLine();
 }
Beispiel #7
0
 /// <summary>
 /// Convenience method for defining a new positional argument.
 /// </summary>
 public PositionalArgument AddPositionalArgument(string key, string desc,
         Argument.OnParseHandler onParse)
 {
     var arg = new PositionalArgument { Key = key, Description = desc };
     arg.OnParse += onParse;
     return (PositionalArgument)Definition.AddArgument(arg);
 }
Beispiel #8
0
        /// <summary>
        /// Creates a new command line argument parser.
        /// </summary>
        /// <param name="argumentSpecification"> The type of object to  parse. </param>
        /// <param name="reporter"> The destination for parse errors. </param>
        public Parser(Type argumentSpecification, ErrorReporter reporter)
        {
            this.reporter = reporter;
            this.arguments = new ArrayList();
            this.argumentMap = new Hashtable();

            foreach (PropertyInfo prop in argumentSpecification.GetProperties())
            {
                ArgumentAttribute attribute = GetAttribute(prop);
                if (attribute is DefaultArgumentAttribute)
                {
                    Debug.Assert(this.defaultArgument == null);
                    this.defaultArgument = new Argument(attribute, prop, reporter);
                }
                else
                {
                    this.arguments.Add(new Argument(attribute, prop, reporter));
                }
            }

            // add explicit names to map
            foreach (Argument argument in this.arguments)
            {
                Debug.Assert(!argumentMap.ContainsKey(argument.LongName));
                this.argumentMap[argument.LongName] = argument;
                if (argument.ExplicitShortName)
                {
                    if (argument.ShortName != null && argument.ShortName.Length > 0)
                    {
                        Debug.Assert(!argumentMap.ContainsKey(argument.ShortName));
                        this.argumentMap[argument.ShortName] = argument;
                    }
                    else
                    {
                        argument.ClearShortName();
                    }
                }
            }

            // add implicit names which don't collide to map
            foreach (Argument argument in this.arguments)
            {
                if (!argument.ExplicitShortName)
                {
                    if (argument.ShortName != null && argument.ShortName.Length > 0 && !argumentMap.ContainsKey(argument.ShortName))
                        this.argumentMap[argument.ShortName] = argument;
                    else
                        argument.ClearShortName();
                }
            }
        }
Beispiel #9
0
 public bool IsValid(Argument arg, string value, out string errorMsg)
 {
     errorMsg = null;
     if(Expression == null) {
         return true;
     }
     else {
         errorMsg = String.Format("Value must satisfy the regular expression: /{0}/", Expression);
         return Expression.IsMatch(value);
     }
 }
Beispiel #10
0
 public bool IsValid(Argument arg, string value, out string errorMsg)
 {
     int iVal = int.Parse(value);
     errorMsg = null;
     if(Min != null && Max != null) {
         errorMsg = String.Format("Value must be in the range {0} to {1} inclusive", Min, Max);
     }
     else if(Min != null) {
         errorMsg = String.Format("Value must be greater than or equal to {0}", Min);
     }
     else if(Max != null) {
         errorMsg = String.Format("Value must be less than or equal to {0}", Max);
     }
     return (Min == null || iVal >= Min) && (Max == null || iVal <= Max);
 }
 private static ArgumentHelpText GetHelpText(Argument arg)
 {
     return new ArgumentHelpText(arg.SyntaxHelp, arg.FullHelpText);
 }