private CommandAppResult Run(string[] args, TestConsole console, Action <IConfigurator>?config = null)
        {
            CommandContext? context  = null;
            CommandSettings?settings = null;

            var app = new CommandApp();

            _appConfiguration?.Invoke(app);

            if (_configuration != null)
            {
                app.Configure(_configuration);
            }

            if (config != null)
            {
                app.Configure(config);
            }

            app.Configure(c => c.ConfigureConsole(console));
            app.Configure(c => c.SetInterceptor(new CallbackCommandInterceptor((ctx, s) =>
            {
                context  = ctx;
                settings = s;
            })));

            var result = app.Run(args);

            var output = console.Output
                         .NormalizeLineEndings()
                         .TrimLines()
                         .Trim();

            return(new CommandAppResult(result, output, context, settings));
        }
Example #2
0
        public static int Main(string[] args)
        {
            var app = new CommandApp();

            app.Configure(config =>
            {
                config.SetApplicationName("fakedotnet");

                // Root command
                config.AddCommand <EfSettings>("ef", ef =>
                {
                    ef.SetDescription("Fake EF Core .NET Command Line Tools");

                    // Database
                    ef.AddCommand <EfCommandSettings>("database", database =>
                    {
                        database.AddCommand <EfUpdateCommand>("update");
                        database.AddCommand <EfDropCommand>("drop");
                    });

                    // DbContext
                    ef.AddCommand <EfCommandSettings>("dbcontext", dbcontext =>
                    {
                        dbcontext.AddCommand <EfScaffoldCommand>("scaffold");
                    });
                });
            });

            return(app.Run(args));
        }
Example #3
0
        public static int Main(string[] args)
        {
            var services = new ServiceCollection()
                           .AddSingleton <IGitConfigService, GitCommandService>()
                           .AddSingleton <GitCommandRunner>()
                           .AddTransient <IGitProfileStore, FileProfileStore>()
                           .AddSingleton <ICommandFileService, CommandFileService>();
            var app = new CommandApp(new DependencyInjectionRegistrar(services));

            app.Configure(config =>
            {
                // Set additional information.
                config.SetApplicationName("Git Profile Manager");
                // app.SetHelpText("Create, manage and activate git profiles for multiple projects");

                /*// Register commands. */
                config.AddCommand <Commands.Activate.ActivateCommand>("activate");
                config.AddCommand <Commands.Deactivate.DeactivateCommand>("deactivate");
                config.AddCommand <Commands.List.ProfileListCommand>("list");
                config.AddBranch <Commands.ProfileSettings>("profile", profile =>
                {
                    profile.SetDescription("Commands for working with Git profiles");
                    profile.AddCommand <Commands.Profile.ProfileCreateCommand>("create");
                    profile.AddCommand <Commands.Profile.ProfileImportCommand>("import");
                    profile.AddCommand <Commands.Profile.ProfileDeleteCommand>("delete");
                    profile.AddCommand <Commands.Profile.ProfileEditCommand>("edit");
                    profile.AddCommand <Commands.Profile.ProfileExportCommand>("export");
                    profile.AddCommand <Commands.Profile.ProfileShowCommand>("show");
                });

                // Run the application.
            });
            return(app.Run(args));
        }
            public void Should_Execute_Nested_Delegate_Command()
            {
                // Given
                var dog  = default(DogSettings);
                var data = 0;

                var app = new CommandApp();

                app.Configure(config =>
                {
                    config.PropagateExceptions();
                    config.AddBranch <AnimalSettings>("foo", foo =>
                    {
                        foo.AddDelegate <DogSettings>("bar",
                                                      (context, settings) =>
                        {
                            dog  = settings;
                            data = (int)context.Data;
                            return(1);
                        }).WithData(2);
                    });
                });

                // When
                var result = app.Run(new[] { "foo", "4", "bar", "12" });

                // Then
                result.ShouldBe(1);
                dog.ShouldNotBeNull();
                dog.Age.ShouldBe(12);
                dog.Legs.ShouldBe(4);
                data.ShouldBe(2);
            }
        public void Should_Pass_Case_3()
        {
            // Given
            var resolver = new FakeTypeResolver();
            var settings = new DogSettings();

            resolver.Register(settings);

            var app = new CommandApp(new FakeTypeRegistrar(resolver));

            app.Configure(config =>
            {
                config.PropagateExceptions();
                config.AddBranch <AnimalSettings>("animal", animal =>
                {
                    animal.AddCommand <DogCommand>("dog");
                    animal.AddCommand <HorseCommand>("horse");
                });
            });

            // When
            var result = app.Run(new[] { "animal", "dog", "12", "--good-boy", "--name", "Rufus" });

            // Then
            result.ShouldBe(0);
            settings.Age.ShouldBe(12);
            settings.GoodBoy.ShouldBe(true);
            settings.IsAlive.ShouldBe(false);
            settings.Name.ShouldBe("Rufus");
        }
Example #6
0
        public static void Main(string[] args)
        {
            var app = new CommandApp(BootstrapServices());

            app.Configure(opts =>
            {
                opts.SetApplicationName("spectbug");
                opts.SetApplicationVersion("1.0");

                //opts.ValidateExamples();
                // => Spectre.Console.Cli.CommandConfigurationException: 'Validation of examples failed.'
                // Unknown option 'm'
                // but 'm' is defined at PrintBaseSettings:L8

                opts.AddBranch <PrintBaseSettings>("print", p =>
                {
                    p.SetDescription("Print message");

                    p.AddCommand <RepeatedPrintCmd>("repeated")
                    .WithAlias("repeat")
                    .WithDescription("Print message several times")
                    .WithExample(new[] { "print", "repeated", "-m", "Lorem ipsum", "-r", "5" });

                    p.AddCommand <DecoratedPrintCmd>("decorated")
                    .WithAlias("decor")
                    .WithDescription("Print with foo flavor")
                    .WithExample(new[] { "print", "decorated", "-m", "Lorem ipsum", "--with-foo" });
                });
            });

            app.Run(args);
        }
            public void Should_Register_Remaining_Raw_Arguments_With_Context()
            {
                // Given
                var capturedContext = default(CommandContext);

                var resolver = new FakeTypeResolver();
                var command  = new InterceptingCommand <DogSettings>((context, _) => { capturedContext = context; });

                resolver.Register(new DogSettings());
                resolver.Register(command);

                var app = new CommandApp(new FakeTypeRegistrar(resolver));

                app.Configure(config =>
                {
                    config.PropagateExceptions();
                    config.AddBranch <AnimalSettings>("animal", animal =>
                    {
                        animal.AddCommand <InterceptingCommand <DogSettings> >("dog");
                    });
                });

                // When
                app.Run(new[] { "animal", "4", "dog", "12", "--", "--foo", "bar", "-bar", "\"baz\"", "qux" });

                // Then
                capturedContext.Remaining.Raw.Count.ShouldBe(5);
                capturedContext.Remaining.Raw[0].ShouldBe("--foo");
                capturedContext.Remaining.Raw[1].ShouldBe("bar");
                capturedContext.Remaining.Raw[2].ShouldBe("-bar");
                capturedContext.Remaining.Raw[3].ShouldBe("\"baz\"");
                capturedContext.Remaining.Raw[4].ShouldBe("qux");
            }
        public void Should_Pass_Case_2()
        {
            // Given
            var resolver = new FakeTypeResolver();
            var settings = new DogSettings();

            resolver.Register(settings);

            var app = new CommandApp(new FakeTypeRegistrar(resolver));

            app.Configure(config =>
            {
                config.PropagateExceptions();
                config.AddCommand <DogCommand>("dog");
            });

            // When
            var result = app.Run(new[] { "dog", "12", "4", "--good-boy", "--name", "Rufus", "--alive" });

            // Then
            result.ShouldBe(0);
            settings.Legs.ShouldBe(12);
            settings.Age.ShouldBe(4);
            settings.GoodBoy.ShouldBe(true);
            settings.IsAlive.ShouldBe(true);
            settings.Name.ShouldBe("Rufus");
        }
            public void Should_Register_Remaining_Parsed_Arguments_With_Context()
            {
                // Given
                var capturedContext = default(CommandContext);

                var resolver = new FakeTypeResolver();
                var command  = new InterceptingCommand <DogSettings>((context, _) => { capturedContext = context; });

                resolver.Register(new DogSettings());
                resolver.Register(command);

                var app = new CommandApp(new FakeTypeRegistrar(resolver));

                app.Configure(config =>
                {
                    config.PropagateExceptions();
                    config.AddBranch <AnimalSettings>("animal", animal =>
                    {
                        animal.AddCommand <InterceptingCommand <DogSettings> >("dog");
                    });
                });

                // When
                app.Run(new[] { "animal", "4", "dog", "12", "--", "--foo", "bar", "--foo", "baz", "-bar", "\"baz\"", "qux" });

                // Then
                capturedContext.Remaining.Parsed.Count.ShouldBe(4);
                capturedContext.ShouldHaveRemainingArgument("foo", values: new[] { "bar", "baz" });
                capturedContext.ShouldHaveRemainingArgument("b", values: new[] { (string)null });
                capturedContext.ShouldHaveRemainingArgument("a", values: new[] { (string)null });
                capturedContext.ShouldHaveRemainingArgument("r", values: new[] { (string)null });
            }
Example #10
0
        public void Should_Add_Unknown_Boolean_Option_To_Remaining_Arguments_In_Relaxed_Mode()
        {
            // Given
            var capturedContext = default(CommandContext);

            var resolver = new FakeTypeResolver();
            var command  = new InterceptingCommand <DogSettings>((context, _) => { capturedContext = context; });

            resolver.Register(new DogSettings());
            resolver.Register(command);

            var registrar = new FakeTypeRegistrar(resolver);
            var app       = new CommandApp(registrar);

            app.Configure(config =>
            {
                config.PropagateExceptions();
                config.AddBranch <AnimalSettings>("animal", animal =>
                {
                    animal.AddCommand <InterceptingCommand <DogSettings> >("dog");
                });
            });

            // When
            var result = app.Run(new[] { "animal", "4", "dog", "12", "--foo" });

            // Then
            capturedContext.ShouldNotBeNull();
            capturedContext.Remaining.Parsed.Count.ShouldBe(1);
            capturedContext.ShouldHaveRemainingArgument("foo", values: new[] { (string)null });
        }
Example #11
0
        public void Should_Register_Commands_When_Configuring_Application()
        {
            // Given
            var registrar = new FakeTypeRegistrar();
            var app       = new CommandApp(registrar);

            // When
            app.Configure(config =>
            {
                config.PropagateExceptions();
                config.AddCommand <GenericCommand <FooCommandSettings> >("foo");
                config.AddBranch <AnimalSettings>("animal", animal =>
                {
                    animal.AddCommand <DogCommand>("dog");
                    animal.AddCommand <HorseCommand>("horse");
                });
            });

            // Then
            registrar.Registrations.ContainsKey(typeof(ICommand)).ShouldBeTrue();
            registrar.Registrations[typeof(ICommand)].Count.ShouldBe(3);
            registrar.Registrations[typeof(ICommand)].ShouldContain(typeof(GenericCommand <FooCommandSettings>));
            registrar.Registrations[typeof(ICommand)].ShouldContain(typeof(DogCommand));
            registrar.Registrations[typeof(ICommand)].ShouldContain(typeof(HorseCommand));
        }
Example #12
0
    public static CommandApp App()
    {
        var app = new CommandApp(DI());

        app.Configure(AddCommands);
        return(app);
    }
Example #13
0
        static int Main(string[] args)
        {
            // to retrieve the log file name, we must first parse the command settings
            // this will require us to delay setting the file path for the file writer.
            // With serilog we can use an enricher and Serilog.Sinks.Map to dynamically
            // pull this setting.
            var serviceCollection = new ServiceCollection()
                                    .AddLogging(configure =>
                                                configure.AddSerilog(new LoggerConfiguration()
                                                                     // log level will be dynamically be controlled by our log interceptor upon running
                                                                     .MinimumLevel.ControlledBy(LogInterceptor.LogLevel)
                                                                     // the log enricher will add a new property with the log file path from the settings
                                                                     // that we can use to set the path dynamically
                                                                     .Enrich.With <LoggingEnricher>()
                                                                     // serilog.sinks.map will defer the configuration of the sink to be ondemand
                                                                     // allowing us to look at the properties set by the enricher to set the path appropriately
                                                                     .WriteTo.Map(LoggingEnricher.LogFilePathPropertyName,
                                                                                  (logFilePath, wt) => wt.File($"{logFilePath}"), 1)
                                                                     .CreateLogger()
                                                                     )
                                                );

            var registrar = new TypeRegistrar(serviceCollection);
            var app       = new CommandApp(registrar);

            app.Configure(config =>
            {
                config.SetInterceptor(new LogInterceptor()); // add the interceptor
                config.AddCommand <HelloCommand>("hello");
            });

            return(app.Run(args));
        }
Example #14
0
        public void Should_Register_Remaining_Arguments()
        {
            // Given
            var registrar = new FakeTypeRegistrar();
            var app       = new CommandApp(registrar);

            app.Configure(config =>
            {
                config.AddCommand <AnimalSettings>("animal", animal =>
                {
                    animal.AddCommand <DogCommand>("dog");
                    animal.AddCommand <HorseCommand>("horse");
                });
            });

            // When
            app.Run(new[] { "animal", "--foo", "f", "dog", "--bar", "b", "--name", "Rufus" });

            // Then
            registrar.Instances.ContainsKey(typeof(IArguments)).ShouldBeTrue();
            registrar.Instances[typeof(IArguments)].Single().As <IArguments>(args =>
            {
                args.Count.ShouldBe(2);
                args.Contains("--foo").ShouldBeTrue();
                args["--foo"].Single().ShouldBe("f");
                args.Contains("--bar").ShouldBeTrue();
                args["--bar"].Single().ShouldBe("b");
            });
        }
Example #15
0
        public async Task <int> Run(string[] args)
        {
            var registrar = BuildTypeRegistrar();

            var app = new CommandApp <DefaultCommand>(registrar);

            app.Configure(config =>
            {
#pragma warning disable SA1114 // Parameter list should follow declaration
#pragma warning disable SA1009 // Closing parenthesis should be spaced correctly
#pragma warning disable SA1111 // Closing parenthesis should be on line of last parameter
                config.SetApplicationName("dotnet cake");
#pragma warning restore SA1111 // Closing parenthesis should be on line of last parameter
#pragma warning restore SA1009 // Closing parenthesis should be spaced correctly
#pragma warning restore SA1114 // Parameter list should follow declaration
                config.ValidateExamples();

                if (_propagateExceptions)
                {
                    config.PropagateExceptions();
                }

                // Top level examples.
                config.AddExample(new[] { string.Empty });
                config.AddExample(new[] { "build.cake", "--verbosity", "quiet" });
                config.AddExample(new[] { "build.cake", "--tree" });
            });

            return(await app.RunAsync(args));
        }
Example #16
0
        public void Should_Register_Command_Settings_When_Configuring_Application()
        {
            // Given
            var registrar = new FakeTypeRegistrar();
            var app       = new CommandApp(registrar);

            app.Configure(config =>
            {
                config.PropagateExceptions();
                config.AddBranch <AnimalSettings>("animal", animal =>
                {
                    animal.AddCommand <DogCommand>("dog");
                    animal.AddCommand <HorseCommand>("horse");
                });
            });

            // When
            app.Run(new[]
            {
                "animal", "4", "dog", "12",
            });

            // Then
            registrar.Registrations.ContainsKey(typeof(DogSettings)).ShouldBeTrue();
            registrar.Registrations[typeof(DogSettings)].Count.ShouldBe(1);
            registrar.Registrations[typeof(DogSettings)].ShouldContain(typeof(DogSettings));
            registrar.Registrations.ContainsKey(typeof(MammalSettings)).ShouldBeTrue();
            registrar.Registrations[typeof(MammalSettings)].Count.ShouldBe(1);
            registrar.Registrations[typeof(MammalSettings)].ShouldContain(typeof(MammalSettings));
        }
Example #17
0
        public static CommandApp CreateApp()
        {
            var app = new CommandApp();

            app.Configure(config =>
            {
                config.PropagateExceptions();
                config.AddBranch("test", branch =>
                {
                    branch.SetDescription("test cases defined in each day `Test` variable");
                    branch.AddDelegate <DayArgs>("one", TestOne).WithDescription("Run day <day>");
                    branch.AddDelegate <EmptyCommandSettings>("last", TestLast).WithDescription("Test only the last day");
                    branch.AddDelegate <EmptyCommandSettings>("all", TestAll).WithDescription("Test All");
                });

                config.AddBranch("run", branch =>
                {
                    branch.SetDescription("run on day inputs");
                    branch.AddDelegate <DayArgs>("one", RunOne);
                    branch.AddDelegate <EmptyCommandSettings>("last", RunLast).WithDescription("Run only the last day");
                    branch.AddDelegate <EmptyCommandSettings>("all", RunAll).WithDescription("Run All");
                });
            });

            return(app);
        }
Example #18
0
    public static int Main(string[] args)
    {
        var app = new CommandApp();

        app.Configure(config =>
        {
            config.SetApplicationName("fake-dotnet");
            config.ValidateExamples();
            config.AddExample(new[] { "run", "--no-build" });

            // Run
            config.AddCommand <RunCommand>("run");

            // Add
            config.AddBranch <AddSettings>("add", add =>
            {
                add.SetDescription("Add a package or reference to a .NET project");
                add.AddCommand <AddPackageCommand>("package");
                add.AddCommand <AddReferenceCommand>("reference");
            });

            // Serve
            config.AddCommand <ServeCommand>("serve")
            .WithExample(new[] { "serve", "-o", "firefox" })
            .WithExample(new[] { "serve", "--port", "80", "-o", "firefox" });
        });

        return(app.Run(args));
    }
Example #19
0
        public static async Task <int> Run(IConsole console, string[] args)
        {
            var app = new CommandApp(new TypeRegistrar(console));

            app.SetDefaultCommand <AnalyzeCommand>();
            app.Configure(config =>
            {
                config.SetApplicationName("snitch");

                config.UseStrictParsing();
                config.ValidateExamples();

                config.AddExample(new[] { "Project.csproj" });
                config.AddExample(new[] { "Project.csproj", "-e", "Foo", "-e", "Bar" });
                config.AddExample(new[] { "Project.csproj", "--tfm", "net462" });
                config.AddExample(new[] { "Project.csproj", "--tfm", "net462", "--strict" });

                config.AddExample(new[] { "Solution.sln" });
                config.AddExample(new[] { "Solution.sln", "-e", "Foo", "-e", "Bar" });
                config.AddExample(new[] { "Solution.sln", "--tfm", "net462" });
                config.AddExample(new[] { "Solution.sln", "--tfm", "net462", "--strict" });

                config.AddCommand <VersionCommand>("version");
            });

            return(await app.RunAsync(args));
        }
        public void Should_Treat_Short_Options_As_Case_Sensitive()
        {
            // Given
            var app = new CommandApp();

            app.Configure(config =>
            {
                config.UseStrictParsing();
                config.PropagateExceptions();
                config.AddCommand <GenericCommand <StringOptionSettings> >("command");
            });

            // When
            var result = Record.Exception(() => app.Run(new[]
            {
                "command", "-F", "bar",
            }));

            // Then
            result.ShouldNotBeNull();
            result.ShouldBeOfType <CommandParseException>().And(ex =>
            {
                ex.Message.ShouldBe("Unknown option 'F'.");
            });
        }
Example #21
0
        public static int Main(string[] args)
        {
            var app = new CommandApp();

            app.Configure(config =>
            {
                config.ValidateExamples();

                // Build
                config.AddCommand <BuildCommand>("build")
                .WithExample(new[] { "build", "--no-restore" });

                // Add
                config.AddBranch <AddSettings>("add", add =>
                {
                    add.SetDescription("Add reference to the project.");

                    // Package
                    add.AddCommand <AddPackageCommand>("package")
                    .WithExample(new[] { "add", "package", "Spectre.Cli" });

                    // Reference
                    add.AddCommand <AddReferenceCommand>("reference")
                    .WithExample(new[] { "add", "reference", "MyProject.csproj" });
                });
            });

            return(app.Run(args));
        }
Example #22
0
        /// <summary>
        /// Runs the program.
        /// </summary>
        /// <param name="args">arguments</param>
        /// <param name="propagateException">Propagate exception</param>
        /// <returns>int</returns>
        internal async Task <int> Run(string[] args, bool propagateException)
        {
            if (args == null)
            {
                args = System.Array.Empty <string>();
            }

            var app = new CommandApp();

            app.Configure(config =>
            {
                config.AddCommand <GenerateCommand>("generate");
                config.AddCommand <WhatIfCommand>("whatif");
                config.AddCommand <ExecuteCommand>("execute");

                if (propagateException)
                {
                    config.PropagateExceptions();
                }
            });

            var executingAssembly = Assembly.GetExecutingAssembly();
            var logRepository     = LogManager.GetRepository(executingAssembly);

            return(await app.RunAsync(args).ConfigureAwait(false));
        }
Example #23
0
        private static int Main(string[] args)
        {
            var app = new CommandApp <InstallCommand>();

            app.Configure(config =>
            {
                config
                .AddCommand <InstallCommand>("install")
                .WithDescription("Install the trainer");

                config
                .AddCommand <UninstallCommand>("uninstall")
                .WithDescription("Uninstall the trainer");
            });
            var result = app.Run(args);

            if (StartedByExplorer())
            {
                Console.WriteLine();
                Console.WriteLine("Press a key to exit...");
                Console.ReadKey();
            }

            return(result);
        }
        public void Should_Pass_Case_5()
        {
            // Given
            var resolver = new FakeTypeResolver();
            var settings = new OptionVectorSettings();

            resolver.Register(settings);

            var app = new CommandApp(new FakeTypeRegistrar(resolver));

            app.Configure(config =>
            {
                config.PropagateExceptions();
                config.AddCommand <OptionVectorCommand>("multi");
            });

            // When
            var result = app.Run(new[] { "multi", "--foo", "a", "--foo", "b", "--bar", "1", "--foo", "c", "--bar", "2" });

            // Then
            result.ShouldBe(0);
            settings.Foo.Length.ShouldBe(3);
            settings.Foo.ShouldBe(new[] { "a", "b", "c" });
            settings.Bar.Length.ShouldBe(2);
            settings.Bar.ShouldBe(new[] { 1, 2 });
        }
Example #25
0
        static async Task <int> Main(string[] args)
        {
            var app = new CommandApp(RegisterServices());

            app.Configure(config => ConfigureCommands(config));

            return(await app.RunAsync(args).ConfigureAwait(false));
        }
Example #26
0
        static Task Main(string[] args)
        {
            var app = new CommandApp();

            app.Configure(c =>
            {
            });

            return(app.RunAsync(args));
        }
Example #27
0
        static Task <int> Main(string[] args)
        {
            var app = new CommandApp();

            app.Configure(config =>
            {
                config.AddCommand <DoctorCommand>("doctor");
            });

            return(app.RunAsync(new[] { "doctor" }.Concat(args)));
        }
Example #28
0
        public static int Main(string[] args)
        {
            var app = new CommandApp();

            app.Configure(config =>
            {
                config.AddCommand <TableGeneratorCommand>("tables");
            });

            return(app.Run(args));
        }
Example #29
0
    public static async Task <int> Main(string[] args)
    {
        var app = new CommandApp <DefaultCommand>();

        app.Configure(config =>
        {
            config.SetApplicationName("dotnet example");
        });

        return(await app.RunAsync(args).ConfigureAwait(false));
    }
Example #30
0
        static void Main(string[] args)
        {
            var app = new CommandApp();

            app.Configure(config =>
            {
                config.AddCommand <ServeCommand>("serve");
                config.AddCommand <ExportCommand>("export");
            });

            app.Run(args);
        }