Example #1
0
        static void HandleCommand(CommandLineApplication cla, CommandLineBinding binding,
                                  MemberInfo m, Func <object> modelGetter)
        {
            if (!binding._executed)
            {
                return;
            }

            if (m is MethodInfo)
            {
                var mi       = (MethodInfo)m;
                var miParams = mi.GetParameters();
                if (miParams.Length == 1)
                {
                    mi.Invoke(binding._parentBinding.GetModel(), new object[] { modelGetter() });
                }
                else if (miParams.Length == 0)
                {
                    mi.Invoke(binding._parentBinding.GetModel(), EmptyValues);
                }
            }
            else if (m is PropertyInfo)
            {
                var pi = (PropertyInfo)m;
                pi.SetValue(binding._parentBinding.GetModel(), modelGetter());
            }
        }
Example #2
0
        static void HandleRemainingArguments(RemainingArgumentsAttribute att,
                                             CommandLineBinding binding, MemberInfo m)
        {
            if (att.SkipIfNone && binding._cla.RemainingArguments?.Count == 0)
            {
                // No remaining args
                return;
            }

            var args = binding._cla.RemainingArguments?.ToArray();

            if (args == null)
            {
                args = new string[0];
            }

            if (m is MethodInfo)
            {
                var mi = (MethodInfo)m;
                mi.Invoke(binding.GetModel(), args);
            }
            else if (m is PropertyInfo)
            {
                var pi = (PropertyInfo)m;
                pi.SetValue(binding.GetModel(), args);
            }
        }
Example #3
0
        public void TestBasicOnExec()
        {
            var b1 = CommandLineBinding <BasicOnExec1> .Build();

            Assert.False(b1.Model._onExecInvoked);
            var r1 = b1.Execute();

            Assert.False(b1.Model._onExecInvoked);
            Assert.Equal(0, r1);

            var b2 = CommandLineBinding <BasicOnExec2> .Build();

            Assert.False(b2.Model._onExecInvoked);
            Assert.Null(b2.Model._onExecParam);
            var r2 = b2.Execute();

            Assert.True(b2.Model._onExecInvoked);
            Assert.NotNull(b2.Model._onExecParam);
            Assert.Equal(0, r2);

            var b3 = CommandLineBinding <BasicOnExec3> .Build();

            Assert.False(b3.Model._onExecInvoked);
            Assert.Null(b3.Model._onExecParam);
            var r3 = b3.Execute();

            Assert.True(b3.Model._onExecInvoked);
            Assert.NotNull(b3.Model._onExecParam);
            Assert.Equal(BasicOnExec3.RETURN_VALUE, r3);
        }
Example #4
0
        public void TestSameExecMultiNames()
        {
            var args = new[]
            {
                new[] { "-g", "Howdy!" },
                new[] { "-g", "Howdy!", "--uppercase" },
                new[] { "-g", "Howdy!", "--uppercase", "name", "John", "Jacob", "Jingle" },
            };

            var claOut   = new StringWriter();
            var claError = new StringWriter();

            var binderOut   = new StringWriter();
            var binderError = new StringWriter();

            foreach (var a in args)
            {
                var cla    = BuildDocSampleCLA();
                var binder = CommandLineBinding <DocSampleModel> .Build();

                SetOutErr(cla, claOut, claError);
                binder.Out   = binderOut;
                binder.Error = binderError;

                cla.Execute(a);
                binder.Execute(a);
            }

//Console.WriteLine(nameof(TestSameExecMultiNames) + "Out:  " + binderOut.ToString());
//Console.WriteLine(nameof(TestSameExecMultiNames) + "Err:  " + binderError.ToString());

            Assert.Equal(claOut.ToString(), binderOut.ToString());
            Assert.Equal(claError.ToString(), binderError.ToString());
        }
Example #5
0
        public void TestSameNameHelp()
        {
            var claOut   = new StringWriter();
            var claError = new StringWriter();

            var binderOut   = new StringWriter();
            var binderError = new StringWriter();

            var cla    = BuildDocSampleCLA();
            var binder = CommandLineBinding <DocSampleModel> .Build();

            SetOutErr(cla, claOut, claError);
            binder.Out   = binderOut;
            binder.Error = binderError;

            var args = new[] { "name", "--help-me" };

            cla.Execute(args);
            binder.Execute(args);

//Console.WriteLine(nameof(TestSameNameHelp) + "Out:  " + claOut.ToString());
//Console.WriteLine(nameof(TestSameNameHelp) + "Err:  " + claError.ToString());

            Assert.Equal(claOut.ToString(), binderOut.ToString());
            Assert.Equal(claError.ToString(), binderError.ToString());
        }
Example #6
0
        public void TestBasicOnBind()
        {
            var b1 = CommandLineBinding <BasicOnBind1> .Build();

            Assert.NotNull(b1.Model._opt1OnBindConfig);
            Assert.NotNull(b1.Model._arg1OnBindConfig);
            Assert.NotNull(b1.Model._cmd1OnBindConfig);
        }
Example #7
0
        public void TestBasicRemainingArgs()
        {
            var empty = new string[0];

            var b1_1 = CommandLineBinding <BasicRemainingArgs1> .Build();

            Assert.Null(b1_1.Model.TheRest);
            b1_1.Execute();
            Assert.Equal(empty, b1_1.Model.TheRest);

            var b1_2 = CommandLineBinding <BasicRemainingArgs1> .Build();

            Assert.Null(b1_2.Model.TheRest);
            b1_2.Execute("--flag1");
            Assert.Equal(empty, b1_2.Model.TheRest);

            var b1_3 = CommandLineBinding <BasicRemainingArgs1> .Build();

            Assert.Null(b1_3.Model.TheRest);
            b1_3.Execute("--opt1", "opt1-value", "--multi1", "m1", "--multi1", "m2");
            Assert.Equal(empty, b1_3.Model.TheRest);

            var b2_1 = CommandLineBinding <BasicRemainingArgs1> .Build();

            Assert.Null(b2_1.Model.TheRest);
            b2_1.Execute("foo");
            Assert.Equal(new[] { "foo" }, b2_1.Model.TheRest);

            var b2_2 = CommandLineBinding <BasicRemainingArgs1> .Build();

            Assert.Null(b2_2.Model.TheRest);
            b2_2.Execute("foo", "bar", "baz");
            Assert.Equal(new[] { "foo", "bar", "baz" }, b2_2.Model.TheRest);

            var b3_1 = CommandLineBinding <BasicRemainingArgs1> .Build();

            Assert.Null(b3_1.Model.TheRest);
            b3_1.Execute("--flag1", "foo");
            Assert.Equal(new[] { "foo" }, b3_1.Model.TheRest);

            var b3_2 = CommandLineBinding <BasicRemainingArgs1> .Build();

            Assert.Null(b3_2.Model.TheRest);
            b3_2.Execute("--opt1", "opt1-value", "--multi1", "m1", "--multi1", "m2", "foo", "bar", "baz");
            Assert.Equal("opt1-value", b3_2.Model.Opt1);
            Assert.Equal(new[] { "m1", "m2" }, b3_2.Model.Multi1);
            Assert.Equal(new[] { "foo", "bar", "baz" }, b3_2.Model.TheRest);

            // This scenario is not supported (interleaved un-named args with named args)
            //var b3_3 = CommandLineBinding<BasicRemainingArgs1>.Build();
            //Assert.Null(b3_3.Model.TheRest);
            //b3_3.Execute("--opt1", "opt1-value", "foo", "--multi1", "m1", "bar", "--multi1", "m2", "baz");
            //Assert.Equal("opt1-value", b3_3.Model.Opt1);
            //Assert.Equal(new[] { "m1", "m2" }, b3_3.Model.Multi1);
            //Assert.Equal(new[] { "foo", "bar", "baz" }, b3_3.Model.TheRest);
        }
Example #8
0
        static void AddVersionOption(CommandLineBinding binding, Attribute att, MemberInfo m)
        {
            if (att is VersionOptionAttribute)
            {
                binding._versionOption = (VersionOptionAttribute)att;

                binding._bindingActions.Add(() =>
                {
                    if (binding._versionOption == null)
                    {
                        return;
                    }

                    if (binding._versionShortGetter == null)
                    {
                        binding._versionShortGetter = binding._versionLongGetter;
                    }

                    if (binding._versionShortGetter != null)
                    {
                        binding._cla.VersionOption(binding._versionOption.Template,
                                                   binding._versionShortGetter, binding._versionLongGetter);
                    }
                    else
                    {
                        binding._cla.VersionOption(binding._versionOption.Template,
                                                   binding._versionOption.ShortVersion, binding._versionOption.LongVersion);
                    }
                });
            }
            else if (att is ShortVersionGetterAttribute || att is LongVersionGetterAttribute)
            {
                var           mi     = m as MethodInfo;
                var           pi     = m as PropertyInfo;
                Func <string> getter = null;

                if (mi != null && mi.ReturnParameter.ParameterType == typeof(string) &&
                    mi.GetParameters().Length == 0)
                {
                    getter = () => (string)mi.Invoke(binding.GetModel(), EmptyValues);
                }
                else if (pi != null && pi.PropertyType == typeof(string))
                {
                    getter = () => (string)pi.GetValue(binding.GetModel());
                }

                if (getter != null && att is ShortVersionGetterAttribute)
                {
                    binding._versionShortGetter = getter;
                }
                if (getter != null && att is LongVersionGetterAttribute)
                {
                    binding._versionLongGetter = getter;
                }
            }
        }
Example #9
0
        public void TestBasicCommands()
        {
            var outWriter = new StringWriter();
            var errWriter = new StringWriter();;
            var binding   = CommandLineBinding <BasicCommands> .Build();

            binding.Out   = outWriter;
            binding.Error = errWriter;

            binding.Execute(BasicCommands.HELP_TEMPLATE);
// Console.WriteLine("*******************************");
// Console.WriteLine("Out:  " + outWriter.ToString());
// Console.WriteLine("Err:  " + errWriter.ToString());
// Console.WriteLine("*******************************");
            Assert.True(outWriter.ToString().Contains("sub1"));
            Assert.True(outWriter.ToString().Contains("sub2"));
            Assert.True(outWriter.ToString().Contains("sub3"));
            Assert.Equal(string.Empty, errWriter.ToString());
            Assert.Null(binding.Model.Sub1);
            Assert.Null(binding.Model._sub2);
            Assert.Null(binding.Model.Sub3);

            binding = CommandLineBinding <BasicCommands> .Build();

            binding.Execute("sub1");
            Assert.False(binding.Model.Opt1);
            Assert.NotNull(binding.Model.Sub1);
            Assert.Null(binding.Model.Sub1.Url);
            Assert.Null(binding.Model._sub2);
            Assert.Null(binding.Model.Sub3);

            binding = CommandLineBinding <BasicCommands> .Build();

            binding.Execute("--opt1", "sub1");
            Assert.True(binding.Model.Opt1);
            Assert.NotNull(binding.Model.Sub1);
            Assert.Null(binding.Model.Sub1.Url);
            Assert.Null(binding.Model._sub2);
            Assert.Null(binding.Model.Sub3);

            binding = CommandLineBinding <BasicCommands> .Build();

            binding.Execute("sub1", "--url", "foo");
            Assert.NotNull(binding.Model.Sub1);
            Assert.Equal("foo", binding.Model.Sub1.Url);
            Assert.Null(binding.Model._sub2);
            Assert.Null(binding.Model.Sub3);

            binding = CommandLineBinding <BasicCommands> .Build();

            binding.Execute("sub2");
            Assert.Null(binding.Model.Sub1);
            Assert.NotNull(binding.Model._sub2);
            Assert.Null(binding.Model._sub2.Path);
            Assert.Null(binding.Model.Sub3);
        }
Example #10
0
        public void TestBasicOnInit()
        {
            var b1 = CommandLineBinding <BasicOnInit1> .Build();

            Assert.False(b1.Model._onInitInvoked);

            var b2 = CommandLineBinding <BasicOnInit2> .Build();

            Assert.True(b2.Model._onInitInvoked);
            Assert.NotNull(b2.Model._onInitParam);
        }
Example #11
0
        static void AddHelpOption(CommandLineBinding binding, Attribute att, MemberInfo m)
        {
            var a = (HelpOptionAttribute)att;

            binding._helpOption = a;

            binding._bindingActions.Add(() =>
            {
                binding._cla.HelpOption(binding._helpOption.Template);
            });
        }
Example #12
0
        public void TestEmptyModel1()
        {
            var outWriter = new StringWriter();
            var errWriter = new StringWriter();;

            var x = CommandLineBinding <EmptyModel1> .Build();

            x.Out   = outWriter;
            x.Error = errWriter;
            x.Execute("-f foo --bar bar baz");
            x.Execute("-h");
            x.Execute("-v");

            Assert.Equal(string.Empty, outWriter.ToString());
            Assert.Equal(string.Empty, errWriter.ToString());
        }
Example #13
0
        static void HandleOption(CommandOption co, CommandLineBinding binding, MemberInfo m)
        {
            if (!co.HasValue())
            {
                return;
            }

            object coValue;

            if (co.OptionType == CommandOptionType.NoValue)
            {
                //coValue = bool.Parse(co.Value());
                coValue = true;
            }
            else if (co.OptionType == CommandOptionType.SingleValue)
            {
                coValue = co.Value();
            }
            else
            {
                coValue = co.Values.ToArray();
            }

            if (m is MethodInfo)
            {
                var mi       = (MethodInfo)m;
                var miParams = mi.GetParameters();
                if (miParams.Length == 2)
                {
                    mi.Invoke(binding.GetModel(), new object[] { coValue, binding });
                }
                else if (miParams.Length == 1)
                {
                    mi.Invoke(binding.GetModel(), new object[] { coValue });
                }
                else
                {
                    mi.Invoke(binding.GetModel(), EmptyValues);
                }
            }
            else if (m is PropertyInfo)
            {
                var pi = (PropertyInfo)m;
                pi.SetValue(binding.GetModel(), coValue);
            }
        }
Example #14
0
        static void SetCLA(CommandLineBinding binding, Attribute att)
        {
            var claAtt = (CommandLineAttribute)att;

            if (claAtt == null)
            {
                claAtt = new CommandLineAttribute();
            }

            if (binding._cla == null)
            {
                binding._cla = new CommandLineApplication(claAtt.ThrowOnUnexpectedArg);
            }

            binding._cla.Name                   = claAtt.Name ?? string.Empty;
            binding._cla.FullName               = claAtt.FullName ?? string.Empty;
            binding._cla.Description            = claAtt.Description ?? string.Empty;
            binding._cla.AllowArgumentSeparator = claAtt.AllowArgumentSeparator;
        }
Example #15
0
        public void TestBasicSwitches()
        {
            var boolSwitch     = "--" + nameof(BasicSwitches.ImplicitBool).ToLower();
            var boolNullSwitch = "--" + nameof(BasicSwitches.ImplicitBoolNullable).ToLower();

            var outWriter = new StringWriter();
            var errWriter = new StringWriter();;
            var binding   = CommandLineBinding <BasicSwitches> .Build();

            binding.Out   = outWriter;
            binding.Error = errWriter;
            binding.Execute("--help-me");
            Assert.True(outWriter.ToString().Contains(boolSwitch));
            Assert.True(outWriter.ToString().Contains(boolNullSwitch));
            Assert.Equal(string.Empty, errWriter.ToString());

            binding = CommandLineBinding <BasicSwitches> .Build();

            binding.Execute(boolSwitch);
            Assert.True(binding.Model._impliciBoolCalled);
            Assert.True(binding.Model._impliciBoolValue);
            Assert.False(binding.Model.ImplicitBoolNullable.HasValue);

            // TODO:
            // Apparently NoValue options of the formt --opt:true or --opt:false
            // are not support contrary to my interpretation of
            //    https://msdn.microsoft.com/en-us/magazine/mt763239.aspx?f=255&MSPPError=-2147217396
            //model = CommandLineModel<BasicSwitches>.Build();
            //model.Execute(boolSwitch + "=true");
            //Assert.True(model.Instance._impliciBoolCalled);
            //Assert.False(model.Instance._impliciBoolValue);
            //Assert.False(model.Instance.ImplicitBoolNullable.HasValue);

            binding = CommandLineBinding <BasicSwitches> .Build();

            binding.Execute(boolNullSwitch);
            Assert.False(binding.Model._impliciBoolCalled);
            Assert.False(binding.Model._impliciBoolValue);
            Assert.True(binding.Model.ImplicitBoolNullable.HasValue);
            Assert.True(binding.Model.ImplicitBoolNullable.Value);
        }
Example #16
0
        public void TestBasicMultiOptions()
        {
            var outWriter = new StringWriter();
            var errWriter = new StringWriter();;
            var binding   = CommandLineBinding <BasicMultiOptions> .Build();

            binding.Out   = outWriter;
            binding.Error = errWriter;

            binding.Execute(BasicMultiOptions.HELP_TEMPLATE);
// Console.WriteLine("*******************************");
// Console.WriteLine("Out:  " + outWriter.ToString());
// Console.WriteLine("Err:  " + errWriter.ToString());
// Console.WriteLine("*******************************");

            binding = CommandLineBinding <BasicMultiOptions> .Build();

            binding.Execute("--multi1", "v1", "--multi1", "v2", "--multi1", "v3");
            Assert.Equal(new[] { "v1", "v2", "v3", }, binding.Model.Multi1);

            binding = CommandLineBinding <BasicMultiOptions> .Build();

            binding.Execute("--multi2", "v1", "--multi2", "v2", "--multi2", "v3");
            Assert.Equal(new[] { "v1", "v2", "v3", }, binding.Model._multi2Values);

            binding = CommandLineBinding <BasicMultiOptions> .Build();

            binding.Execute("--multi3", "v1", "--multi3", "v2", "--multi3", "v3");
            Assert.Equal(new[] { "v1", "v2", "v3", }, binding.Model._multi3Values);

            binding = CommandLineBinding <BasicMultiOptions> .Build();

            binding.Execute(
                "--multi1", "v1", "--multi2", "v2", "--multi3", "v3",
                "--multi1", "vA", "--multi2", "vB", "--multi3", "vC",
                "--multi1", "vI", "--multi2", "vII", "--multi3", "vIII"
                );
            Assert.Equal(new[] { "v1", "vA", "vI", }, binding.Model.Multi1);
            Assert.Equal(new[] { "v2", "vB", "vII", }, binding.Model._multi2Values);
            Assert.Equal(new[] { "v3", "vC", "vIII", }, binding.Model._multi3Values);
        }
Example #17
0
        static void BindRemainingArguments(CommandLineBinding binding)
        {
            var m = binding._remainingArgumentsMember;

            if (m == null)
            {
                return;
            }

            var a            = (RemainingArgumentsAttribute)m.GetCustomAttribute(typeof(RemainingArgumentsAttribute));
            var onConfigName = $"{m.Name}{MemberOnBindMethodSuffix}";
            var onConfigMeth = binding.GetModel().GetType().GetTypeInfo().GetMethod(
                onConfigName, OnBindRemainingArgumentsParams);

            if (onConfigMeth != null)
            {
                onConfigMeth.Invoke(binding.GetModel(), new[] { binding._cla });
            }

            binding._postExecActions.Add(() => { HandleRemainingArguments(a, binding, m); });
        }
Example #18
0
        public void TestHelpfulEmptyModel()
        {
            var outWriter = new StringWriter();
            var errWriter = new StringWriter();;

            var binding = CommandLineBinding <HelpfulEmptyModel> .Build();

            binding.Out   = outWriter;
            binding.Error = errWriter;

            binding.Execute("-f foo --bar bar baz");
            Assert.Equal(string.Empty, outWriter.ToString());

            binding.Execute("-v");
            Assert.Equal(string.Empty, outWriter.ToString());

            binding.Execute("-h");
            Assert.True(outWriter.ToString().Contains("Usage"));
            Assert.True(outWriter.ToString().Contains("Options"));
            Assert.True(outWriter.ToString().Contains("Show help information"));

            Assert.Equal(string.Empty, errWriter.ToString());
        }
Example #19
0
        public void TestDynamicallyVersionedEmptyModel()
        {
            var outWriter = new StringWriter();
            var errWriter = new StringWriter();;

            var binding = CommandLineBinding <DynamicallyVersionedEmptyModel> .Build();

            binding.Out   = outWriter;
            binding.Error = errWriter;
            binding.Execute("-f foo --bar bar baz");
            Assert.Equal(string.Empty, outWriter.ToString());

            binding.Execute("-h");
            Assert.Equal(string.Empty, outWriter.ToString());

            binding.Execute("--version");

            Assert.Equal($"{nameof(DynamicallyVersionedEmptyModel)} {DynamicallyVersionedEmptyModel.SVER}",
                         binding.GetFullNameAndVersion());
            Assert.Equal($"{nameof(DynamicallyVersionedEmptyModel)}\r\n{DynamicallyVersionedEmptyModel.LVER}",
                         outWriter.ToString().Trim());
            Assert.Equal(string.Empty, errWriter.ToString());
        }
Example #20
0
        static void HandleArgument(CommandArgument ca, CommandLineBinding binding, MemberInfo m)
        {
            if (ca.Values?.Count == 0)
            {
                return;
            }

            object caValue;

            if (ca.MultipleValues)
            {
                caValue = ca.Values.ToArray();
            }
            else
            {
                caValue = ca.Value;
            }

            if (m is MethodInfo)
            {
                var mi       = (MethodInfo)m;
                var miParams = mi.GetParameters();
                if (miParams.Length == 2)
                {
                    mi.Invoke(binding.GetModel(), new object[] { caValue, binding });
                }
                else
                {
                    mi.Invoke(binding.GetModel(), new object[] { caValue });
                }
            }
            else if (m is PropertyInfo)
            {
                var pi = (PropertyInfo)m;
                pi.SetValue(binding.GetModel(), caValue);
            }
        }
Example #21
0
        public void TestSameExecBadOption()
        {
            var claOut   = new StringWriter();
            var claError = new StringWriter();

            var binderOut   = new StringWriter();
            var binderError = new StringWriter();

            var cla    = BuildDocSampleCLA();
            var binder = CommandLineBinding <DocSampleModel> .Build();

            SetOutErr(cla, claOut, claError);
            binder.Out   = binderOut;
            binder.Error = binderError;

            cla.Execute("--foo");
            binder.Execute("--foo");

// Console.WriteLine("Out:  " + claOut.ToString());
// Console.WriteLine("Err:  " + claError.ToString());

            Assert.Equal(claOut.ToString(), binderOut.ToString());
            Assert.Equal(claError.ToString(), binderError.ToString());
        }
Example #22
0
        static void AddCommand(CommandLineBinding binding, Attribute att, MemberInfo m)
        {
            var a = (CommandAttribute)att;

            var cmdName = a.Name;

            if (string.IsNullOrEmpty(cmdName))
            {
                cmdName = m.Name.ToLower();
            }

            Type cmdType;

            if (m is MethodInfo)
            {
                var mi       = (MethodInfo)m;
                var miParams = mi.GetParameters();

                if (miParams.Length == 1)
                {
                    cmdType = miParams[0].ParameterType;
                }
                else if (miParams.Length == 0)
                {
                    cmdType = null;
                }
                else
                {
                    throw new NotSupportedException("method signature is not supported");
                }
            }
            else if (m is PropertyInfo)
            {
                var pi = (PropertyInfo)m;
                cmdType = pi.PropertyType;
            }
            else
            {
                return;
            }

            // See if there is an optional configuration method for this sub-command
            var onConfigName = $"{m.Name}{MemberOnBindMethodSuffix}";
            var onConfigMeth = binding.GetModel().GetType().GetTypeInfo().GetMethod(
                onConfigName, OnBindCommandParams);

            // Add the option based on whether there is a config method
            Action <CommandLineApplication> configAction = cla => { };

            if (onConfigMeth != null)
            {
                configAction = cla => onConfigMeth.Invoke(binding.GetModel(), new[] { cla });
            }

            var subCla = binding._cla.Command(cmdName, configAction, a.ThrowOnUnexpectedArg);

            // When a sub-command is specified, its OnExecute handler is invoked instead of the
            // parent's so we inject a post-exec action to invoke the parent's post-exec actions
            Action parentPostExec = () => binding.PostExec(true);
            var    subBinding     = CommandLineBinding.BindModel(cmdType, subCla,
                                                                 binding.GetModel(), parentPostExec);

            subBinding._parentBinding = binding;
            binding._childBindings.Add(subBinding);

            // This is already invoked by Apply which is invoke by Build
            //subModelSetCLA.Invoke(null, new object[] { subModel, cmdType.GetTypeInfo()
            //        .GetCustomAttribute<CommandLineApplicationAttribute>() });

            // We need to make sure the command name from the Command attr is preserved  after
            // processing of the optional CLA attr on the subclass which may have its own name
            subCla.Name = cmdName;

            binding._postExecActions.Add(() => HandleCommand(subCla, subBinding, m,
                                                             () => subBinding.GetModel()));
        }
Example #23
0
        static void AddOption(CommandLineBinding binding, Attribute att, MemberInfo m)
        {
            var a = (OptionAttribute)att;

            // Resolve the option value type
            Type valueType = null;

            if (m is PropertyInfo)
            {
                var pi = (PropertyInfo)m;
                valueType = pi.PropertyType;
            }
            else if (m is MethodInfo)
            {
                var mi       = (MethodInfo)m;
                var miParams = mi.GetParameters();

                if (miParams.Length == 1 || (miParams.Length == 2 &&
                                             typeof(CommandLineBinding).GetTypeInfo().IsAssignableFrom(miParams[1].ParameterType)))
                {
                    valueType = miParams[0].ParameterType;
                }
                else if (miParams.Length > 0)
                {
                    throw new NotSupportedException("method signature is not supported");
                }
            }

            // Figure out the option type based on value type if it wasn't explicitly specified
            CommandOptionType optionType = CommandOptionType.NoValue;

            if (a.OptionType == null && valueType != null)
            {
                // Try to resolve the option type based on the property type
                if (valueType.GetTypeInfo().IsAssignableFrom(typeof(string)))
                {
                    optionType = CommandOptionType.SingleValue;
                }
                else if (valueType.GetTypeInfo().IsAssignableFrom(typeof(string[])))
                {
                    optionType = CommandOptionType.MultipleValue;
                }
                else if (valueType == typeof(bool?) || valueType == typeof(bool))
                {
                    optionType = CommandOptionType.NoValue;
                }
                else
                {
                    throw new NotSupportedException("option value type is not supported");
                }
            }

            // Resolve the option template if it wasn't explicitly specified
            var template = a.Template;

            if (string.IsNullOrEmpty(template))
            {
                template = $"--{m.Name.ToLower()}";
            }

            // See if there is an optional configuration method for this option
            var onConfigName = $"{m.Name}{MemberOnBindMethodSuffix}";
            var onConfigMeth = binding.GetModel().GetType().GetTypeInfo().GetMethod(
                onConfigName, OnBindOptionParams);

            // Add the option based on whether there is a config method
            CommandOption co;

            if (onConfigMeth != null)
            {
                co = binding._cla.Option(template, a.Description,
                                         optionType,
                                         cmdOpt => onConfigMeth.Invoke(binding.GetModel(), new[] { cmdOpt }),
                                         a.Inherited);
            }
            else
            {
                co = binding._cla.Option(template, a.Description,
                                         optionType,
                                         a.Inherited);
            }

            // Add a post-exec handler for this option
            binding._postExecActions.Add(() => HandleOption(co, binding, m));
        }
Example #24
0
        static void AddArgument(CommandLineBinding binding, Attribute att, MemberInfo m)
        {
            var a = (ArgumentAttribute)att;

            // Resolve the option value type
            Type valueType = null;

            if (m is PropertyInfo)
            {
                var pi = (PropertyInfo)m;
                valueType = pi.PropertyType;
            }
            else if (m is MethodInfo)
            {
                var mi       = (MethodInfo)m;
                var miParams = mi.GetParameters();

                if (miParams.Length == 1 || (miParams.Length == 2 &&
                                             typeof(CommandLineBinding).GetTypeInfo().IsAssignableFrom(miParams[1].ParameterType)))
                {
                    valueType = miParams[0].ParameterType;
                }
                else if (miParams.Length > 0)
                {
                    throw new NotSupportedException("method signature is not supported");
                }
            }

            // Figure out the argument arity based on value type if it wasn't explicitly specified
            var multi = a.MultipleValues;

            if (multi == null && valueType != null)
            {
                // Try to resolve the option type based on the property type
                if (valueType.GetTypeInfo().IsAssignableFrom(typeof(string)))
                {
                    multi = false;
                }
                else if (valueType.GetTypeInfo().IsAssignableFrom(typeof(string[])))
                {
                    multi = true;
                }
                else
                {
                    throw new NotSupportedException("option value type is not supported");
                }
            }

            // Resolve the arg name if it wasn't explicitly specified
            var argName = a.Name;

            if (string.IsNullOrEmpty(argName))
            {
                argName = m.Name.ToLower();
            }

            // See if there is an optional configuration method for this option
            var onConfigName = $"{m.Name}{MemberOnBindMethodSuffix}";
            var onConfigMeth = binding.GetModel().GetType().GetTypeInfo().GetMethod(
                onConfigName, OnBindArgumentParams);

            CommandArgument ca;

            if (onConfigMeth != null)
            {
                ca = binding._cla.Argument(argName, a.Description,
                                           cmdArg => onConfigMeth.Invoke(binding.GetModel(), new[] { cmdArg }),
                                           multi.GetValueOrDefault());
            }
            else
            {
                ca = binding._cla.Argument(argName, a.Description, multi.GetValueOrDefault());
            }

            binding._postExecActions.Add(() => { HandleArgument(ca, binding, m); });
        }
Example #25
0
        static void AddRemainingArguments(CommandLineBinding binding, Attribute att, MemberInfo m)
        {
            var a = (RemainingArgumentsAttribute)att;

            binding._remainingArgumentsMember = m;
        }
Example #26
0
        public void TestEmptyModel2b()
        {
            var x = CommandLineBinding <EmptyModel2> .Build();

            x.Execute("-f", "foo", "--bar", "bar", "baz");
        }