Ejemplo n.º 1
0
        public void AutoBuild_when_no_assembly_attributes()
        {
            try
            {
                string expectedCopyright = "Copyright (C) 1 author";

                ReflectionHelper.SetAttributeOverride(new Attribute[0]);

                ParserResult <Simple_Options> fakeResult = new NotParsed <Simple_Options>(
                    TypeInfo.Create(typeof(Simple_Options)), new Error[0]);
                bool     onErrorCalled = false;
                HelpText actualResult  = HelpText.AutoBuild(fakeResult, ht =>
                {
                    onErrorCalled = true;
                    return(ht);
                }, ex => ex, new ParserSettings());

                onErrorCalled.Should().BeTrue();
                actualResult.Copyright.Should().Be(expectedCopyright);
            }
            finally
            {
                ReflectionHelper.SetAttributeOverride(null);
            }
        }
Ejemplo n.º 2
0
        public void Options_should_be_separated_by_spaces()
        {
            // Fixture setup
            var handlers   = new CultureInfo("en-US").MakeCultureHandlers();
            var fakeResult =
                new NotParsed <Options_With_Default_Set_To_Sequence>(
                    typeof(Options_With_Default_Set_To_Sequence).ToTypeInfo(),
                    Enumerable.Empty <Error>()
                    );

            // Exercize system
            handlers.ChangeCulture();
            var helpText = HelpText.AutoBuild(fakeResult);

            handlers.ResetCulture();

            // Verify outcome
            var text  = helpText.ToString();
            var lines = text.ToLines().TrimStringArray();

            Console.WriteLine(text);
            lines[3].Should().Be("-z, --strseq    (Default: a b c)");
            lines[5].Should().Be("-y, --intseq    (Default: 1 2 3)");
            lines[7].Should().Be("-q, --dblseq    (Default: 1.1 2.2 3.3)");

            // Teardown
        }
Ejemplo n.º 3
0
        public void AutoBuild_with_assembly_title_and_version_attributes_only()
        {
            try
            {
                string expectedTitle   = "Title";
                string expectedVersion = "1.2.3.4";

                ReflectionHelper.SetAttributeOverride(new Attribute[]
                {
                    new AssemblyTitleAttribute(expectedTitle),
                    new AssemblyInformationalVersionAttribute(expectedVersion)
                });

                ParserResult <Simple_Options> fakeResult = new NotParsed <Simple_Options>(
                    TypeInfo.Create(typeof(Simple_Options)), new Error[0]);
                bool     onErrorCalled = false;
                HelpText actualResult  = HelpText.AutoBuild(fakeResult, ht =>
                {
                    onErrorCalled = true;
                    return(ht);
                }, ex => ex, new ParserSettings());

                onErrorCalled.Should().BeTrue();
                actualResult.Heading.Should().Be(string.Format("{0} {1}", expectedTitle, expectedVersion));
            }
            finally
            {
                ReflectionHelper.SetAttributeOverride(null);
            }
        }
Ejemplo n.º 4
0
        public void Invoke_AutoBuild_for_Options_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed <FakeOptions>(
                new FakeOptions(),
                new Error[]
            {
                new BadFormatTokenError("badtoken"),
                new SequenceOutOfRangeError(new NameInfo("i", ""))
            });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            Assert.True(lines[0].StartsWith("CommandLine", StringComparison.Ordinal));
            Assert.True(lines[1].StartsWith("Copyright (c)", StringComparison.Ordinal));
            Assert.Equal("ERROR(S):", lines[2]);
            Assert.Equal("Token 'badtoken' is not recognized.", lines[3]);
            Assert.Equal("A sequence option 'i' is defined with few items than required.", lines[4]);
            Assert.Equal("--stringvalue    Define a string value here.", lines[5]);
            Assert.Equal("-i               Define a int sequence here.", lines[6]);
            Assert.Equal("-x               Define a boolean or switch value here.", lines[7]);
            Assert.Equal("--help           Display this help screen.", lines[8]);
            // Teardown
        }
Ejemplo n.º 5
0
        public void AutoBuild_when_no_assembly_attributes()
        {
            try
            {
                string expectedCopyright = "Copyright (C) 1 author";

                ReflectionHelper.SetAttributeOverride(new Attribute[0]);

                ParserResult<Simple_Options> fakeResult = new NotParsed<Simple_Options>(
                    TypeInfo.Create(typeof (Simple_Options)), new Error[0]);
                bool onErrorCalled = false;
                HelpText actualResult = HelpText.AutoBuild(fakeResult, ht =>
                {
                    onErrorCalled = true;
                    return ht;
                }, ex => ex);

                onErrorCalled.Should().BeTrue();
                actualResult.Copyright.Should().Be(expectedCopyright);
            }
            finally
            {
                ReflectionHelper.SetAttributeOverride(null);
            }
        }
Ejemplo n.º 6
0
        public static void RenderUsageText_returns_properly_formatted_text()
        {
            // Fixture setup
            ParserResult<Options_With_Usage_Attribute> result =
                new NotParsed<Options_With_Usage_Attribute>(
                    TypeInfo.Create(typeof(Options_With_Usage_Attribute)), Enumerable.Empty<Error>());

            // Exercize system
            var text = HelpText.RenderUsageText(result);

            // Verify outcome
            var lines = text.ToNotEmptyLines();

            // Teardown
            lines[0].ShouldBeEquivalentTo("Normal scenario:");
            lines[1].ShouldBeEquivalentTo("  mono testapp.exe --input file.bin --output out.bin");
            lines[2].ShouldBeEquivalentTo("Logging warnings:");
            lines[3].ShouldBeEquivalentTo("  mono testapp.exe -w --input file.bin");
            lines[4].ShouldBeEquivalentTo("Logging errors:");
            lines[5].ShouldBeEquivalentTo("  mono testapp.exe -e --input file.bin");
            lines[6].ShouldBeEquivalentTo("  mono testapp.exe --errs --input=file.bin");
            lines[7].ShouldBeEquivalentTo("List:");
            lines[8].ShouldBeEquivalentTo("  mono testapp.exe -l 1,2");
            lines[9].ShouldBeEquivalentTo("Value:");
            lines[10].ShouldBeEquivalentTo("  mono testapp.exe value");
        }
Ejemplo n.º 7
0
        public static void RenderUsageText_returns_properly_formatted_text()
        {
            // Fixture setup
            ParserResult <Options_With_Usage_Attribute> result =
                new NotParsed <Options_With_Usage_Attribute>(
                    TypeInfo.Create(typeof(Options_With_Usage_Attribute)), Enumerable.Empty <Error>());

            // Exercize system
            var text = HelpText.RenderUsageText(result);

            // Verify outcome
            var lines = text.ToNotEmptyLines();

            // Teardown
            lines[0].Should().BeEquivalentTo("Normal scenario:");
            lines[1].Should().BeEquivalentTo("  mono testapp.exe --input file.bin --output out.bin");
            lines[2].Should().BeEquivalentTo("Logging warnings:");
            lines[3].Should().BeEquivalentTo("  mono testapp.exe -w --input file.bin");
            lines[4].Should().BeEquivalentTo("Logging errors:");
            lines[5].Should().BeEquivalentTo("  mono testapp.exe -e --input file.bin");
            lines[6].Should().BeEquivalentTo("  mono testapp.exe --errs --input=file.bin");
            lines[7].Should().BeEquivalentTo("List:");
            lines[8].Should().BeEquivalentTo("  mono testapp.exe -l 1,2");
            lines[9].Should().BeEquivalentTo("Value:");
            lines[10].Should().BeEquivalentTo("  mono testapp.exe value");
        }
Ejemplo n.º 8
0
        public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed <object>(
                TypeInfo.Create(typeof(NullInstance)),
                new Error[]
            {
                new HelpVerbRequestedError("commit", typeof(Commit_Verb), true)
            });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            lines[0].Should().Be(HeadingInfo.Default.ToString());
            lines[1].Should().Be(CopyrightInfo.Default.ToString());
            lines[2].Should().BeEquivalentTo("-p, --patch      Use the interactive patch selection interface to chose which");
            lines[3].Should().BeEquivalentTo("changes to commit.");
            lines[4].Should().BeEquivalentTo("--amend          Used to amend the tip of the current branch.");
            lines[5].Should().BeEquivalentTo("-m, --message    Use the given message as the commit message.");
            lines[6].Should().BeEquivalentTo("--help           Display this help screen.");
            // Teardown
        }
Ejemplo n.º 9
0
        public void AutoBuild_with_assembly_company_attribute_only()
        {
            try
            {
                string expectedCompany = "Company";

                ReflectionHelper.SetAttributeOverride(new Attribute[]
                {
                    new AssemblyCompanyAttribute(expectedCompany)
                });

                ParserResult <Simple_Options> fakeResult = new NotParsed <Simple_Options>(
                    TypeInfo.Create(typeof(Simple_Options)), new Error[0]);
                bool     onErrorCalled = false;
                HelpText actualResult  = HelpText.AutoBuild(fakeResult, ht =>
                {
                    onErrorCalled = true;
                    return(ht);
                }, ex => ex, new ParserSettings());

                onErrorCalled.Should().BeFalse(); // Other attributes have fallback logic
                actualResult.Copyright.Should().Be(string.Format("Copyright (C) {0} {1}", DateTime.Now.Year, expectedCompany));
            }
            finally
            {
                ReflectionHelper.SetAttributeOverride(null);
            }
        }
Ejemplo n.º 10
0
        public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_formatted_text_given_display_width_100()
        {
            // Fixture setup
            var fakeResult = new NotParsed <object>(
                TypeInfo.Create(typeof(NullInstance)),
                new Error[]
            {
                new HelpVerbRequestedError("commit", typeof(Commit_Verb), true)
            });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult, new ParserSettings(), maxDisplayWidth: 100);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

#if !PLATFORM_DOTNET
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].ShouldBeEquivalentTo("Copyright (c) 2005 - 2018 Giacomo Stelluti Scala & Contributors");
#else
            // Takes the name of the xUnit test program
            lines[0].Should().StartWithEquivalent("xUnit");
            lines[1].Should().StartWithEquivalent("Copyright (C) Outercurve Foundation");
#endif
            lines[2].ShouldBeEquivalentTo("-p, --patch      Use the interactive patch selection interface to chose which changes to commit.");
            lines[3].ShouldBeEquivalentTo("--amend          Used to amend the tip of the current branch.");
            lines[4].ShouldBeEquivalentTo("-m, --message    Use the given message as the commit message.");
            lines[5].ShouldBeEquivalentTo("--help           Display this help screen.");
            // Teardown
        }
Ejemplo n.º 11
0
        public void Default_set_to_sequence_should_be_properly_printed()
        {
            // Fixture setup
            var handlers   = new CultureInfo("en-US").MakeCultureHandlers();
            var fakeResult =
                new NotParsed <Options_With_Default_Set_To_Sequence>(
                    typeof(Options_With_Default_Set_To_Sequence).ToTypeInfo(),
                    new Error[] { new BadFormatTokenError("badtoken") });

            // Exercize system
            handlers.ChangeCulture();
            var helpText = HelpText.AutoBuild(fakeResult);

            handlers.ResetCulture();

            // Verify outcome
            var text  = helpText.ToString();
            var lines = text.ToNotEmptyLines().TrimStringArray();

            lines[4].Should().Be("-z, --strseq    (Default: a b c)");
            lines[5].Should().Be("-y, --intseq    (Default: 1 2 3)");
            lines[6].Should().Be("-q, --dblseq    (Default: 1.1 2.2 3.3)");

            // Teardown
        }
Ejemplo n.º 12
0
        public void Invoke_AutoBuild_for_Verbs_with_unknown_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var verbTypes = Enumerable.Empty <Type>().Concat(
                new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb) });
            var fakeResult = new NotParsed <object>(
                TypeInfo.Create(typeof(NullInstance),
                                verbTypes),
                new Error[] { new HelpVerbRequestedError(null, null, false) });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult, new ParserSettings());

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

#if !PLATFORM_DOTNET
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].Should().StartWithEquivalent("Copyright (c)");
#else
            // Takes the name of the xUnit test program
            lines[0].Should().StartWithEquivalent("xUnit");
            lines[1].Should().StartWithEquivalent("Copyright (C) Outercurve Foundation");
#endif
            lines[2].ShouldBeEquivalentTo("add        Add file contents to the index.");
            lines[3].ShouldBeEquivalentTo("commit     Record changes to the repository.");
            lines[4].ShouldBeEquivalentTo("clone      Clone a repository into a new directory.");
            lines[5].ShouldBeEquivalentTo("help       Display more information on a specific command.");
            lines[6].ShouldBeEquivalentTo("version    Display version information.");
            // Teardown
        }
Ejemplo n.º 13
0
        public void Invoke_AutoBuild_for_Verbs_with_unknown_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var verbTypes = Enumerable.Empty <Type>().Concat(
                new[] { typeof(Add_Verb), typeof(Commit_Verb), typeof(Clone_Verb) });
            var fakeResult = new NotParsed <object>(
                TypeInfo.Create(typeof(NullInstance),
                                verbTypes),
                new Error[] { new HelpVerbRequestedError(null, null, false) });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            lines[0].Should().Be(HeadingInfo.Default.ToString());
            lines[1].Should().Be(CopyrightInfo.Default.ToString());
            lines[2].Should().BeEquivalentTo("add        Add file contents to the index.");
            lines[3].Should().BeEquivalentTo("commit     Record changes to the repository.");
            lines[4].Should().BeEquivalentTo("clone      Clone a repository into a new directory.");
            lines[5].Should().BeEquivalentTo("help       Display more information on a specific command.");
            lines[6].Should().BeEquivalentTo("version    Display version information.");
            // Teardown
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class,
        /// automatically handling verbs or options scenario.
        /// </summary>
        /// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
        /// <returns>
        /// An instance of <see cref="CommandLine.Text.HelpText"/> class.
        /// </returns>
        /// <remarks>This feature is meant to be invoked automatically by the parser, setting the HelpWriter property
        /// of <see cref="CommandLine.ParserSettings"/>.</remarks>
        public static HelpText AutoBuild <T>(ParserResult <T> parserResult)
        {
            if (parserResult.Tag != ParserResultType.NotParsed)
            {
                throw new ArgumentException("Excepting NotParsed<T> type.", "parserResult");
            }

            var errors = ((NotParsed <T>)parserResult).Errors;

            if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
            {
                return(new HelpText(HeadingInfo.Default).AddPreOptionsLine(Environment.NewLine));
            }

            if (!errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
            {
                return(AutoBuild(parserResult, current => DefaultParsingErrorsHandler(parserResult, current)));
            }

            var err = errors.OfType <HelpVerbRequestedError>().Single();
            var pr  = new NotParsed <object>(TypeInfo.Create(err.Type), Enumerable.Empty <Error>());

            return(err.Matched
                ? AutoBuild(pr, current => DefaultParsingErrorsHandler(pr, current))
                : AutoBuild(parserResult, current => DefaultParsingErrorsHandler(parserResult, current), true));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class,
        /// automatically handling verbs or options scenario.
        /// </summary>
        /// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
        /// <returns>
        /// An instance of <see cref="CommandLine.Text.HelpText"/> class.
        /// </returns>
        /// <remarks>This feature is meant to be invoked automatically by the parser, setting the HelpWriter property
        /// of <see cref="CommandLine.ParserSettings"/>.</remarks>
        public static HelpText AutoBuild <T>(ParserResult <T> parserResult)
        {
            if (parserResult.Tag != ParserResultType.NotParsed)
            {
                throw new InvalidOperationException();
            }

            var errors      = ((NotParsed <T>)parserResult).Errors;
            var helpVerbErr = errors.OfType <HelpVerbRequestedError>();

            if (!helpVerbErr.Any())
            {
                return(AutoBuild(parserResult, current => DefaultParsingErrorsHandler(parserResult, current)));
            }

            var err = helpVerbErr.Single();

            if (err.Matched)
            {
                var pr = new NotParsed <object>(err.Type.AutoDefault(), Enumerable.Empty <Error>());
                return(AutoBuild(pr, current => DefaultParsingErrorsHandler(pr, current)));
            }

            return(AutoBuild(parserResult, current => DefaultParsingErrorsHandler(parserResult, current), true));
        }
Ejemplo n.º 16
0
        private void PrintHelp(NotParsed <object> result)
        {
            PerformanceTesting.Checkpoint("Begin Help");
            var verb = GetVerb(result.TypeInfo.Current);

            HelpPrinter.PrintHelp(verb, result);
        }
Ejemplo n.º 17
0
        public void Invoke_AutoBuild_for_Options_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed <Simple_Options>(
                TypeInfo.Create(typeof(Simple_Options)),
                new Error[]
            {
                new BadFormatTokenError("badtoken"),
                new SequenceOutOfRangeError(new NameInfo("i", ""))
            });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            lines[0].Should().Be(HeadingInfo.Default.ToString());
            lines[1].Should().Be(CopyrightInfo.Default.ToString());
            lines[2].Should().BeEquivalentTo("ERROR(S):");
            lines[3].Should().BeEquivalentTo("Token 'badtoken' is not recognized.");
            lines[4].Should().BeEquivalentTo("A sequence option 'i' is defined with fewer or more items than required.");
            lines[5].Should().BeEquivalentTo("--stringvalue         Define a string value here.");
            lines[6].Should().BeEquivalentTo("-s, --shortandlong    Example with both short and long name.");
            lines[7].Should().BeEquivalentTo("-i                    Define a int sequence here.");
            lines[8].Should().BeEquivalentTo("-x                    Define a boolean or switch value here.");
            lines[9].Should().BeEquivalentTo("--help                Display this help screen.");
            // Teardown
        }
Ejemplo n.º 18
0
        public void Invoke_AutoBuild_for_Options_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed <Simple_Options>(
                TypeInfo.Create(typeof(Simple_Options)),
                new Error[]
            {
                new BadFormatTokenError("badtoken"),
                new SequenceOutOfRangeError(new NameInfo("i", ""))
            });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult, new ParserSettings());

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

#if !PLATFORM_DOTNET
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].Should().StartWithEquivalent("Copyright (c)");
#else
            // Takes the name of the xUnit test program
            lines[0].Should().StartWithEquivalent("xUnit");
            lines[1].Should().StartWithEquivalent("Copyright (C) Outercurve Foundation");
#endif
            lines[2].ShouldBeEquivalentTo("ERROR(S):");
            lines[3].ShouldBeEquivalentTo("Token 'badtoken' is not recognized.");
            lines[4].ShouldBeEquivalentTo("A sequence option 'i' is defined with fewer or more items than required.");
            lines[5].ShouldBeEquivalentTo("--stringvalue         Define a string value here.");
            lines[6].ShouldBeEquivalentTo("-s, --shortandlong    Example with both short and long name.");
            lines[7].ShouldBeEquivalentTo("-i                    Define a int sequence here.");
            lines[8].ShouldBeEquivalentTo("-x                    Define a boolean or switch value here.");
            lines[9].ShouldBeEquivalentTo("--help                Display this help screen.");
            // Teardown
        }
Ejemplo n.º 19
0
        public static void PrintHelp(IVerb verb, NotParsed <object> result)
        {
            if (verb?.Usage != null)
            {
                Output.Fancy.Write($"\nUSAGE: ", Color.Info);
                Output.Fancy.WriteLine($"{verb.GetVerbName()} {verb.Usage}");
            }

            var errors = RenderErrors(result);

            if (!string.IsNullOrWhiteSpace(errors))
            {
                Output.Fancy.WriteLine("\nERRORS:", Color.Danger);
                Output.Fancy.WriteLine(errors);
            }

            if (verb == null)
            {
                Output.Fancy.WriteLine("\nVERBS:", Color.Info);
                Output.Fancy.WriteLine(GenerateVerbHelp(result));
            }
            else
            {
                Output.Fancy.WriteLine("\nOPTIONS:", Color.Info);
                Output.Fancy.WriteLine(GenerateOptionsHelp(result));
            }
        }
Ejemplo n.º 20
0
        private static string GenerateOptionsHelp(NotParsed <object> result)
        {
            var text = RenderHelpText(b =>
            {
                b.AddDashesToOption = true;
                b.AddOptions(result);
            });

            return(Regex.Replace(text, @"\(pos\. \d*\)", t => new string(' ', t.Value.Length)));
        }
Ejemplo n.º 21
0
        public void AutoBuild_when_no_assembly_attributes()
        {
            string expectedCopyright = $"Copyright (C) {DateTime.Now.Year} author";

            ReflectionHelper.SetAttributeOverride(new Attribute[0]);

            ParserResult <Simple_Options> fakeResult = new NotParsed <Simple_Options>(
                TypeInfo.Create(typeof(Simple_Options)), new Error[0]);
            HelpText actualResult = HelpText.AutoBuild(fakeResult, ht => ht, ex => ex);

            actualResult.Copyright.Should().Be(expectedCopyright);
        }
Ejemplo n.º 22
0
        public void Invoke_AutoBuild_for_Options_with_Usage_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed <Options_With_Usage_Attribute>(
                TypeInfo.Create(typeof(Options_With_Usage_Attribute)),
                new Error[]
            {
                new BadFormatTokenError("badtoken")
            });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult, new ParserSettings());

            // Verify outcome
            var text  = helpText.ToString();
            var lines = text.ToNotEmptyLines().TrimStringArray();

#if !PLATFORM_DOTNET
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].Should().StartWithEquivalent("Copyright (c)");
#else
            // Takes the name of the xUnit test program
            lines[0].Should().StartWithEquivalent("xUnit");
            lines[1].Should().StartWithEquivalent("Copyright (C) Outercurve Foundation");
#endif
            lines[2].ShouldBeEquivalentTo("ERROR(S):");
            lines[3].ShouldBeEquivalentTo("Token 'badtoken' is not recognized.");
            lines[4].ShouldBeEquivalentTo("USAGE:");
            lines[5].ShouldBeEquivalentTo("Normal scenario:");
            lines[6].ShouldBeEquivalentTo("mono testapp.exe --input file.bin --output out.bin");
            lines[7].ShouldBeEquivalentTo("Logging warnings:");
            lines[8].ShouldBeEquivalentTo("mono testapp.exe -w --input file.bin");
            lines[9].ShouldBeEquivalentTo("Logging errors:");
            lines[10].ShouldBeEquivalentTo("mono testapp.exe -e --input file.bin");
            lines[11].ShouldBeEquivalentTo("mono testapp.exe --errs --input=file.bin");
            lines[12].ShouldBeEquivalentTo("List:");
            lines[13].ShouldBeEquivalentTo("mono testapp.exe -l 1,2");
            lines[14].ShouldBeEquivalentTo("Value:");
            lines[15].ShouldBeEquivalentTo("mono testapp.exe value");
            lines[16].ShouldBeEquivalentTo("-i, --input     Set input file.");
            lines[17].ShouldBeEquivalentTo("-i, --output    Set output file.");
            lines[18].ShouldBeEquivalentTo("--verbose       Set verbosity level.");
            lines[19].ShouldBeEquivalentTo("-w, --warns     Log warnings.");
            lines[20].ShouldBeEquivalentTo("-e, --errs      Log errors.");
            lines[21].ShouldBeEquivalentTo("-l              List.");
            lines[22].ShouldBeEquivalentTo("--help          Display this help screen.");
            lines[23].ShouldBeEquivalentTo("--version       Display version information.");
            lines[24].ShouldBeEquivalentTo("value pos. 0    Value.");

            // Teardown
        }
        public static int FindFirstUknownArg <T>(string[] args)
        {
            Parser parser = new Parser((parserSettings) =>
            {
                parserSettings.HelpWriter = null;
            });

            ParserResult <T> parserResult = parser.ParseArguments <T>(args);

            if (parserResult.Tag == ParserResultType.NotParsed)
            {
                List <int> unknownArgsIndexes = new List <int>();

                NotParsed <T> info = parserResult as NotParsed <T>;
                foreach (var error in info.Errors)
                {
                    if (error.Tag == ErrorType.UnknownOptionError)
                    {
                        UnknownOptionError unknownOptionError = error as UnknownOptionError;
                        int uknownArgIndex = Array.FindIndex(args, (arg) =>
                        {
                            if (unknownOptionError.Token.Length == 1)
                            {
                                return(arg.StartsWith("-" + unknownOptionError.Token));
                            }
                            else
                            {
                                return(arg.Equals("--" + unknownOptionError.Token));
                            }
                        });
                        unknownArgsIndexes.Add(uknownArgIndex);
                    }
                }

                if (unknownArgsIndexes.Count == 0)
                {
                    return(-1);
                }
                int min = int.MaxValue;
                foreach (int index in unknownArgsIndexes)
                {
                    if (index < min)
                    {
                        min = index;
                    }
                }
                return(min);
            }
            return(-1);
        }
Ejemplo n.º 24
0
        public void Explicit_help_request_generates_help_requested_error()
        {
            // Fixture setup
            var expectedResult = new NotParsed <Simple_Options>(
                TypeInfo.Create(typeof(Simple_Options)), new Error[] { new HelpRequestedError() });

            // Exercize system
            var result = InvokeBuild <Simple_Options>(
                new[] { "--help" });

            // Verify outcome
            result.Should().BeEquivalentTo(expectedResult);

            // Teardown
        }
Ejemplo n.º 25
0
        public void AutoBuild_with_assembly_title_and_version_attributes_only()
        {
            string expectedTitle   = "Title";
            string expectedVersion = "1.2.3.4";

            ReflectionHelper.SetAttributeOverride(new Attribute[]
            {
                new AssemblyTitleAttribute(expectedTitle),
                new AssemblyInformationalVersionAttribute(expectedVersion)
            });

            ParserResult <Simple_Options> fakeResult = new NotParsed <Simple_Options>(
                TypeInfo.Create(typeof(Simple_Options)), new Error[0]);
            HelpText actualResult = HelpText.AutoBuild(fakeResult, ht => ht, ex => ex);

            actualResult.Heading.Should().Be(string.Format("{0} {1}", expectedTitle, expectedVersion));
        }
Ejemplo n.º 26
0
        private static int Main(string[] args)
        {
            using var parser = new Parser(settings =>
            {
                settings.HelpWriter             = null;
                settings.IgnoreUnknownArguments = false;
                settings.AllowMultiInstance     = true;
            });

            var result = parser.ParseArguments <Options>(args);

            return(result switch
            {
                Parsed <Options> parsed => Run(parsed.Value),
                NotParsed <Options> notParsed => HandleError(notParsed),
                _ => 1
            });
Ejemplo n.º 27
0
        public void AutoBuild_with_errors_and_preoptions_renders_correctly(bool startWithNewline, bool newlineBetweenSections)
        {
            // Fixture setup
            var fakeResult = new NotParsed <Simple_Options_Without_HelpText>(
                TypeInfo.Create(typeof(Simple_Options_Without_HelpText)),
                new Error[]
            {
                new BadFormatTokenError("badtoken")
            });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult,
                                              h =>
            {
                h.AddNewLineBetweenHelpSections = newlineBetweenSections;
                h.AddPreOptionsLine((startWithNewline ? Environment.NewLine : null) + "pre-options");
                return(HelpText.DefaultParsingErrorsHandler(fakeResult, h));
            },
                                              e => e
                                              );

            // Verify outcome
            var expected = new List <string>()
            {
                HeadingInfo.Default.ToString(),
                CopyrightInfo.Default.ToString(),
                "pre-options",
                "",
                "ERROR(S):",
                "Token 'badtoken' is not recognized.",
                "",
                "-v, --verbose",
                "",
                "--input-file"
            };

            if (newlineBetweenSections || startWithNewline)
            {
                expected.Insert(2, "");
            }

            var text  = helpText.ToString();
            var lines = text.ToLines().TrimStringArray();

            lines.Should().StartWith(expected);
        }
Ejemplo n.º 28
0
        public void Explicit_help_request_generates_help_requested_error()
        {
            // Fixture setup
            var fakeOptions    = new FakeOptions();
            var expectedResult = new NotParsed <FakeOptions>(
                TypeInfo.Create(typeof(FakeOptions)), new Error[] { new HelpRequestedError() });

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just <Func <FakeOptions> >(() => fakeOptions),
                new[] { "--help" },
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            Assert.True(expectedResult.Equals(result));

            // Teardown
        }
Ejemplo n.º 29
0
        public void AutoBuild_with_custom_help_and_version_request()
        {
            string expectedTitle   = "Title";
            string expectedVersion = "1.2.3.4";

            ReflectionHelper.SetAttributeOverride(new Attribute[]
            {
                new AssemblyTitleAttribute(expectedTitle),
                new AssemblyInformationalVersionAttribute(expectedVersion)
            });

            ParserResult <Simple_Options> fakeResult = new NotParsed <Simple_Options>(
                TypeInfo.Create(typeof(Simple_Options)),
                new Error[] { new VersionRequestedError() });

            HelpText helpText = HelpText.AutoBuild(fakeResult, ht => ht);

            helpText.ToString().Trim().Should().Be($"{expectedTitle} {expectedVersion}");
        }
Ejemplo n.º 30
0
        public void AutoBuild_with_custom_copyright_using_onError_action()
        {
            string expectedCopyright = "Copyright (c) 2019 Global.com";
            var    expectedHeading   = "MyApp 2.0.0-beta";
            ParserResult <Simple_Options> fakeResult = new NotParsed <Simple_Options>(
                TypeInfo.Create(typeof(Simple_Options)),
                new Error[] { new HelpRequestedError() });
            bool     onErrorCalled = false;
            HelpText actualResult  = HelpText.AutoBuild(fakeResult, ht =>
            {
                ht.AdditionalNewLineAfterOption = false;
                ht.Heading   = "MyApp 2.0.0-beta";
                ht.Copyright = "Copyright (c) 2019 Global.com";
                return(ht);
            });

            actualResult.Copyright.Should().Be(expectedCopyright);
            actualResult.Heading.Should().Be(expectedHeading);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class,
        /// automatically handling verbs or options scenario.
        /// </summary>
        /// <param name='parserResult'>The <see cref="CommandLine.ParserResult{T}"/> containing the instance that collected command line arguments parsed with <see cref="CommandLine.Parser"/> class.</param>
        /// <param name="maxDisplayWidth">The maximum width of the display.</param>
        /// <returns>
        /// An instance of <see cref="CommandLine.Text.HelpText"/> class.
        /// </returns>
        /// <remarks>This feature is meant to be invoked automatically by the parser, setting the HelpWriter property
        /// of <see cref="CommandLine.ParserSettings"/>.</remarks>
        public static HelpText AutoBuild<T>(ParserResult<T> parserResult, int maxDisplayWidth = DefaultMaximumLength)
        {
            if (parserResult.Tag != ParserResultType.NotParsed)
                throw new ArgumentException("Excepting NotParsed<T> type.", "parserResult");

            var errors = ((NotParsed<T>)parserResult).Errors;

            if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
                return new HelpText(HeadingInfo.Default){MaximumDisplayWidth = maxDisplayWidth }.AddPreOptionsLine(Environment.NewLine);

            if (!errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
                return AutoBuild(parserResult, current => DefaultParsingErrorsHandler(parserResult, current), e => e, maxDisplayWidth: maxDisplayWidth);

            var err = errors.OfType<HelpVerbRequestedError>().Single();
            var pr = new NotParsed<object>(TypeInfo.Create(err.Type), Enumerable.Empty<Error>());
            return err.Matched
                ? AutoBuild(pr, current => DefaultParsingErrorsHandler(pr, current), e => e, maxDisplayWidth: maxDisplayWidth)
                : AutoBuild(parserResult, current => DefaultParsingErrorsHandler(parserResult, current), e => e, true, maxDisplayWidth);
        }
Ejemplo n.º 32
0
        static async Task <int> MainAsync(string[] args)
        {
            DetectEnvironment();

            // Cert verification is not yet fully functional when using Windows OS for the container
            bool bypassCertVerification = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

            if (!bypassCertVerification && IsIotEdgeModule)
            {
                InstallCert();
            }

            var result = CommandLine.Parser.Default.ParseArguments <Options>(args);
            Parsed <Options> parsed = result as Parsed <Options>;

            if (parsed != null)
            {
                Options options          = parsed.Value;
                string  connectionString = GetHubConnectionString();
                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new InvalidOperationException("No IoT Hub connection string configured");
                }
                deviceClient = await Init(connectionString, options, bypassCertVerification);

                var cts = new CancellationTokenSource();
                void OnUnload(AssemblyLoadContext ctx) => CancelProgram(cts);

                AssemblyLoadContext.Default.Unloading += OnUnload;
                Console.CancelKeyPress += (sender, cpe) => { CancelProgram(cts); };

                ConsumeKafkaMessages(deviceClient, options, cts);

                return(0);
            }
            else
            {
                NotParsed <Options> notparsed = result as NotParsed <Options>;
                //notparsed.Errors;
                return(-1);
            }
        }
Ejemplo n.º 33
0
        public void Invoking_RenderParsingErrorsText_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed<object>(
                TypeInfo.Create(typeof(NullInstance)),
                new Error[]
                    {
                        new BadFormatTokenError("badtoken"),
                        new MissingValueOptionError(new NameInfo("x", "switch")),
                        new UnknownOptionError("unknown"),
                        new MissingRequiredOptionError(new NameInfo("", "missing")),
                        new SequenceOutOfRangeError(new NameInfo("s", "sequence")),
                        new NoVerbSelectedError(),
                        new BadVerbSelectedError("badverb"),
                        new HelpRequestedError(), // should be ignored
                        new HelpVerbRequestedError(null, null, false) // should be ignored
                    });
            Func<Error, string> fakeRenderer = err =>
                {
                    switch (err.Tag)
                    {
                        case ErrorType.BadFormatTokenError:
                            return "ERR " + ((BadFormatTokenError)err).Token;
                        case ErrorType.MissingValueOptionError:
                            return "ERR " + ((MissingValueOptionError)err).NameInfo.NameText;
                        case ErrorType.UnknownOptionError:
                            return "ERR " + ((UnknownOptionError)err).Token;
                        case ErrorType.MissingRequiredOptionError:
                            return "ERR " + ((MissingRequiredOptionError)err).NameInfo.NameText;
                        case ErrorType.SequenceOutOfRangeError:
                            return "ERR " + ((SequenceOutOfRangeError)err).NameInfo.NameText;
                        case ErrorType.NoVerbSelectedError:
                            return "ERR no-verb-selected";
                        case ErrorType.BadVerbSelectedError:
                            return "ERR " + ((BadVerbSelectedError)err).Token;
                        default:
                            throw new InvalidOperationException();
                    }
                };
            Func<IEnumerable<MutuallyExclusiveSetError>, string> fakeMutExclRenderer =
                _ => string.Empty;

            // Exercize system
            var errorsText = HelpText.RenderParsingErrorsText(fakeResult, fakeRenderer, fakeMutExclRenderer, 2);

            // Verify outcome
            var lines = errorsText.ToNotEmptyLines();

            lines[0].ShouldBeEquivalentTo("  ERR badtoken");
            lines[1].ShouldBeEquivalentTo("  ERR x, switch");
            lines[2].ShouldBeEquivalentTo("  ERR unknown");
            lines[3].ShouldBeEquivalentTo("  ERR missing");
            lines[4].ShouldBeEquivalentTo("  ERR s, sequence");
            lines[5].ShouldBeEquivalentTo("  ERR no-verb-selected");
            lines[6].ShouldBeEquivalentTo("  ERR badverb");
            // Teardown
        }
Ejemplo n.º 34
0
        public void Invoke_AutoBuild_for_Verbs_with_unknown_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var verbTypes = Enumerable.Empty<Type>().Concat(
                new[] { typeof(AddOptions), typeof(CommitOptions), typeof(CloneOptions) });
            var fakeResult = new NotParsed<object>(
                TypeInfo.Create(typeof(NullInstance),
                    verbTypes),
                new Error[] { new HelpVerbRequestedError(null, null, false) });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].Should().StartWithEquivalent("Copyright (c)");
            lines[2].ShouldBeEquivalentTo("add        Add file contents to the index.");
            lines[3].ShouldBeEquivalentTo("commit     Record changes to the repository.");
            lines[4].ShouldBeEquivalentTo("clone      Clone a repository into a new directory.");
            lines[5].ShouldBeEquivalentTo("help       Display more information on a specific command.");
            lines[6].ShouldBeEquivalentTo("version    Display version information.");
            // Teardown
        }
Ejemplo n.º 35
0
        public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed<object>(
                TypeInfo.Create(typeof(NullInstance)),
                new Error[]
                    {
                        new HelpVerbRequestedError("commit", typeof(CommitOptions), true)
                    });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].Should().StartWithEquivalent("Copyright (c)");
            lines[2].ShouldBeEquivalentTo("-p, --patch    Use the interactive patch selection interface to chose which");
            lines[3].ShouldBeEquivalentTo("changes to commit.");
            lines[4].ShouldBeEquivalentTo("--amend        Used to amend the tip of the current branch.");
            lines[5].ShouldBeEquivalentTo("--help         Display this help screen.");
            // Teardown
        }
Ejemplo n.º 36
0
        public void Invoke_AutoBuild_for_Options_with_Usage_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed<FakeOptionsWithUsageText>(
                TypeInfo.Create(typeof(FakeOptionsWithUsageText)),
                new Error[]
                    {
                        new BadFormatTokenError("badtoken")
                    });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var text = helpText.ToString();
            var lines = text.ToNotEmptyLines().TrimStringArray();
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].Should().StartWithEquivalent("Copyright (c)");
            lines[2].ShouldBeEquivalentTo("ERROR(S):");
            lines[3].ShouldBeEquivalentTo("Token 'badtoken' is not recognized.");
            lines[4].ShouldBeEquivalentTo("USAGE:");
            lines[5].ShouldBeEquivalentTo("Normal scenario:");
            lines[6].ShouldBeEquivalentTo("mono testapp.exe --input file.bin --output out.bin");
            lines[7].ShouldBeEquivalentTo("Logging warnings:");
            lines[8].ShouldBeEquivalentTo("mono testapp.exe -w --input file.bin");
            lines[9].ShouldBeEquivalentTo("Logging errors:");
            lines[10].ShouldBeEquivalentTo("mono testapp.exe -e --input file.bin");
            lines[11].ShouldBeEquivalentTo("mono testapp.exe --errs --input=file.bin");
            lines[12].ShouldBeEquivalentTo("-i, --input     Set input file.");
            lines[13].ShouldBeEquivalentTo("-i, --output    Set output file.");
            lines[14].ShouldBeEquivalentTo("--verbose       Set verbosity level.");
            lines[15].ShouldBeEquivalentTo("-w, --warns     Log warnings.");
            lines[16].ShouldBeEquivalentTo("-e, --errs      Log errors.");
            lines[17].ShouldBeEquivalentTo("--help          Display this help screen.");
            lines[18].ShouldBeEquivalentTo("--version       Display version information.");

            // Teardown
        }
Ejemplo n.º 37
0
        public void Invoke_AutoBuild_for_Options_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed<FakeOptions>(
                TypeInfo.Create(typeof(FakeOptions)),
                new Error[]
                    {
                        new BadFormatTokenError("badtoken"),
                        new SequenceOutOfRangeError(new NameInfo("i", ""))
                    });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].Should().StartWithEquivalent("Copyright (c)");
            lines[2].ShouldBeEquivalentTo("ERROR(S):");
            lines[3].ShouldBeEquivalentTo("Token 'badtoken' is not recognized.");
            lines[4].ShouldBeEquivalentTo("A sequence option 'i' is defined with fewer or more items than required.");
            lines[5].ShouldBeEquivalentTo("--stringvalue    Define a string value here.");
            lines[6].ShouldBeEquivalentTo("-i               Define a int sequence here.");
            lines[7].ShouldBeEquivalentTo("-x               Define a boolean or switch value here.");
            lines[8].ShouldBeEquivalentTo("--help           Display this help screen.");
            // Teardown
        }
Ejemplo n.º 38
0
        public void Explicit_help_request_generates_help_requested_error()
        {
            // Fixture setup
            var fakeOptions = new FakeOptions();
            var expectedResult = new NotParsed<FakeOptions>(
                TypeInfo.Create(typeof(FakeOptions)), new Error[] { new HelpRequestedError() });

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just<Func<FakeOptions>>(() => fakeOptions),
                new[] { "--help" },
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture);

            // Verify outcome
            Assert.True(expectedResult.Equals(result));

            // Teardown
        }
Ejemplo n.º 39
0
        public void Invoke_AutoBuild_for_Verbs_with_unknown_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var verbTypes = Enumerable.Empty<Type>().Concat(
                new[] { typeof(AddOptions), typeof(CommitOptions), typeof(CloneOptions) });
            var fakeResult = new NotParsed<object>(
                new NullInstance(),
                verbTypes,
                new Error[] { new HelpVerbRequestedError(null, null, false) });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            Assert.True(lines[0].StartsWith("CommandLine", StringComparison.Ordinal));
            Assert.True(lines[1].StartsWith("Copyright (c)", StringComparison.Ordinal));
            Assert.Equal("add       Add file contents to the index.", lines[2]);
            Assert.Equal("commit    Record changes to the repository.", lines[3]);
            Assert.Equal("clone     Clone a repository into a new directory.", lines[4]);
            Assert.Equal("help      Display more information on a specific command.", lines[5]);
            // Teardown
        }
Ejemplo n.º 40
0
        public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed<object>(
                new NullInstance(),
                new Error[]
                    {
                        new HelpVerbRequestedError("commit", typeof(CommitOptions), true)
                    });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            Assert.True(lines[0].StartsWith("CommandLine", StringComparison.Ordinal));
            Assert.True(lines[1].StartsWith("Copyright (c)", StringComparison.Ordinal));
            Assert.Equal("-p, --patch    Use the interactive patch selection interface to chose which", lines[2]);
            Assert.Equal("changes to commit.", lines[3]);
            Assert.Equal("--amend        Used to amend the tip of the current branch.", lines[4]);
            Assert.Equal("--help         Display this help screen.", lines[5]);
            // Teardown
        }
Ejemplo n.º 41
0
        public void Explicit_help_request_generates_help_requested_error()
        {
            // Fixture setup
            var fakeOptions = new Simple_Options();
            var expectedResult = new NotParsed<Simple_Options>(
                TypeInfo.Create(typeof(Simple_Options)), new Error[] { new HelpRequestedError() });

            // Exercize system
            var result = InstanceBuilder.Build(
                Maybe.Just<Func<Simple_Options>>(() => fakeOptions),
                new[] { "--help" },
                StringComparer.Ordinal,
                CultureInfo.InvariantCulture,
                Enumerable.Empty<ErrorType>());

            // Verify outcome
            result.ShouldBeEquivalentTo(expectedResult);

            // Teardown
        }
Ejemplo n.º 42
0
        public void Invoke_AutoBuild_for_Verbs_with_specific_verb_returns_appropriate_formatted_text_given_display_width_100()
        {
            // Fixture setup
            var fakeResult = new NotParsed<object>(
                TypeInfo.Create(typeof(NullInstance)),
                new Error[]
                    {
                        new HelpVerbRequestedError("commit", typeof(Commit_Verb), true)
                    });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult, maxDisplayWidth: 100);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            #if !PLATFORM_DOTNET
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].ShouldBeEquivalentTo("Copyright (c) 2005 - 2015 Giacomo Stelluti Scala");
            #else
            // Takes the name of the xUnit test program
            lines[0].Should().StartWithEquivalent("xUnit");
            lines[1].Should().StartWithEquivalent("Copyright (C) Outercurve Foundation");
            #endif
            lines[2].ShouldBeEquivalentTo("-p, --patch      Use the interactive patch selection interface to chose which changes to commit.");
            lines[3].ShouldBeEquivalentTo("--amend          Used to amend the tip of the current branch.");
            lines[4].ShouldBeEquivalentTo("-m, --message    Use the given message as the commit message.");
            lines[5].ShouldBeEquivalentTo("--help           Display this help screen.");
            // Teardown
        }
Ejemplo n.º 43
0
        public void Default_set_to_sequence_should_be_properly_printed()
        {
            // Fixture setup
            var handlers = new CultureInfo("en-US").MakeCultureHandlers();
            var fakeResult =
                new NotParsed<Options_With_Default_Set_To_Sequence>(
                    typeof(Options_With_Default_Set_To_Sequence).ToTypeInfo(),
                    new Error[] { new BadFormatTokenError("badtoken") });

            // Exercize system
            handlers.ChangeCulture();
            var helpText = HelpText.AutoBuild(fakeResult);
            handlers.ResetCulture();

            // Verify outcome
            var text = helpText.ToString();
            var lines = text.ToNotEmptyLines().TrimStringArray();

            lines[4].Should().Be("-z, --strseq    (Default: a b c)");
            lines[5].Should().Be("-y, --intseq    (Default: 1 2 3)");
            lines[6].Should().Be("-q, --dblseq    (Default: 1.1 2.2 3.3)");

            // Teardown
        }
Ejemplo n.º 44
0
        public void Invoke_AutoBuild_for_Options_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed<FakeOptions>(
                new FakeOptions(),
                new Error[]
                    {
                        new BadFormatTokenError("badtoken"),
                        new SequenceOutOfRangeError(new NameInfo("i", ""))
                    });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var lines = helpText.ToString().ToNotEmptyLines().TrimStringArray();

            Assert.True(lines[0].StartsWith("CommandLine", StringComparison.Ordinal));
            Assert.True(lines[1].StartsWith("Copyright (c)", StringComparison.Ordinal));
            Assert.Equal("ERROR(S):", lines[2]);
            Assert.Equal("Token 'badtoken' is not recognized.", lines[3]);
            Assert.Equal("A sequence option 'i' is defined with few items than required.", lines[4]);
            Assert.Equal("--stringvalue    Define a string value here.", lines[5]);
            Assert.Equal("-i               Define a int sequence here.", lines[6]);
            Assert.Equal("-x               Define a boolean or switch value here.", lines[7]);
            Assert.Equal("--help           Display this help screen.", lines[8]);
            // Teardown
        }
Ejemplo n.º 45
0
        public void AutoBuild_with_assembly_company_attribute_only()
        {
            try
            {
                string expectedCompany = "Company";

                ReflectionHelper.SetAttributeOverride(new Attribute[]
                {
                    new AssemblyCompanyAttribute(expectedCompany)
                });

                ParserResult<Simple_Options> fakeResult = new NotParsed<Simple_Options>(
                    TypeInfo.Create(typeof (Simple_Options)), new Error[0]);
                bool onErrorCalled = false;
                HelpText actualResult = HelpText.AutoBuild(fakeResult, ht =>
                {
                    onErrorCalled = true;
                    return ht;
                }, ex => ex);

                onErrorCalled.Should().BeFalse(); // Other attributes have fallback logic
                actualResult.Copyright.Should().Be(string.Format("Copyright (C) {0} {1}", DateTime.Now.Year, expectedCompany));
            }
            finally
            {
                ReflectionHelper.SetAttributeOverride(null);
            }
        }
Ejemplo n.º 46
0
        public void AutoBuild_with_assembly_title_and_version_attributes_only()
        {
            try
            {
                string expectedTitle = "Title";
                string expectedVersion = "1.2.3.4";

                ReflectionHelper.SetAttributeOverride(new Attribute[]
                {
                    new AssemblyTitleAttribute(expectedTitle),
                    new AssemblyInformationalVersionAttribute(expectedVersion)
                });

                ParserResult<Simple_Options> fakeResult = new NotParsed<Simple_Options>(
                    TypeInfo.Create(typeof (Simple_Options)), new Error[0]);
                bool onErrorCalled = false;
                HelpText actualResult = HelpText.AutoBuild(fakeResult, ht =>
                {
                    onErrorCalled = true;
                    return ht;
                }, ex => ex);

                onErrorCalled.Should().BeTrue();
                actualResult.Heading.Should().Be(string.Format("{0} {1}", expectedTitle, expectedVersion));
            }
            finally
            {
                ReflectionHelper.SetAttributeOverride(null);
            }
        }
Ejemplo n.º 47
0
        public void Invoke_AutoBuild_for_Options_with_Usage_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed<Options_With_Usage_Attribute>(
                TypeInfo.Create(typeof(Options_With_Usage_Attribute)),
                new Error[]
                    {
                        new BadFormatTokenError("badtoken")
                    });

            // Exercize system
            var helpText = HelpText.AutoBuild(fakeResult);

            // Verify outcome
            var text = helpText.ToString();
            var lines = text.ToNotEmptyLines().TrimStringArray();
            #if !PLATFORM_DOTNET
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].Should().StartWithEquivalent("Copyright (c)");
            #else
            // Takes the name of the xUnit test program
            lines[0].Should().StartWithEquivalent("xUnit");
            lines[1].Should().StartWithEquivalent("Copyright (C) Outercurve Foundation");
            #endif
            lines[2].ShouldBeEquivalentTo("ERROR(S):");
            lines[3].ShouldBeEquivalentTo("Token 'badtoken' is not recognized.");
            lines[4].ShouldBeEquivalentTo("USAGE:");
            lines[5].ShouldBeEquivalentTo("Normal scenario:");
            lines[6].ShouldBeEquivalentTo("mono testapp.exe --input file.bin --output out.bin");
            lines[7].ShouldBeEquivalentTo("Logging warnings:");
            lines[8].ShouldBeEquivalentTo("mono testapp.exe -w --input file.bin");
            lines[9].ShouldBeEquivalentTo("Logging errors:");
            lines[10].ShouldBeEquivalentTo("mono testapp.exe -e --input file.bin");
            lines[11].ShouldBeEquivalentTo("mono testapp.exe --errs --input=file.bin");
            lines[12].ShouldBeEquivalentTo("List:");
            lines[13].ShouldBeEquivalentTo("mono testapp.exe -l 1,2");
            lines[14].ShouldBeEquivalentTo("Value:");
            lines[15].ShouldBeEquivalentTo("mono testapp.exe value");
            lines[16].ShouldBeEquivalentTo("-i, --input     Set input file.");
            lines[17].ShouldBeEquivalentTo("-i, --output    Set output file.");
            lines[18].ShouldBeEquivalentTo("--verbose       Set verbosity level.");
            lines[19].ShouldBeEquivalentTo("-w, --warns     Log warnings.");
            lines[20].ShouldBeEquivalentTo("-e, --errs      Log errors.");
            lines[21].ShouldBeEquivalentTo("-l              List.");
            lines[22].ShouldBeEquivalentTo("--help          Display this help screen.");
            lines[23].ShouldBeEquivalentTo("--version       Display version information.");
            lines[24].ShouldBeEquivalentTo("value pos. 0    Value.");

            // Teardown
        }