예제 #1
0
파일: Help01.cs 프로젝트: kutoga/FluentArgs
 public static void Main(string[] args)
 {
     FluentArgsBuilder.New()
     .WithApplicationDescription("This application demonstrates how to use the help-features.")
     .RegisterHelpFlag("-h", "--help", "--another-help-flag")
     .Parameter("-n", "--name")
     .WithDescription("Your name.")
     .WithExamples("Peter", "Benjamin")
     .IsRequired()
     .Parameter <int>("-a", "--age")
     .WithDescription("Your age.")
     .WithExamples(23, 56)
     .WithValidation(a => a >= 0 && a <= 120, a => $"You are probably not {a} years old")
     .IsRequired()
     .Parameter <string?>("-e", "--email")
     .WithDescription("Your email address.")
     .WithExamples("*****@*****.**", "*****@*****.**")
     .WithValidation(m => m.Contains('@', StringComparison.InvariantCulture), "Your mail must contain an @-sign!")
     .IsOptional()
     .Call(email => age => name =>
     {
         Console.WriteLine($"Name: {name}");
         Console.WriteLine($"Age: {age}");
         Console.WriteLine($"EMail: {email}");
     })
     .Parse(args);
 }
예제 #2
0
 public static Task Main(string[] args)
 {
     return(FluentArgsBuilder.New()
            .Parameter <int>("-n").IsRequired()
            .Call(n => MyAsyncApp(n))
            .ParseAsync(args));
 }
예제 #3
0
        public static void InvalidCommandValues_ShouldRecommendHelp()
        {
            var args = new[] { "-n", "1" };
            var dummyParsingErrorPrinter = new DummyParsingErrorPrinter();
            var called  = false;
            var builder = FluentArgsBuilder.New()
                          .DefaultConfigs()
                          .RegisterParsingErrorPrinter(dummyParsingErrorPrinter)
                          .Given.Command("-n")
                          .HasValue("111").Then(() => called = true)
                          .ElseIsInvalid()
                          .Call(() => called = true);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
            called.Should().BeFalse();
            dummyParsingErrorPrinter.ArgumentMissingErrors.Should().BeEmpty();
            dummyParsingErrorPrinter.ArgumentParsingErrors.Should().BeEmpty();
            dummyParsingErrorPrinter.InvalidStateErrors.Should().Be(0);
            dummyParsingErrorPrinter.InvalidCommandValueErrors.Count.Should().Be(1);
            dummyParsingErrorPrinter.InvalidCommandValueErrors.First().aliases.Should().BeEquivalentTo("-n");
            dummyParsingErrorPrinter.InvalidCommandValueErrors.First().helpFlagAliases.Should().BeEquivalentTo("-h", "--help");
            dummyParsingErrorPrinter.NotAllArgumentsAreUsedErrors.Should().BeEmpty();
        }
예제 #4
0
 public static Task Main(string[] args)
 {
     return(FluentArgsBuilder.New()
            .DefaultConfigsWithAppDescription("This app allows to access a remote file system and to execute some commands on it.")
            .Parameter("-k", "--apikey")
            .WithDescription("The api key")
            .IsRequired()
            .Parameter <uint>("-t", "--timeout")
            .WithDescription("Command timeout in seconds")
            .IsOptionalWithDefault(60)
            .Given.Command("-c", "--command")
            .HasValue("init").Then(timeout => apiKey => Init(apiKey, timeout))
            .HasValue("delete").Then(b => b
                                     .Parameter("-f", "--file")
                                     .WithDescription("The file to delete")
                                     .IsRequired()
                                     .Call(file => timeout => apiKey => Delete(apiKey, file, timeout)))
            .HasValue("move").Then(b => b
                                   .Parameter("-s", "--source")
                                   .WithDescription("Source path")
                                   .IsRequired()
                                   .Parameter("-d", "--destination")
                                   .WithDescription("Destination path")
                                   .IsRequired()
                                   .Call(destination => source => timeout => apiKey => Move(apiKey, source, destination, timeout)))
            .ElseIsInvalid()
            .Invalid()
            .ParseAsync(args));
 }
예제 #5
0
        public static void FailedValidationWithCustomParser_ShouldRecommendHelp()
        {
            var args = new[] { "101" };
            var dummyParsingErrorPrinter = new DummyParsingErrorPrinter();
            var called  = false;
            var builder = FluentArgsBuilder.New()
                          .DefaultConfigs()
                          .RegisterParsingErrorPrinter(dummyParsingErrorPrinter)
                          .PositionalArgument <int>()
                          .WithParser(_ => 110)
                          .WithValidation(n => n < 100)
                          .IsRequired()
                          .Call(_ => called = true);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
            called.Should().BeFalse();
            dummyParsingErrorPrinter.ArgumentMissingErrors.Should().BeEmpty();
            dummyParsingErrorPrinter.InvalidStateErrors.Should().Be(0);
            dummyParsingErrorPrinter.ArgumentParsingErrors.Count.Should().Be(1);
            dummyParsingErrorPrinter.ArgumentParsingErrors.First().aliases.Should().BeNull();
            dummyParsingErrorPrinter.ArgumentParsingErrors.First().helpFlagAliases.Should().BeEquivalentTo("-h", "--help");
            dummyParsingErrorPrinter.InvalidCommandValueErrors.Should().BeEmpty();
            dummyParsingErrorPrinter.NotAllArgumentsAreUsedErrors.Should().BeEmpty();
        }
예제 #6
0
 public static void Main(string[] args)
 {
     FluentArgsBuilder.New()
     .WithApplicationDescription("A simple calculator: add two numbers")
     .Given.Flag("-v", "--version").Then(() =>
     {
         /* ... */
         Console.WriteLine("Program version: 2.0");
         /* ... */
     })
     .Given.Flag("-u", "--update").Then(b => b
                                        .Parameter <Uri>("-s", "--source")
                                        .WithDescription("Update source url")
                                        .IsOptionalWithDefault(new Uri("http://my-update-server.com/update.zip"))
                                        .Call(uri =>
     {
         /* ... */
         Console.WriteLine($"Install update from {uri}...");
         /* ... */
     }))
     .PositionalArgument <int>()
     .WithDescription("The first number")
     .IsRequired()
     .PositionalArgument <int>()
     .WithDescription("the second number")
     .IsRequired()
     .Call(n2 => n1 =>
     {
         /* ... */
         Console.WriteLine($"{n1}+{n2}={n1 + n2}");
         /* ... */
     })
     .Parse(args);
 }
예제 #7
0
 public static void Main(string[] args)
 {
     FluentArgsBuilder.New()
     .Parameter <int>("-n").IsRequired()
     .Call(n => MyBlockingApp(n))
     .Parse(args);
 }
예제 #8
0
 // TODO: Enum parser
 private static IParsable BuildParser(DummyClient dummyClient)
 {
     return(FluentArgsBuilder.New()
            .Parameter("--apikey", "-k").IsRequired()
            .Given.Command("--action", "--act", "-a")
            .HasValue("copy").Then(b => b
                                   .Parameter("--source", "-s").IsRequired()
                                   .Parameter("--target", "-t").IsRequired()
                                   .Call(target => source => apiKey =>
     {
         dummyClient.ApiKey = apiKey;
         dummyClient.CopyFile(source, target);
     }))
            .HasValue("delete", "del").Then(b => b
                                            .Parameter("--file", "-f").IsRequired()
                                            .Call(file => apiKey =>
     {
         dummyClient.ApiKey = apiKey;
         dummyClient.DeleteFile(file);
     }))
            .HasValue("reset").Then(b => b
                                    .Parameter <int?>("--timeout", "-t").IsOptional()
                                    .Call(timeout => apiKey =>
     {
         dummyClient.ApiKey = apiKey;
         dummyClient.ResetAccount(timeout);
     }))
            .ElseIsInvalid()
            .Invalid()
            .Build());
 }
예제 #9
0
 public static Task Main(string[] args)
 {
     return FluentArgsBuilder.New()
         .DefaultConfigsWithAppDescription("An app to convert png files to jpg files.")
         .Parameter("-i", "--input")
             .WithDescription("Input png file")
             .WithExamples("input.png")
             .IsRequired()
         .Parameter("-o", "--output")
             .WithDescription("Output jpg file")
             .WithExamples("output.jpg")
             .IsRequired()
         .Parameter<ushort>("-q", "--quality")
             .WithDescription("Quality of the conversion")
             .WithValidation(n => n >= 0 && n <= 100)
             .IsOptionalWithDefault(50)
         .Call(quality => outputFile => inputFile =>
         {
             /* ... */
             Console.WriteLine($"Convert {inputFile} to {outputFile} with quality {quality}...");
             /* ... */
             return Task.CompletedTask;
         })
         .ParseAsync(args);
 }
        public static void Whitespaces_ShouldAlwaysThrow(string name)
        {
            Action buildAction = () => FluentArgsBuilder.New()
                                 .Flag(name)
                                 .Call(_ => { });

            buildAction.Should().Throw <Exception>();
        }
        public static void IncludingTheSameParameterNameMultipleTimesInTheSameDefinition_ShouldAlwaysThrow()
        {
            Action buildAction = () => FluentArgsBuilder.New()
                                 .Parameter("-x", "-x").IsOptional()
                                 .Call(_ => { });

            buildAction.Should().Throw <Exception>();
        }
예제 #12
0
        public static void Main(string[] args)
        {
            var success = FluentArgsBuilder.New()
                          .PositionalArgument <int>().IsRequired()
                          .Call(_ => { })
                          .Parse(args);

            Console.WriteLine($"Parse success: {success}");
        }
예제 #13
0
        public static void GivenARequiredArgIsMissing_ShouldNotbeParsedSuccessful()
        {
            var args    = new[] { "--name", "beni" };
            var builder = FluentArgsBuilder.New()
                          .Parameter <int>("--age").IsRequired()
                          .Call(age => { });

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
        }
예제 #14
0
        public static void GivenAnAmbiguousEnumParameter_ParsingShouldNotWork()
        {
            var args    = new[] { "-m", "naMeB" };
            var builder = FluentArgsBuilder.New()
                          .Parameter <MyEnum>("-m").IsRequired()
                          .Call(m => { });

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
        }
예제 #15
0
        public static void GivenARequiredParameterWithoutAValue_ShouldNotbeParsedSuccessful()
        {
            var args    = new[] { "--name" };
            var builder = FluentArgsBuilder.New()
                          .Parameter("--name").IsRequired()
                          .Call(name => { });

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
        }
예제 #16
0
        public static void GivenNoArguments_UntypedCallsShouldBePossible()
        {
            var args = Array.Empty <string>();
            IReadOnlyCollection <object?>?parameters = null;
            var builder = FluentArgsBuilder.New()
                          .CallUntyped(p => parameters = p);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeTrue();
            parameters.Should().BeEmpty();
        }
예제 #17
0
        public static void GivenARequiredListParameterWhichIsNotPresent_ShouldNotParseSuccessful()
        {
            var args = new[] { "-x" };
            IReadOnlyList <int>?parsedN = default;
            var builder = FluentArgsBuilder.New()
                          .ListParameter <int>("-n").IsRequired()
                          .Call(n => parsedN = n);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
        }
예제 #18
0
        public static void IfTooManyArgumentsAreGiven_ShouldBeParsable()
        {
            var args    = new[] { "a", "b" };
            var called  = false;
            var builder = FluentArgsBuilder.New()
                          .Call(() => called = true);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeTrue();
            called.Should().BeTrue();
        }
예제 #19
0
 public static void Main(string[] args)
 {
     FluentArgsBuilder.New()
     .DefaultConfigs()
     .Parameter <int>("-b", "--binaryNumber")
     .WithDescription("A binary number which is greater or equal to 0 and smaller or equal to 100")
     .WithParser(BinaryNumberParser)
     .WithValidation(n => n >= 0 && n <= 100)
     .IsRequired()
     .Call(n => Console.WriteLine($"Number: {n}"))
     .Parse(args);
 }
예제 #20
0
        public static void GivenNoArgumentsButParameters_ShouldBeParsable()
        {
            var done    = false;
            var args    = new[] { "-a", "-b", "--bla" };
            var builder = FluentArgsBuilder.New()
                          .Call(() => done = true);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeTrue();
            done.Should().BeTrue();
        }
예제 #21
0
        static void Main(string[] args)
        {
            FluentArgsBuilder
            .NewWithDefaultConfigs()
            .WithApplicationDescription("Benchmark of sqlite3 bulk inserts with different pragmas.")
            .Parameter <int>("-i", "--batchSizeIncrement")
            .WithDescription("Growth of 'batchSizeBase' parameter in each test set run.")
            .WithValidation(i => i >= 1)
            .IsOptionalWithDefault(5_000)
            .Parameter <int>("-b", "--batchSizeBase")
            .WithDescription("Minimal number of inserts in a transaction, will be incremented by 'batchSizeIncrement' in each test set run.")
            .WithValidation(b => b >= 1)
            .IsOptionalWithDefault(5_000)
            .Parameter <int>("-t", "--tableCount")
            .WithDescription("Number of tables to use for inserts.")
            .WithValidation(t => t >= 1)
            .IsOptionalWithDefault(10)
            .Parameter <string>("-s", "--string")
            .WithDescription("Value to insert (along with sequential integer primary key).")
            .IsOptionalWithDefault("string")
            .Parameter <int>("-r", "--rowCount")
            .WithDescription("Total number of rows to insert in each test.")
            .WithValidation(r => r >= 100)
            .IsOptionalWithDefault(5_000_000)
            .Parameter <int>("-n", "--number")
            .WithDescription("Number of test set runs.")
            .WithValidation(n => n >= 1)
            .IsOptionalWithDefault(40)
            .Call(n => totalRows => value => tblCount => batchSizeBase => batchSizeIncrement =>
            {
                Console.WriteLine("batchSize;default;sync-off;jm-wal;jm-off;lm-excl;sync-off&jm-off&lm-excl");
                for (int i = 0; i < n; i++)
                {
                    var batchSize = batchSizeBase + batchSizeIncrement * i;
                    var commits   = Math.Max(1, totalRows / batchSize);

                    Console.WriteLine(new StringBuilder().AppendJoin(";",
                                                                     batchSize,
                                                                     RunTestSet("default", i, Array.Empty <string>(), tblCount, commits, batchSize, value),
                                                                     RunTestSet("sync-off", i, new[] { "synchronous = OFF" }, tblCount, commits, batchSize, value),
                                                                     RunTestSet("jm-wal", i, new[] { "journal_mode = WAL" }, tblCount, commits, batchSize, value),
                                                                     RunTestSet("jm-off", i, new[] { "journal_mode = OFF" }, tblCount, commits, batchSize, value),
                                                                     RunTestSet("lm-excl", i, new[] { "locking_mode = EXCLUSIVE" }, tblCount, commits, batchSize, value),
                                                                     RunTestSet("sync-off&jm-off&lm-excl", i, new[] {
                        "synchronous = OFF",
                        "journal_mode = OFF",
                        "locking_mode = EXCLUSIVE"
                    }, tblCount, commits, batchSize, value)
                                                                     ));
                }
            })
            .Parse(args);
        }
예제 #22
0
        public static void Main(string[] args)
        {
            FluentArgsBuilder.New()

            .RegisterParsingErrorPrinter(new SimpleParsingErrorPrinter(Console.Out))
            /* or */
            .RegisterParsingErrorPrinter(new MyParsingErrorPrinter())

            .PositionalArgument <int>().IsRequired()
            .Call(_ => { })
            .Parse(args);
        }
예제 #23
0
        public static void GivenNoArgumentsAndNoParameters_ShouldBeParsable()
        {
            var done    = false;
            var args    = Array.Empty <string>();
            var builder = FluentArgsBuilder.New()
                          .Call(() => done = true);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeTrue();
            done.Should().BeTrue();
        }
예제 #24
0
        public static void IfAParameterIsUsedAndRemoved_TheSurroundingElementsShouldNotProduceANewParameter()
        {
            var args    = new[] { "--a", "--b", "b", "a" };
            var builder = FluentArgsBuilder.New()
                          .Parameter("--a").IsRequired()
                          .Parameter("--b").IsRequired()
                          .Call(b => a => { });

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
        }
예제 #25
0
        public static void GivenAllAssignmentOperatorsAreDisabled_ShouldNotUseThem()
        {
            var args    = new[] { "-a=1" };
            var builder = FluentArgsBuilder.New()
                          .WithoutAssignmentOperators()
                          .Parameter("-a").IsRequired()
                          .Call(_ => { });

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
        }
        public static void IfNotConfigured_AnyNonEmptyNameIsValid(string name)
        {
            var args    = new[] { name };
            var called  = false;
            var builder = FluentArgsBuilder.New()
                          .Flag(name)
                          .Call(_ => called = true);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeTrue();
            called.Should().BeTrue();
        }
예제 #27
0
        public static void GivenNoParametersAreDefined_AllParametersShouldBeRemainingArguments()
        {
            var args = new[] { "-x", "a", "-y", "b" };
            IReadOnlyList <string>?parsedArgs = default;
            var builder = FluentArgsBuilder.New()
                          .LoadRemainingArguments()
                          .Call(args => parsedArgs = args);

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeTrue();
            parsedArgs.Should().BeEquivalentWithSameOrdering(new[] { "-x", "a", "-y", "b" });
        }
        public static void GivenTwoIdenticalParameterNames_ShouldNotThrow()
        {
            var called  = false;
            var builder = FluentArgsBuilder.New()
                          .Parameter("-x").IsOptional()
                          .Parameter("-x").IsOptional()
                          .Call(_ => _ => called = true);

            var parseSuccess = builder.Parse();

            parseSuccess.Should().BeTrue();
            called.Should().BeTrue();
        }
예제 #29
0
        public static void GivenAnAlwaysInvalidCommandValue_ShouldNotParseSuccessful()
        {
            var args    = new[] { "-c", "beni" };
            var builder = FluentArgsBuilder.New()
                          .Given.Command("-c")
                          .Matches(_ => false).Then(() => { })
                          .ElseIsInvalid()
                          .Call(() => { });

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
        }
예제 #30
0
        public static void GivenACommandWithAnInvalidValue_ShouldNotParseSuccessful()
        {
            var args    = new[] { "--type", "pi" };
            var builder = FluentArgsBuilder.New()
                          .Given.Command("--type")
                          .HasValue("a").Then(() => { })
                          .ElseIsInvalid()
                          .Call(() => { });

            var parseSuccess = builder.Parse(args);

            parseSuccess.Should().BeFalse();
        }