Exemplo n.º 1
0
        /// <summary>
        /// Parses a string array of command line arguments constructing values in an instance of type <typeparamref name="T"/>.
        /// Grammar rules are defined decorating public properties with appropriate attributes.
        /// </summary>
        /// <typeparam name="T">Type of the target instance built with parsed value.</typeparam>
        /// <param name="factory">A <see cref="System.Func{T}"/> delegate used to initialize the target instance.</param>
        /// <param name="args">A <see cref="System.String"/> array of command line arguments, normally supplied by application entry point.</param>
        /// <returns>A <see cref="CommandLine.ParserResult{T}"/> containing an instance of type <typeparamref name="T"/> with parsed values
        /// and a sequence of <see cref="CommandLine.Error"/>.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if one or more arguments are null.</exception>
        public ParserResult <T> ParseArguments <T>(Func <T> factory, IEnumerable <string> args)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (!typeof(T).IsMutable())
            {
                throw new ArgumentException("factory");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            return(MakeParserResult(
                       InstanceBuilder.Build(
                           Maybe.Just(factory),
                           (arguments, optionSpecs) => Tokenize(arguments, optionSpecs, settings),
                           args,
                           settings.NameComparer,
                           settings.CaseInsensitiveEnumValues,
                           settings.ParsingCulture,
                           settings.AutoHelp,
                           settings.AutoVersion,
                           settings.AllowMultiInstance,
                           HandleUnknownArguments(settings.IgnoreUnknownArguments)),
                       settings));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Parses a string array of command line arguments constructing values in an instance of type <typeparamref name="T"/>.
        /// Grammar rules are defined decorating public properties with appropriate attributes.
        /// </summary>
        /// <typeparam name="T">Type of the target instance built with parsed value.</typeparam>
        /// <param name="args">A <see cref="System.String"/> array of command line arguments, normally supplied by application entry point.</param>
        /// <returns>A <see cref="CommandLine.ParserResult{T}"/> containing an instance of type <typeparamref name="T"/> with parsed values
        /// and a sequence of <see cref="CommandLine.Error"/>.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if one or more arguments are null.</exception>
        public ParserResult <T> ParseArguments <T>(IEnumerable <string> args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            var factory = typeof(T).IsMutable()
                ? Maybe.Just <Func <T> >(Activator.CreateInstance <T>)
                : Maybe.Nothing <Func <T> >();

            return(MakeParserResult(
                       InstanceBuilder.Build(
                           factory,
                           (arguments, optionSpecs) => Tokenize(arguments, optionSpecs, settings),
                           args,
                           settings.NameComparer,
                           settings.CaseInsensitiveEnumValues,
                           settings.ParsingCulture,
                           settings.AutoHelp,
                           settings.AutoVersion,
                           settings.AllowMultiInstance,
                           HandleUnknownArguments(settings.IgnoreUnknownArguments)),
                       settings));
        }
Exemplo n.º 3
0
        public void Double_dash_force_subsequent_arguments_as_values()
        {
            // Fixture setup
            var expectedResult = new FakeOptionsWithValues
            {
                StringValue    = "str1",
                LongValue      = 10L,
                StringSequence = new[] { "-a", "--bee", "-c" },
                IntValue       = 20
            };
            var arguments = new[] { "--stringvalue", "str1", "--", "10", "-a", "--bee", "-c", "20" };

            // Exercize system
            var result = InstanceBuilder.Build(
                () => new FakeOptionsWithValues(),
                (a, optionSpecs) =>
                Tokenizer.PreprocessDashDash(a,
                                             args => Tokenizer.Tokenize(args, name => NameLookup.Contains(name, optionSpecs, StringComparer.Ordinal))),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expectedResult.ShouldHave().AllProperties().EqualTo(result.Value);

            // Teardown
        }
Exemplo n.º 4
0
        public void Double_dash_force_subsequent_arguments_as_values()
        {
            // Fixture setup
            var expectedResult = new Simple_Options_With_Values
            {
                StringValue    = "str1",
                LongValue      = 10L,
                StringSequence = new[] { "-a", "--bee", "-c" },
                IntValue       = 20
            };
            var arguments = new[] { "--stringvalue", "str1", "--", "10", "-a", "--bee", "-c", "20" };

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <Simple_Options_With_Values> >(() => new Simple_Options_With_Values()),
                (a, optionSpecs) =>
                Tokenizer.PreprocessDashDash(a,
                                             args => Tokenizer.Tokenize(args, name => NameLookup.Contains(name, optionSpecs, StringComparer.Ordinal))),
                arguments,
                StringComparer.Ordinal,
                false,
                CultureInfo.InvariantCulture,
                true,
                true,
                Enumerable.Empty <ErrorType>());

            // Verify outcome
            expectedResult.Should().BeEquivalentTo(((Parsed <Simple_Options_With_Values>)result).Value);

            // Teardown
        }
Exemplo n.º 5
0
        /// <summary>
        /// Parses a string array of command line arguments constructing values in an instance of type <typeparamref name="T"/>.
        /// Grammar rules are defined decorating public properties with appropriate attributes.
        /// </summary>
        /// <typeparam name="T">Type of the target instance built with parsed value.</typeparam>
        /// <param name="factory">A <see cref="System.Func{T}"/> delegate used to intitalize the target instance.</param>
        /// <param name="args">A <see cref="System.String"/> array of command line arguments, normally supplied by application entry point.</param>
        /// <returns>A <see cref="CommandLine.ParserResult{T}"/> containing an instance of type <typeparamref name="T"/> with parsed values
        /// and a sequence of <see cref="CommandLine.Error"/>.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if one or more arguments are null.</exception>
        public ParserResult <T> ParseArguments <T>(Func <T> factory, IEnumerable <string> args)
            where T : new()
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (!typeof(T).IsMutable())
            {
                throw new ArgumentException("factory");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            return(MakeParserResult(
                       () => InstanceBuilder.Build(
                           Maybe.Just(factory),
                           (arguments, optionSpecs) => Tokenize(arguments, optionSpecs, settings),
                           args,
                           settings.NameComparer,
                           settings.ParsingCulture),
                       settings));
        }
Exemplo n.º 6
0
 private static ParserResult <T> InvokeBuildImmutable <T>(string[] arguments)
 {
     return(InstanceBuilder.Build(
                Maybe.Nothing <Func <T> >(),
                (args, optionSpecs) => Tokenizer.ConfigureTokenizer(StringComparer.Ordinal, false, false)(args, optionSpecs),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture,
                Enumerable.Empty <ErrorType>()));
 }
        public void Empty_set_options_allowed_with_mutually_exclusive_sets(string[] arguments, int expected)
        {
            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithNamedAndEmptySets> >(() => new FakeOptionsWithNamedAndEmptySets()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            result.Errors.Should().HaveCount(x => x == expected);
        }
Exemplo n.º 8
0
        public void Specifying_options_two_or_more_times_generates_RepeatedOptionError(string[] arguments, int expected)
        {
            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptions> >(() => new FakeOptions()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            ((NotParsed <FakeOptions>)result).Errors.Should().HaveCount(x => x == expected);
        }
Exemplo n.º 9
0
        protected override CodeBase ParseLines(IEnumerable <SlocLineItem> lines)
        {
            var inclusionExtension   = Inclusion.GetDescription();
            var inclusionCodeBagType = MapToCodeBag(Inclusion);

            var classes = lines.Where(x => x.FileName.EndsWith(inclusionExtension))
                          .Select(each => InstanceBuilder.Build(
                                      new CodeBag(each.Directory, inclusionCodeBagType, each.Directory), each.FileName, each.PhysicalPath, each.SourceLoc))
                          .ToList();

            return(new CodeBase(new CodeGraph(classes)));
        }
Exemplo n.º 10
0
        public void Can_define_options_on_interface_properties(string[] arguments, string expected)
        {
            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeInterfaceOptions> >(() => new FakeInterfaceOptions()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(((Parsed <FakeInterfaceOptions>)result).Value.InputFile);
        }
Exemplo n.º 11
0
        public void Min_and_max_constraint_set_to_zero_throws_exception()
        {
            // Exercize system
            Action test = () => InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithMinMaxZero> >(() => new FakeOptionsWithMinMaxZero()),
                new string[] { },
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            Assert.Throws <ApplicationException>(test);
        }
 private static ParserResult <T> InvokeBuildEnumValuesCaseIgnore <T>(string[] arguments)
     where T : new()
 {
     return(InstanceBuilder.Build(
                Maybe.Just <Func <T> >(() => new T()),
                (args, optionSpecs) => Tokenizer.ConfigureTokenizer(StringComparer.Ordinal, false, false)(args, optionSpecs),
                arguments,
                StringComparer.Ordinal,
                true,
                CultureInfo.InvariantCulture,
                Enumerable.Empty <ErrorType>()));
 }
Exemplo n.º 13
0
        public void Min_and_max_constraint_set_to_zero_throws_exception()
        {
            // Exercize system
            Action test = () => InstanceBuilder.Build(
                Maybe.Just <Func <Options_With_Both_Min_And_Max_Set_To_Zero> >(() => new Options_With_Both_Min_And_Max_Set_To_Zero()),
                new string[] { },
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture,
                Enumerable.Empty <ErrorType>());

            // Verify outcome
            Assert.Throws <ApplicationException>(test);
        }
Exemplo n.º 14
0
 protected Instance this[string fileName]
 {
     get
     {
         var found = instances.SingleOrDefault(x => x.PhysicalPath == new Location(fileName));
         if (found != null)
         {
             return(found);
         }
         found = InstanceBuilder.Build(fileName);
         instances.Add(found);
         return(found);
     }
 }
Exemplo n.º 15
0
        public void Breaking_required_constraint_generate_MissingRequiredOptionError(string[] arguments, int expected)
        {
            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithTwoRequired> >(() => new FakeOptionsWithTwoRequired()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            var errors = ((NotParsed <FakeOptionsWithTwoRequired>)result).Errors;

            errors.OfType <MissingRequiredOptionError>().Should().HaveCount(x => x == expected);
        }
Exemplo n.º 16
0
        public void Breaking_required_constraint_generate_MissingRequiredOptionError(string[] arguments, int expected)
        {
            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <Options_With_Two_Options_Having_Required_Set_To_True> >(() => new Options_With_Two_Options_Having_Required_Set_To_True()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture,
                Enumerable.Empty <ErrorType>());

            // Verify outcome
            var errors = ((NotParsed <Options_With_Two_Options_Having_Required_Set_To_True>)result).Errors;

            errors.OfType <MissingRequiredOptionError>().Should().HaveCount(x => x == expected);
        }
Exemplo n.º 17
0
        public void Parse_int_sequence(string[] arguments, int[] expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithSequence> >(() => new FakeOptionsWithSequence()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            Assert.True(expected.SequenceEqual(((Parsed <FakeOptionsWithSequence>)result).Value.IntSequence));

            // Teardown
        }
Exemplo n.º 18
0
        public void Omitting_names_assumes_identifier_as_long_name(string[] arguments, string expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptions> >(() => new FakeOptions()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            Assert.True(expected.Equals(((Parsed <FakeOptions>)result).Value.StringValue));

            // Teardown
        }
Exemplo n.º 19
0
        public Instance Build(XElement typeElement)
        {
            var members = (from m in typeElement.Descendants("Members").Descendants("Member")
                           select fxCopMemberBuilder.Build(m)).ToList();
            var nspace       = typeElement.Parent.Parent.AttributeValue("Name");
            var metrics      = typeElement.Descendants("Metrics").Descendants("Metric");
            var physicalfile = GetPhysicaFileFrom(typeElement);
            var codeBag      = new CodeBag(nspace, CodeBagType.Namespace, Path.GetDirectoryName(physicalfile));

            return(InstanceBuilder.Build(codeBag, typeElement.AttributeValue("Name"), physicalfile,
                                         GetMetricValue(metrics, "LinesOfCode"),
                                         GetMetricValue(metrics, "CyclomaticComplexity"),
                                         GetMetricValue(metrics, "DepthOfInheritance"),
                                         GetMetricValue(metrics, "ClassCoupling"),
                                         members));
        }
Exemplo n.º 20
0
        public void Parse_to_immutable_instance(string[] arguments, FakeImmutableOptions expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Nothing <Func <FakeImmutableOptions> >(),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(((Parsed <FakeImmutableOptions>)result).Value);

            // Teardown
        }
Exemplo n.º 21
0
        public void Parse_string_sequence_with_separator(string[] arguments, string[] expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithSequenceAndSeparator> >(() => new FakeOptionsWithSequenceAndSeparator()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(((Parsed <FakeOptionsWithSequenceAndSeparator>)result).Value.StringSequence);

            // Teardown
        }
Exemplo n.º 22
0
        public void Parse_sequence_value_without_range_constraints(string[] arguments, long[] expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithSequenceWithoutRange> >(() => new FakeOptionsWithSequenceWithoutRange()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(result.Value.LongSequence);

            // Teardown
        }
Exemplo n.º 23
0
        public void Parse_string_sequence_with_only_max_constraint(string[] arguments, string[] expected)
        {
            // Fixture setup with attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithSequenceAndOnlyMaxConstraint> >(() => new FakeOptionsWithSequenceAndOnlyMaxConstraint()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            Assert.True(expected.SequenceEqual(((Parsed <FakeOptionsWithSequenceAndOnlyMaxConstraint>)result).Value.StringSequence));

            // Teardown
        }
Exemplo n.º 24
0
        public void Parse_double_value(string[] arguments, double expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithDouble> >(() => new FakeOptionsWithDouble()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            Assert.Equal(expected, ((Parsed <FakeOptionsWithDouble>)result).Value.DoubleValue);

            // Teardown
        }
Exemplo n.º 25
0
        public void Parse_utf8_string_correctly(string[] arguments, string expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptions> >(() => new FakeOptions()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(((Parsed <FakeOptions>)result).Value.StringValue);

            // Teardown
        }
Exemplo n.º 26
0
        public void Parse_nullable_long(string[] arguments, long?expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithNullables> >(() => new FakeOptionsWithNullables()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(((Parsed <FakeOptionsWithNullables>)result).Value.NullableLong);

            // Teardown
        }
Exemplo n.º 27
0
        [InlineData(new[] { "-9223372036854775807" }, -9223372036854775807)] // long.MaxValue * -1
        public void Parse_negative_long_value(string[] arguments, long expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptions> >(() => new FakeOptions()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            Assert.Equal(expected, result.Value.LongValue);

            // Teardown
        }
Exemplo n.º 28
0
        public void Parse_string_scalar_with_required_constraint_as_value(string[] arguments, FakeOptionsWithRequiredValue expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithRequiredValue> >(() => new FakeOptionsWithRequiredValue()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(((Parsed <FakeOptionsWithRequiredValue>)result).Value);

            // Teardown
        }
Exemplo n.º 29
0
        public void Parse_string_scalar_and_sequence_adjacent(string[] arguments, FakeOptionsWithScalarValueAndSequenceStringAdjacent expected)
        {
            // Fixture setup in attributes

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithScalarValueAndSequenceStringAdjacent> >(() => new FakeOptionsWithScalarValueAndSequenceStringAdjacent()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(((Parsed <FakeOptionsWithScalarValueAndSequenceStringAdjacent>)result).Value);

            // Teardown
        }
Exemplo n.º 30
0
        public void Parse_enum_value(string[] arguments, Colors expected)
        {
            // Fixture setup in attribute

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptionsWithEnum> >(() => new FakeOptionsWithEnum()),
                arguments,
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            expected.ShouldBeEquivalentTo(((Parsed <FakeOptionsWithEnum>)result).Value.Colors);

            // Teardown
        }