Example #1
0
        public static async Task <int> Main(string[] args)
        {
            var command = new RootCommand();

            command.Add(ScrapeCommand.Create());
            command.Description = "Scrapes test results from AzDO, xUnit files, etc. and stores it in a database.";

            var builder = new CommandLineBuilder(command);

            builder.UseHelp();
            builder.UseVersionOption();
            builder.UseDebugDirective();
            builder.UseParseErrorReporting();
            builder.ParseResponseFileAs(ResponseFileHandling.ParseArgsAsSpaceSeparated);
            builder.UsePrefixes(new[] { "-", "--", }); // disable garbage windows conventions

            builder.CancelOnProcessTermination();
            builder.UseExceptionHandler(HandleException);

            // Allow fancy drawing.
            builder.UseAnsiTerminalWhenAvailable();

            var parser = builder.Build();

            return(await parser.InvokeAsync(args));
        }
Example #2
0
        public static Task <int> Main(string[] args)
        {
            var command = new RootCommand()
            {
                Description = "Developer tool to update the Visual Studio project versions."
            };

            command.AddCommand(ListCommand.Create());
            command.AddCommand(MajorCommand.Create());
            command.AddCommand(MinorCommand.Create());
            command.AddCommand(PatchCommand.Create());
            command.AddCommand(BuildCommand.Create());
            command.AddCommand(PreCommand.Create());
            command.AddCommand(SetCommand.Create());


            var builder = new CommandLineBuilder(command)
                          .UseHelp()
                          .UseDefaults()
                          .UseVersionOption()
                          .CancelOnProcessTermination()
                          .UseExceptionHandler();

            var parser = builder.Build();

            return(parser.InvokeAsync(args));
        }
        public virtual int ProcessCommandLine()
        {
            var buildState = AppHostBuilder.BuildState;
            var arguments  = buildState.ParsableArguments();
            var console    = Plugins.GetRequiredService <IConsole>();

            // Creating & configuring CLI builder
            CliBuilder = new CommandLineBuilder().UseDefaults();
            ConfigureCliBuilder();
            // Letting other CLI plugins to kick in
            CliBuilder.UsePlugins <ICliPlugin>(Plugins);

            // Building parser & parsing the arguments
            var cliParser      = CliBuilder.Build();
            var cliParseResult = cliParser.Parse(arguments);

            // Invoking commands
            var exitCode     = cliParseResult.Invoke(console);
            var cliException = buildState.CliException;

            if (cliException != null)
            {
                ExceptionDispatchInfo.Throw(cliException);
            }
            return(exitCode);
        }
Example #4
0
        public static async Task <int> Main(string[] args)
        {
            var command = new RootCommand()
            {
                Description = "Developer tools and publishing for microservices.",
            };

            // Show commandline help unless a subcommand was used.
            command.Handler = CommandHandler.Create <IHelpBuilder>(help =>
            {
                help.Write(command);
                return(1);
            });

            var builder = new CommandLineBuilder(command);

            builder.UseHelp();
            builder.UseVersionOption();
            builder.UseDebugDirective();
            builder.UseParseErrorReporting();
            builder.ParseResponseFileAs(ResponseFileHandling.ParseArgsAsSpaceSeparated);

            builder.CancelOnProcessTermination();
            builder.UseExceptionHandler(HandleException);

            var parser = builder.Build();

            return(await parser.InvokeAsync(args));
        }
Example #5
0
        static async Task <int> Main(string[] args)
        {
            var builder = new CommandLineBuilder()
                          .UseHost(host =>
            {
                host.ConfigureServices((context, services) =>
                {
                    // services.AddTransient(typeof(ILoggerFactory), typeof(LoggerFactory));
                    // services.AddTransient(typeof(ILogger<>), typeof(Logger<>));
                    services.AddLogging(logging => logging
                                        .AddConsole()
                                        .AddDebug()
                                        .SetMinimumLevel(LogLevel.Trace));
                });
            })
                          .UseDebugDirective()
                          .UseHelp()
                          .UseTypoCorrections()
                          .UseAttributedCommands()
                          .UseSuggestDirective();

            var parser      = builder.Build();
            var parseResult = parser.Parse("test -b -a \"parameter a\"");
            var invoke      = await parseResult.InvokeAsync();

            return(invoke);
        }
Example #6
0
        static CommandLine()
        {
            var commandLine = new CommandLineBuilder()
                              .UseParseDirective()
                              .UseHelp()
                              .UseSuggestDirective()
                              .UseParseErrorReporting()
                              .UseExceptionHandler()
                              .AddOption("--file",
                                         ".trx file(s) to parse",
                                         a => a.ExistingFilesOnly()
                                         .ParseArgumentsAs <FileInfo[]>())
                              .AddOption("--filter",
                                         "Only look at tests matching the filter. \"*\" can be used as a wildcard.",
                                         args => args.ExactlyOne())
                              .AddOption("--format",
                                         "The format for the output.",
                                         args => args.WithDefaultValue(() => OutputFormat.Summary)
                                         .ParseArgumentsAs <OutputFormat>())
                              .AddOption("--path",
                                         "Directory or directories to search for .trx files. Only the most recent .trx file in a given directory is used.",
                                         a => a.WithDefaultValue(Directory.GetCurrentDirectory)
                                         .ParseArgumentsAs <DirectoryInfo[]>())
                              .AddOption("--show-test-output",
                                         "For failed tests, display the output.",
                                         a => a.ParseArgumentsAs <bool>());

            commandLine.Description = "A command line testing tool for .NET";

            commandLine.OnExecute(typeof(CommandLine).GetMethod(nameof(InvokeAsync)));

            Parser = commandLine.Build();
        }
Example #7
0
        private void StartProcess()
        {
            var processStartInfo = new ProcessStartInfo($@"""{Path.Combine(JavaHome.FullName, "bin/java.exe")}""")
            {
                UseShellExecute        = false,
                Arguments              = _commandLineBuilder.Build(_parameters),
                WindowStyle            = ProcessWindowStyle.Maximized,
                CreateNoWindow         = true,
                LoadUserProfile        = false,
                WorkingDirectory       = ElasticsearchHome.FullName,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                StandardOutputEncoding = Encoding.ASCII,
            };

            _elasticSearchProcess = Process.Start(processStartInfo);
            if (null == _elasticSearchProcess)
            {
                throw new Exception("Fail to start elasticsearch");
            }

            _elasticSearchProcess.ErrorDataReceived  += (sender, eventargs) => Info(eventargs.Data);
            _elasticSearchProcess.OutputDataReceived += (sender, eventargs) => Info(eventargs.Data);
            _elasticSearchProcess.BeginOutputReadLine();
        }
Example #8
0
        static async Task <int> Main(string[] args)
        {
            var command = new RootCommand();

            command.Add(RunCommand(args));
            command.Add(NewCommand());

            command.Description = "Process manager and orchestrator for microservices.";

            var builder = new CommandLineBuilder(command);

            builder.UseHelp();
            builder.UseVersionOption();
            builder.UseDebugDirective();
            builder.UseParseErrorReporting();
            builder.ParseResponseFileAs(ResponseFileHandling.ParseArgsAsSpaceSeparated);
            builder.UsePrefixes(new[] { "-", "--", }); // disable garbage windows conventions

            builder.CancelOnProcessTermination();
            builder.UseExceptionHandler(HandleException);

            // Allow fancy drawing.
            builder.UseAnsiTerminalWhenAvailable();

            var parser = builder.Build();

            return(await parser.InvokeAsync(args));
        }
Example #9
0
        private Parser GetDirectiveParser()
        {
            if (_directiveParser == null)
            {
                var root = new RootCommand();

                foreach (var c in _directiveCommands)
                {
                    root.Add(c);
                }

                var commandLineBuilder =
                    new CommandLineBuilder(root)
                    .ParseResponseFileAs(ResponseFileHandling.Disabled)
                    .UseMiddleware(
                        context => context.BindingContext
                        .AddService(
                            typeof(KernelInvocationContext),
                            () => KernelInvocationContext.Current));

                commandLineBuilder.EnableDirectives = false;

                _directiveParser = commandLineBuilder.Build();
            }

            return(_directiveParser);
        }
        private Parser GetDirectiveParser()
        {
            if (_directiveParser == null)
            {
                EnsureRootCommandIsInitialized();

                var commandLineBuilder =
                    new CommandLineBuilder(_rootCommand)
                    .ParseResponseFileAs(ResponseFileHandling.Disabled)
                    .UseTypoCorrections()
                    .UseHelpBuilder(bc => new HelpBuilderThatOmitsRootCommandName(bc.Console, _rootCommand.Name))
                    .UseHelp()
                    .UseMiddleware(
                        context =>
                {
                    context.BindingContext
                    .AddService(
                        typeof(KernelInvocationContext),
                        _ => KernelInvocationContext.Current);
                });

                commandLineBuilder.EnableDirectives = false;

                _directiveParser = commandLineBuilder.Build();
            }

            return(_directiveParser);
        }
Example #11
0
        public static async Task <int> Main(string[] args)
        {
            var command = new RootCommand
            {
                Commands.Deploy.Command(),
                // ...add more commands here
            };

            command.Name        = "clud";
            command.Description = "clud deployment tool";

            // Show commandline help unless a sub-command was used.
            command.Handler = CommandHandler.Create <IHelpBuilder>(help =>
            {
                ConsoleHelpers.PrintLogo();
                help.Write(command);
                return(1);
            });

            var builder = new CommandLineBuilder(command);

            builder.UseHelp();
            builder.UseVersionOption();
            builder.UseDebugDirective();
            builder.UseParseErrorReporting();
            builder.ParseResponseFileAs(ResponseFileHandling.ParseArgsAsSpaceSeparated);

            builder.CancelOnProcessTermination();
            builder.UseExceptionHandler(HandleException);

            var parser = builder.Build();

            return(await parser.InvokeAsync(args));
        }
Example #12
0
        public static async Task <int> Main(string [] args)
        {
            var rootCommand                  = MsIdentityCommand();
            var listAadAppsCommand           = ListAADAppsCommand();
            var listServicePrincipalsCommand = ListServicePrincipalsCommand();
            var provisionApplicationCommand  = ProvisionApplicationCommand();

            listAadAppsCommand.Handler           = CommandHandler.Create <ProvisioningToolOptions>(HandleListApps);
            listServicePrincipalsCommand.Handler = CommandHandler.Create <ProvisioningToolOptions>(HandleListServicePrincipals);
            provisionApplicationCommand.Handler  = CommandHandler.Create <ProvisioningToolOptions>(HandleProvisionApplication);
            rootCommand.AddCommand(listAadAppsCommand);
            rootCommand.AddCommand(listServicePrincipalsCommand);
            rootCommand.AddCommand(provisionApplicationCommand);

            if (args == null || args.Length == 0)
            {
                args = new string[] { "-h" };
            }

            var commandLineBuilder = new CommandLineBuilder(rootCommand);

            commandLineBuilder.UseDefaults();

            var parser = commandLineBuilder.Build();

            return(await parser.InvokeAsync(args));
        }
Example #13
0
        /// <summary>
        /// Create an instance of the command processor;
        /// </summary>
        /// <param name="serviceProvider">service provider interface</param>
        /// <param name="console">console instance</param>
        /// <param name="assemblies">Optional list of assemblies to look for commands</param>
        /// <param name="types">Optional list of types to look for commands</param>
        public CommandProcessor(IServiceProvider serviceProvider, IConsole console, IEnumerable <Assembly> assemblies = null, IEnumerable <Type> types = null)
        {
            Debug.Assert(serviceProvider != null);
            Debug.Assert(assemblies != null);
            _serviceProvider = serviceProvider;
            _console         = console;

            var rootBuilder = new CommandLineBuilder(new Command(">"));

            rootBuilder.UseHelp()
            .UseHelpBuilder((bindingContext) => GetService <IHelpBuilder>())
            .UseParseDirective()
            .UseSuggestDirective()
            .UseParseErrorReporting()
            .UseExceptionHandler();

            if (assemblies != null)
            {
                BuildCommands(rootBuilder, assemblies);
            }
            if (types != null)
            {
                BuildCommands(rootBuilder, types);
            }
            _rootCommand = rootBuilder.Command;
            _parser      = rootBuilder.Build();
        }
Example #14
0
        public static async Task <int> Main(string[] args)
        {
            CommandLineBuilder commandLineBuilder = CreateCommandLineBuilder();
            Parser             parser             = commandLineBuilder.Build();

            return(await parser.InvokeAsync(args));
        }
Example #15
0
        private static Parser BuildParser(MethodInfo method, string xmlDocsFilePath, object target)
        {
            var builder = new CommandLineBuilder()
                          .ConfigureRootCommandFromMethod(method, target)
                          .ConfigureHelpFromXmlComments(method, xmlDocsFilePath)
                          .UseDefaults()
                          .UseAnsiTerminalWhenAvailable();

            return(builder.Build());
        }
Example #16
0
        internal static async Task <int> RunEngine(CommandLineBuilder hostBuilder)
        {
            var args = Environment.GetCommandLineArgs();

            if (args.Length == 0)
            {
                AnsiConsole.MarkupLine("[bold red]Loadit.dev[/]");
            }
            return(await hostBuilder.Build().InvokeAsync(args));
        }
        public void Can_add_argument()
        {
            ////Arrange
            var builder = new CommandLineBuilder();

            ////Act
            var result = builder.Build(new Example {Argument = "tester"});

            ////Assert
            Assert.That(result, Is.EqualTo(" -Des.index.gateway.type=tester"));
        }
Example #18
0
        public void Global_options_are_added_to_the_root_command()
        {
            var globalOption = new Option("global");
            var builder      = new CommandLineBuilder().AddGlobalOption(globalOption);

            Parser parser = builder.Build();

            Command rootCommand = (Command)parser.Configuration.RootCommand;

            rootCommand.GlobalOptions.Should().Contain(globalOption);
        }
Example #19
0
        public static async Task <int> Main(string[] args)
        {
            var rootCommand = NupkgInfo();

            rootCommand.Handler = CommandHandler.Create <ToolOptions>(HandleNupkgInfo);
            var commandLineBuilder = new CommandLineBuilder(rootCommand);

            commandLineBuilder.UseDefaults();
            var parser = commandLineBuilder.Build();

            return(await parser.InvokeAsync(args));
        }
Example #20
0
        internal static Parser CreateParser(Command command, bool disableHelp = false)
        {
            var builder = new CommandLineBuilder(command)
                          .UseParseDirective()
                          .UseSuggestDirective()
                          .EnablePosixBundling(false);

            if (!disableHelp)
            {
                builder = builder.UseHelp();
            }
            return(builder.Build());
        }
Example #21
0
        public static async Task <int> Main(string[] args, IConsole console = null)
        {
            var rpCommand = new RootCommand("Interact with Report Portal API");

            AddConnectCommand(rpCommand);
            AddLaunchCommand(rpCommand);

            var b = new CommandLineBuilder(rpCommand)
                    .UseDefaults();
            var parser = b.Build();

            return(await parser.InvokeAsync(args, console));
        }
        /// <summary>
        /// Create an instance of the command processor;
        /// </summary>
        /// <param name="assemblies">The list of assemblies to look for commands</param>
        public CommandProcessor(IEnumerable <Assembly> assemblies)
        {
            var rootBuilder = new CommandLineBuilder();

            rootBuilder.UseHelp()
            .UseParseDirective()
            .UseSuggestDirective()
            .UseParseErrorReporting()
            .UseExceptionHandler();
            BuildCommands(rootBuilder, assemblies);
            _rootCommand = rootBuilder.Command;
            _parser      = rootBuilder.Build();
        }
        public void Can_add_argument()
        {
            ////Arrange
            var builder = new CommandLineBuilder();

            ////Act
            var result = builder.Build(new Example {
                Argument = "tester"
            });

            ////Assert
            Assert.That(result, Is.EqualTo(" -Des.index.gateway.type=tester"));
        }
Example #24
0
        public static Task <int> Main(string[] args)
        {
            var root = new RootCommand();

            root.Handler = CommandHandler.Create <IConsole, IHelpBuilder>((console, help) =>
            {
                // looks a bit gross but avoids a newline
                console.Out.Write(@"   _____      __                         __  _
  / ___/_____/ /_  ___  ____ ___  ____ _/ /_(_)____
  \__ \/ ___/ __ \/ _ \/ __ `__ \/ __ `/ __/ / ___/
 ___/ / /__/ / / /  __/ / / / / / /_/ / /_/ / /__
/____/\___/_/ /_/\___/_/ /_/ /_/\__,_/\__/_/\___/

The helpful database schema querying tool.

");

                help.Write(root);
                return(1);
            });

            var configFileOption = new Option <FileInfo>(
                "--config",
                getDefaultValue: () => new FileInfo(
                    Path.Combine(Directory.GetCurrentDirectory(),
                                 "schematic.config.json"
                                 )),
                description: "A path to a configuration file used to retrieve options such as connection strings."
                ).ExistingOnly();

            root.AddGlobalOption(configFileOption);

            root.AddCommand(new OrmCommand());
            root.AddCommand(new LintCommand());
            root.AddCommand(new ReportCommand());
            root.AddCommand(new TestCommand());

            var builder = new CommandLineBuilder(root);

            builder.UseHelp();
            builder.UseVersionOption();
            builder.UseDebugDirective();
            builder.UseParseErrorReporting();
            builder.ParseResponseFileAs(ResponseFileHandling.ParseArgsAsSpaceSeparated);
            builder.CancelOnProcessTermination();
            builder.UseExceptionHandler(HandleException);

            var parser = builder.Build();

            return(parser.InvokeAsync(args));
        }
Example #25
0
        /*
         * dotnet scaffold [generator] [-p|--project] [-n|--nuget-package-dir] [-c|--configuration] [-tfm|--target-framework] [-b|--build-base-path] [--no-build]
         *
         * This commands supports the following generators :
         *  Area
         *  Controller
         *  Identity
         *  Razorpage
         *  View
         *
         * e.g: dotnet scaffold area <AreaNameToGenerate>
         *   dotnet scaffold identity
         *   dotnet scaffold razorpage
         *
         */

        public static int Main(string[] args)
        {
            var rootCommand = ScaffoldCommand();

            rootCommand.AddCommand(ScaffoldAreaCommand());
            rootCommand.AddCommand(ScaffoldControllerCommand());
            rootCommand.AddCommand(ScaffoldRazorPageCommand());
            rootCommand.AddCommand(ScaffoldViewCommand());
            rootCommand.AddCommand(ScaffoldIdentityCommand());

            rootCommand.Description = "dotnet scaffold [command] [-p|--project] [-n|--nuget-package-dir] [-c|--configuration] [-tfm|--target-framework] [-b|--build-base-path] [--no-build] ";
            if (args.Length == 0)
            {
                args = new string[] { "-h" };
            }

            var commandLineBuilder = new CommandLineBuilder(rootCommand);

            commandLineBuilder.UseDefaults();
            var parser        = commandLineBuilder.Build();
            int parseExitCode = parser.Invoke(args);

            if (parseExitCode != 0)
            {
                return(parseExitCode);
            }

            ParseResult parseResult       = parser.Parse(args);
            string      parsedCommandName = parseResult.CommandResult.Command.Name;

            switch (parsedCommandName)
            {
            case AREA_COMMAND:
            case CONTROLLER_COMMAND:
            case IDENTITY_COMMAND:
            case RAZORPAGE_COMMAND:
            case VIEW_COMMAND:
                if (parseResult.CommandResult.Children.Count == 1 &&
                    string.Equals(parseResult.CommandResult.Children[0].Symbol?.Name, "help", StringComparison.OrdinalIgnoreCase))
                {
                    // The help option for the commands are handled by System.Commandline.
                    return(0);
                }
                return(VisualStudio.Web.CodeGeneration.Tools.Program.Main(args));

            default:
                // The command is not handled by 'dotnet scaffold'.
                return(-1);
            }
        }
        /// <summary>
        /// Composes the <see cref="IServiceCollection"/> with <see cref="ConfigureServices"/> and
        /// builds a new <see cref="CommandLineBuilder"/> which is configured by calling all
        /// <see cref="ConfigureCommandLine"/>.
        /// </summary>
        /// <returns>A new <see cref="Parser"/> instance.</returns>
        public Parser Build()
        {
            var services = ComposeServiceCollection();

            var builder = new CommandLineBuilder(this._rootCommand)
                          .UseAffectedCli(new StartupData(services));

            foreach (var callback in _configureCommandLine)
            {
                callback.Invoke(builder);
            }

            return(builder.Build());
        }
Example #27
0
        static async Task Main(string[] args)
        {
            var command = new RootCommand("Run a .NET Framework website in IIS")
            {
                new Argument <DirectoryInfo?>(CLIHelper.ParsePath <DirectoryInfo>)
                {
                    Arity       = ArgumentArity.ExactlyOne,
                    Description = "The relative or absolute path to the .NET Framework project directory",
                    Name        = "path",
                },
                new Argument <DirectoryInfo?>(CLIHelper.ParsePath <DirectoryInfo>)
                {
                    Arity       = ArgumentArity.ZeroOrOne,
                    Description = "The relative or absolute path to the solution directory",
                    Name        = "solutionPath"
                },
                new Option("--no-build", "Do not build the website before launching it"),
                new Option("--name", "The name of the website")
                {
                    Argument = new Argument <string>("name")
                },
                new Option("--port", "The port that the website should listen on")
                {
                    Argument = new Argument <int>("port")
                }
            };

            command.Handler = CommandHandler.Create <CommandArguments>(async arg =>
            {
                if (string.IsNullOrEmpty(arg.Path?.FullName))
                {
                    throw new Exception("Argument 'path' is required.");
                }

                var environmentVariables = EnvironmentHelper.LoadEnvironmentVariables();

                await using var iisHost = new IISHost(environmentVariables);
                await iisHost.Run(arg.Console, arg, arg.Token);
            });

            var builder = new CommandLineBuilder(command);

            builder.UseHelp();
            builder.UseDebugDirective();
            builder.UseExceptionHandler(CLIHelper.HandleException);
            builder.CancelOnProcessTermination();

            var parser = builder.Build();
            await parser.InvokeAsync(args);
        }
Example #28
0
        public static async Task <int> InvokeMethodAsync(
            string[] args,
            IConsole console,
            MethodInfo method,
            object @object)
        {
            var builder = new CommandLineBuilder()
                          .ConfigureFromMethod(method, @object)
                          .ConfigureHelpFromXmlComments(method)
                          .UseDefaults();

            Parser parser = builder.Build();

            return(await parser.InvokeAsync(args, console));
        }
Example #29
0
        internal static Parser CreateParser(Command command, bool disableHelp = false)
        {
            var builder = new CommandLineBuilder(command)
                          .UseParseErrorReporting()
                          //TODO: decide if it's needed to implement it; and implement if needed
                          //.UseParseDirective()
                          //.UseSuggestDirective()
                          .EnablePosixBundling(false);

            if (!disableHelp)
            {
                builder = builder.UseHelp();
            }
            return(builder.Build());
        }
        public static async Task <int> InvokeMethodAsync(
            string[] args,
            MethodInfo method,
            object target    = null,
            IConsole console = null)
        {
            var builder = new CommandLineBuilder()
                          .ConfigureRootCommandFromMethod(method, target)
                          .ConfigureHelpFromXmlComments(method)
                          .UseDefaults()
                          .UseAnsiTerminalWhenAvailable();

            Parser parser = builder.Build();

            return(await parser.InvokeAsync(args, console));
        }
        /// <summary>
        /// Configures the cli.
        /// </summary>
        /// <param name="configurationBuilder">The configuration builder.</param>
        public void ConfigureCli(IConfigurationBuilder configurationBuilder)
        {
            var rocketHostBuilder = RocketHostExtensions.GetConventionalHostBuilder(_hostBuilder);
            var clb = new CommandLineBuilder(
                rocketHostBuilder.Scanner,
                rocketHostBuilder.AssemblyProvider,
                rocketHostBuilder.AssemblyCandidateFinder,
                rocketHostBuilder.Logger,
                rocketHostBuilder.Properties
                );

            _exec = clb.Build().Parse(_args ?? Array.Empty <string>());
            _args = _exec.ApplicationState.RemainingArguments ?? Array.Empty <string>();
            configurationBuilder.AddApplicationState(_exec.ApplicationState);
            rocketHostBuilder.Properties.Add(typeof(ICommandLineExecutor), _exec);
        }