public Attributes(ArgumentAttribute input, TlcModule.RangeAttribute range, bool optional = false)
 {
     Contracts.AssertValue(input);
     Contracts.AssertValueOrNull(range);
     Input    = input;
     Range    = range;
     Optional = optional;
 }
        public void Constructor_should_default_Position_to_max_int_value()
        {
            //  act
            var attr = new ArgumentAttribute(null, null, null);

            //  assert
            Assert.AreEqual(int.MaxValue, attr.Position);
        }
Пример #3
0
 private void AddArgument(List <IArgument> args, ArgumentAttribute argAttrib, PropertyInfo pi, string parent)
 {
     args.Add(
         _argTypeMapper.Map(
             argAttrib,
             pi,
             _config.CliConfig,
             parent));
 }
Пример #4
0
 private static void SetDefaults(ArgumentAttribute attr)
 {
     // If appending and didn't explicitly set the constraint,
     // the sane default is to accept AtLeast N parameters.
     if (!attr.ExplicitlySetConstraint &&
         (attr.Action == ParseAction.Append || attr.Action == ParseAction.AppendConst))
     {
         attr.Constraint = NumArgsConstraint.AtLeast;
     }
 }
Пример #5
0
        public void Match(string from, string toExcluding, string version, bool match)
        {
            var attribute = new ArgumentAttribute("hi")
            {
                From        = from,
                ToExcluding = toExcluding
            };

            var result = attribute.Match(Version.Parse(version));

            Assert.Equal(match, result);
        }
Пример #6
0
        private bool ReadArgument(PropertyInfo pi, Type type, out object value)
        {
            value = null;
            ArgumentAttribute aa = pi.GetCustomAttribute <ArgumentAttribute>( );

            if (aa == null)
            {
                return(false);
            }

            IOption opt = null;

            if (!string.IsNullOrEmpty(aa.Of))
            {
                opt = GetOptionForName(aa.Of);
            }

            string argName = pi.Name;

            if (opt != null)
            {
                argName = argName.Replace(
                    _specDeriverConfig.PropertyNamingStyle.ToString(opt.Name),
                    string.Empty);
            }

            IArgument arg = (opt?.Arguments ?? _spec.Arguments).FirstOrDefault(a => a.Name == argName)
                            ?? (_spec.DynamicArgument != null && _spec.DynamicArgument.Name == argName
                     ? _spec.DynamicArgument
                     : _spec.Options.FirstOrDefault(o => o.DynamicArgument != null && o.DynamicArgument.Name == argName)
                                ?.DynamicArgument);

            if (arg == null)
            {
                throw new Exception($"spec does not contain an {nameof( IArgument )} with name {argName}");
            }

            if (arg.IsDynamicArgument)
            {
                value = GetValueForDynamicArgument(arg);
            }
            else if (type.IsNullableType( ))
            {
                value = GetValueForNullableArgument(arg, type);
            }
            else
            {
                value = GetValueForArgument(arg);
            }

            return(true);
        }
Пример #7
0
    public ArgumentDescriptionRepository()
    {
        ClassEnumerator classEnumerator = new ClassEnumerator(typeof(ArgumentAttribute), typeof(IArgumentDescription), typeof(ArgumentAttribute).get_Assembly(), true, false, false);

        ListView <Type> .Enumerator enumerator = classEnumerator.results.GetEnumerator();
        while (enumerator.MoveNext())
        {
            Type current = enumerator.Current;
            ArgumentAttribute    argumentAttribute   = current.GetCustomAttributes(typeof(ArgumentAttribute), false)[0] as ArgumentAttribute;
            IArgumentDescription argumentDescription = Activator.CreateInstance(current) as IArgumentDescription;
            this.Descriptions.Add(argumentAttribute.order, argumentDescription);
        }
    }
Пример #8
0
        public IArgument GetArgument(string propertyName)
        {
            PropertyInfo pi = _t.GetProperty(propertyName);

            if (pi == null)
            {
                throw new Exception($"{_t} has no property {propertyName}");
            }

            ArgumentAttribute      aa = pi.GetCustomAttribute <ArgumentAttribute>( );
            FirstArgumentAttribute fa = pi.GetCustomAttribute <FirstArgumentAttribute>( );
            OptionAttribute        oa = pi.GetCustomAttribute <OptionAttribute>( );
            string argName;

            if (aa != null)
            {
                argName = !string.IsNullOrEmpty(aa.Name)
                  ? aa.Name
                  : string.IsNullOrEmpty(aa.Of)
                        ? propertyName
                        : propertyName.Replace(aa.Of, string.Empty);
            }
            else if (fa != null)
            {
                argName = !string.IsNullOrEmpty(fa.Name)
                  ? fa.Name
                  : $"{propertyName}{CliSpecDeriver.ImplicitFirstArg}";
            }
            else if (oa != null)
            {
                argName = $"{propertyName}{CliSpecDeriver.ImplicitFirstArg}";
            }
            else
            {
                throw new Exception($"no argument mapped to property {propertyName}");
            }

            IArgument arg = _spec.Arguments.Union(
                _spec.Options.SelectMany(o => o.Arguments))
                            .Union(
                _spec.Flags.SelectMany(f => f.Arguments))
                            .FirstOrDefault(a => a.Name == argName);

            if (arg == null)
            {
                throw new Exception($"no argument mapped to property {propertyName}");
            }

            return(arg);
        }
        public void ConstructorTest()
        {
            string name = "Some name";
            ArgumentAttribute attribute = new ArgumentAttribute(name);
            Assert.AreEqual(name, attribute.Name);
            Assert.IsTrue(attribute.Optional);
            Assert.IsNull(attribute.DefaultValue);
            Assert.IsFalse(attribute.NeedEncode);

            attribute.Optional = false;
            Assert.IsFalse(attribute.Optional);

            attribute.NeedEncode = true;
            Assert.IsTrue(attribute.NeedEncode);
        }
Пример #10
0
        public void Constructor_should_initialize_properties()
        {
            //  arrange
            const string name      = "name";
            const string shortName = "short_name";
            const string desc      = "description";

            //  act
            var attr = new ArgumentAttribute(name, shortName, desc);

            //  assert
            Assert.AreEqual(name, attr.Name);
            Assert.AreEqual(shortName, attr.ShortName);
            Assert.AreEqual(desc, attr.Description);
        }
        public void Constructor_should_initialize_properties()
        {
            //  arrange
            const string name = "name";
            const string shortName = "short_name";
            const string desc = "description";

            //  act
            var attr = new ArgumentAttribute(name, shortName, desc);

            //  assert
            Assert.AreEqual(name, attr.Name);
            Assert.AreEqual(shortName, attr.ShortName);
            Assert.AreEqual(desc, attr.Description);
        }
Пример #12
0
        public void ConstructorTest()
        {
            string            name      = "Some name";
            ArgumentAttribute attribute = new ArgumentAttribute(name);

            Assert.AreEqual(name, attribute.Name);
            Assert.IsTrue(attribute.Optional);
            Assert.IsNull(attribute.DefaultValue);
            Assert.IsFalse(attribute.NeedEncode);

            attribute.Optional = false;
            Assert.IsFalse(attribute.Optional);

            attribute.NeedEncode = true;
            Assert.IsTrue(attribute.NeedEncode);
        }
Пример #13
0
        private IArgument GetDynamicArgument(CliSpecification spec, Type t, string parent)
        {
            foreach (PropertyInfo pi in t.GetProperties( ))
            {
                ArgumentAttribute      argAttrib      = pi.GetCustomAttribute <ArgumentAttribute>( );
                FirstArgumentAttribute firstArgAttrib = pi.GetCustomAttribute <FirstArgumentAttribute>( );
                if (argAttrib == null &&
                    firstArgAttrib == null)
                {
                    continue;
                }
                if (argAttrib != null &&
                    (string.Compare(parent, argAttrib.Of, StringComparison.InvariantCulture) != 0 ||
                     t.Name.Contains(parent)))
                {
                    continue;
                }
                if (firstArgAttrib != null &&
                    string.Compare(parent, pi.Name, StringComparison.InvariantCulture) != 0)
                {
                    continue;
                }
                if (!argAttrib?.Dynamic ?? !firstArgAttrib.Dynamic)
                {
                    continue;
                }

                if (argAttrib != null)
                {
                    return(_argTypeMapper.Map(
                               argAttrib,
                               pi,
                               _config.CliConfig,
                               parent));
                }

                return(_argTypeMapper.Map(
                           firstArgAttrib,
                           $"{pi.Name}{ImplicitFirstArg}",
                           pi.PropertyType,
                           spec.Config));
            }

            return(null);
        }
Пример #14
0
        private static void CollectArguments(Type commandType, CommandDescriptor descriptor)
        {
            // Build up a list of arguments that will later be used for parsing
            PropertyInfo[] properties = commandType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo propertyInfo in properties)
            {
                if (propertyInfo.IsDefined(typeof(ArgumentAttribute), true))
                {
                    ArgumentAttribute attribute = (ArgumentAttribute)Attribute.GetCustomAttribute(
                        propertyInfo, typeof(ArgumentAttribute), true);

                    ArgumentDescriptor argumentDescriptor = new ArgumentDescriptor();
                    argumentDescriptor.ArgumentType = propertyInfo.PropertyType;
                    argumentDescriptor.PropertyInfo = propertyInfo;
                    argumentDescriptor.Position     = attribute.Position;

                    // Add the specified short name
                    if (!string.IsNullOrEmpty(attribute.ShortName))
                    {
                        argumentDescriptor.ShortNames.Add(attribute.ShortName);
                    }

                    // Add the specified long name
                    if (!string.IsNullOrEmpty(attribute.LongName))
                    {
                        argumentDescriptor.LongNames.Add(attribute.LongName);
                    }

                    // If this isn't a positional argument, and a short or long name has not been set in the attribute,
                    // then we'll automatically create a long name using the property name
                    if (attribute.Position == -1 &&
                        string.IsNullOrEmpty(attribute.ShortName) &&
                        string.IsNullOrEmpty(attribute.LongName))
                    {
                        argumentDescriptor.LongNames.Add(propertyInfo.Name.ToLower());
                    }

                    descriptor.Arguments.Add(argumentDescriptor);
                }
            }
        }
Пример #15
0
        private static IEnumerable <string> GetEnvironmentVariableAndDefaultValue(ArgumentAttribute attribute,
                                                                                  Func <string, string> getEnvironmentVariable = null)
        {
            var results = new List <string>();

            if (!string.IsNullOrWhiteSpace(attribute.EnvVar))
            {
                var item = (getEnvironmentVariable ?? Environment.GetEnvironmentVariable)(attribute.EnvVar);
                if (item != null)
                {
                    results.Add(item);
                }
            }

            if (!string.IsNullOrEmpty(attribute.Default))
            {
                results.Add(attribute.Default);
            }

            return(results);
        }
Пример #16
0
        private void AddArguments(CliSpecification spec, Type t)
        {
            foreach (PropertyInfo pi in t.GetProperties( ))
            {
                ArgumentAttribute argAttrib = pi.GetCustomAttribute <ArgumentAttribute>( );
                if (argAttrib == null)
                {
                    continue;
                }
                if (!string.IsNullOrEmpty(argAttrib.Of))
                {
                    continue;
                }
                IArgument arg;
                if (argAttrib.Dynamic)
                {
                    spec.DynamicArgument = arg =
                        _argTypeMapper.Map(
                            argAttrib,
                            pi,
                            _config.CliConfig,
                            string.Empty);
                }
                else
                {
                    spec.AddArgument(
                        arg = _argTypeMapper.Map(
                            argAttrib,
                            pi,
                            _config.CliConfig,
                            string.Empty));
                }

                foreach (ArgumentConstraintAttribute ca in pi.GetCustomAttributes <ArgumentConstraintAttribute>( ))
                {
                    ca.Handler.Handle(arg, ca);
                }
            }
        }
Пример #17
0
        private Type GenerateManyToOneColumn(IndentingTextWriter writer, string className, Type columnType,
                                             System.Reflection.FieldInfo fieldInfo, ArgumentAttribute inputAttr, Type type, bool isArray)
        {
            var fieldName = CSharpGeneratorUtils.Capitalize(inputAttr.Name ?? fieldInfo.Name);
            var apiName   = _generatedClasses.GetApiName(type, "");

            writer.WriteLine($"public {className}()");
            writer.WriteLine("{");
            writer.WriteLine("}");
            writer.WriteLine("");
            writer.WriteLine($"public {className}(string output{fieldName}, params string[] input{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"Add{fieldName}(output{fieldName}, input{fieldName}s);");
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine("");
            writer.WriteLine($"public void Add{fieldName}(string name, params string[] source)");
            writer.WriteLine("{");
            writer.Indent();
            if (isArray)
            {
                writer.WriteLine($"var list = {fieldName} == null ? new List<{apiName}>() : new List<{apiName}>({fieldName});");
                writer.WriteLine($"list.Add(ManyToOneColumn<{apiName}>.Create(name, source));");
                writer.WriteLine($"{fieldName} = list.ToArray();");
            }
            else
            {
                writer.WriteLine($"{fieldName} = ManyToOneColumn<{apiName}>.Create(name, source);");
            }
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine();

            Contracts.Assert(columnType == null);

            columnType = type;
            return(columnType);
        }
        public void GetArgumentAttribute_With_InvalidEnum_Return_Null()
        {
            ArgumentAttribute argumentAttribute = ((MockEnum)(-1)).GetArgumentAttribute();

            Assert.IsNull(argumentAttribute);
        }
Пример #19
0
 void Bind(object commando, PropertyInfo property, List <CommandLineParameter> parameters, ArgumentAttribute attribute, BindingContext context)
 {
     if (attribute is PositionalArgumentAttribute)
     {
         BindPositional(commando, property, parameters, (PositionalArgumentAttribute)attribute, context);
     }
     else if (attribute is NamedArgumentAttribute)
     {
         BindNamed(commando, property, parameters, (NamedArgumentAttribute)attribute, context);
     }
     else
     {
         throw Ex("Don't know the attribute type {0}", attribute.GetType().Name);
     }
 }
Пример #20
0
 public PropArg(PropertyInfo propInfo, ArgumentAttribute argAttribute)
 {
     Property = propInfo;
     Argument = argAttribute;
 }
        private Type GenerateOneToOneColumn(IndentedTextWriter writer, string className, Type columnType,
                                            System.Reflection.FieldInfo fieldInfo, ArgumentAttribute inputAttr, Type type, bool isArray)
        {
            var fieldName     = CSharpGeneratorUtils.Capitalize(inputAttr.Name ?? fieldInfo.Name);
            var generatedType = _generatedClasses.GetApiName(type, "");

            writer.WriteLine($"public {className}()");
            writer.WriteLine("{");
            writer.WriteLine("}");
            writer.WriteLine("");
            writer.WriteLine($"public {className}(params string[] input{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"if (input{fieldName}s != null)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"foreach (string input in input{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"Add{fieldName}(input);");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine("");
            writer.WriteLine($"public {className}(params (string inputColumn, string outputColumn)[] inputOutput{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"if (inputOutput{fieldName}s != null)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"foreach (var inputOutput in inputOutput{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"Add{fieldName}(inputOutput.outputColumn, inputOutput.inputColumn);");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine("");
            writer.WriteLine($"public void Add{fieldName}(string inputColumn)");
            writer.WriteLine("{");
            writer.Indent();
            if (isArray)
            {
                writer.WriteLine($"var list = {fieldName} == null ? new List<{generatedType}>() : new List<{generatedType}>({fieldName});");
                writer.WriteLine($"list.Add(OneToOneColumn<{generatedType}>.Create(inputColumn));");
                writer.WriteLine($"{fieldName} = list.ToArray();");
            }
            else
            {
                writer.WriteLine($"{fieldName} = OneToOneColumn<{generatedType}>.Create(inputColumn);");
            }
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLineNoTabs();
            writer.WriteLine($"public void Add{fieldName}(string outputColumn, string inputColumn)");
            writer.WriteLine("{");
            writer.Indent();
            if (isArray)
            {
                writer.WriteLine($"var list = {fieldName} == null ? new List<{generatedType}>() : new List<{generatedType}>({fieldName});");
                writer.WriteLine($"list.Add(OneToOneColumn<{generatedType}>.Create(outputColumn, inputColumn));");
                writer.WriteLine($"{fieldName} = list.ToArray();");
            }
            else
            {
                writer.WriteLine($"{fieldName} = OneToOneColumn<{generatedType}>.Create(outputColumn, inputColumn);");
            }
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLineNoTabs();

            Contracts.Assert(columnType == null);

            columnType = type;
            return(columnType);
        }
        public void GetArgumentAttribute_With_ValidArgument_Return_InstanceArgumentAttribute()
        {
            ArgumentAttribute argumentAttribute = MockEnum.Mock1.GetArgumentAttribute();

            Assert.IsNotNull(argumentAttribute);
        }
        protected override string GetAnnotatedDescription()
        {
            ArgumentAttribute descriptionAttribute = AttributeProvider.GetCustomAttribute <ArgumentAttribute>();

            return(descriptionAttribute?.Description);
        }
        private void AddArgument(PropertyInfo prop,
                                 ArgumentAttribute argumentAttr,
                                 ConventionContext convention,
                                 SortedList <int, CommandArgument> argOrder,
                                 Dictionary <int, PropertyInfo> argPropOrder)
        {
            var argument = argumentAttr.Configure(prop);

            foreach (var attr in prop.GetCustomAttributes().OfType <ValidationAttribute>())
            {
                argument.Validators.Add(new AttributeValidator(attr));
            }

            argument.MultipleValues =
                prop.PropertyType.IsArray ||
                (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) &&
                 prop.PropertyType != typeof(string));

            if (argPropOrder.TryGetValue(argumentAttr.Order, out var otherProp))
            {
                throw new InvalidOperationException(
                          Strings.DuplicateArgumentPosition(argumentAttr.Order, prop, otherProp));
            }

            argPropOrder.Add(argumentAttr.Order, prop);
            argOrder.Add(argumentAttr.Order, argument);

            var setter = ReflectionHelper.GetPropertySetter(prop);

            if (argument.MultipleValues)
            {
                convention.Application.OnParsingComplete(r =>
                {
                    var collectionParser = CollectionParserProvider.Default.GetParser(
                        prop.PropertyType,
                        convention.Application.ValueParsers);
                    if (collectionParser == null)
                    {
                        throw new InvalidOperationException(Strings.CannotDetermineParserType(prop));
                    }

                    if (argument.Values.Count == 0)
                    {
                        return;
                    }

                    if (r.SelectedCommand is IModelAccessor cmd)
                    {
                        setter.Invoke(cmd.GetModel(), collectionParser.Parse(argument.Name, argument.Values));
                    }
                });
            }
            else
            {
                convention.Application.OnParsingComplete(r =>
                {
                    var parser = convention.Application.ValueParsers.GetParser(prop.PropertyType);
                    if (parser == null)
                    {
                        throw new InvalidOperationException(Strings.CannotDetermineParserType(prop));
                    }

                    if (argument.Values.Count == 0)
                    {
                        return;
                    }

                    if (r.SelectedCommand is IModelAccessor cmd)
                    {
                        setter.Invoke(
                            cmd.GetModel(),
                            parser.Parse(
                                argument.Name,
                                argument.Value,
                                convention.Application.ValueParsers.ParseCulture));
                    }
                });
            }
        }
        public void GetArgumentAttribute_With_EnumWIthoutAttribute_Return_Null()
        {
            ArgumentAttribute argumentAttribute = MockEnum.Mock4.GetArgumentAttribute();

            Assert.IsNull(argumentAttribute);
        }