private static void AddGlobalOptions(RootCommand command)
    {
        if (command == null)
        {
            throw new ArgumentNullException(nameof(command));
        }

        // Path to the settings file, required
        command.AddGlobalOption(
            new Option <string>("--settingsfile")
        {
            Description = "Path to settings file",
            IsRequired  = true
        });

        // Path to the log file, optional
        command.AddGlobalOption(
            new Option <string>("--logfile")
        {
            Description = "Path to log file",
            IsRequired  = false
        });

        // Append to log vs. overwrite, optional
        command.AddGlobalOption(
            new Option <bool>("--logappend")
        {
            Description = "Append to the log file vs. default overwrite",
            IsRequired  = false
        });
    }
Exemple #2
0
    public static Task Main(string[] args)
    {
        var collectCommand = new Command("collect")
        {
            new Option <DirectoryInfo>("--directory", getDefaultValue: () => new DirectoryInfo(Directory.GetCurrentDirectory())),
            new Option <string>("--pattern", getDefaultValue: () => "*.jpg"),
            new Option <string>("--collectionID")
            {
                Required = true
            },
            new Option <bool>("--recurse", getDefaultValue: () => false),
        };

        var searchCommand = new Command("search")
        {
            new Option <DirectoryInfo>("--directory", getDefaultValue: () => new DirectoryInfo(Directory.GetCurrentDirectory())),
            new Option <string>("--pattern", getDefaultValue: () => "*.jpg"),
            new Option <string>("--collectionID")
            {
                Required = true
            },
            new Option <bool>("--recurse", getDefaultValue: () => false),
        };

        collectCommand.Handler = CommandHandler.Create <CollectOptions>(options => new CollectCommand(options).ExecuteAsync());
        searchCommand.Handler  = CommandHandler.Create <SearchOptions>(options => new SearchCommand(options).ExecuteAsync());

        var rootCommand = new RootCommand();

        rootCommand.Add(collectCommand);
        rootCommand.Add(searchCommand);

        rootCommand.AddGlobalOption(new Option <string>("--access-key", "Amazon Rekognition access key")
        {
            Required = true
        });
        rootCommand.AddGlobalOption(new Option <string>("--secret-key", "Amazon Rekognition secret key")
        {
            Required = true
        });

        var regionOption = new Option <RegionEndpoint>("--region",
                                                       new ParseArgument <RegionEndpoint>(target => RegionEndpoint.GetBySystemName(target.Tokens[0].Value)));

        regionOption.Description = "System name of an AWS region";
        regionOption.Required    = true;
        regionOption.WithSuggestions(RegionEndpoint.EnumerableAllRegions
                                     .Where(r => r.SystemName.StartsWith("eu-", StringComparison.OrdinalIgnoreCase))
                                     .Select(r => r.SystemName)
                                     .ToArray());

        rootCommand.AddGlobalOption(regionOption);

        rootCommand.Description = "Amazon Rekognition testing tool";

        return(rootCommand.InvokeAsync(args));
    }
Exemple #3
0
        private static RootCommand CreateRootCommand(Option <bool> whatIfOption, List <Option> imapConfigurationOptions, List <Command> commands)
        {
            var rootCommand = new RootCommand();

            rootCommand.Description = "IMAP cleanup tool. Will delete emails in the inbox, only keeping a given number of emails.";
            imapConfigurationOptions.ForEach(o => rootCommand.AddGlobalOption(o));
            rootCommand.AddGlobalOption(whatIfOption);
            commands.ForEach(command => rootCommand.Add(command));

            return(rootCommand);
        }
        private static CommandLineBuilder GetCommandLine()
        {
            RootCommand root = new RootCommand("parent")
            {
                Description = $"Microsoft IoT Models Repository CommandLine v{Outputs.CommandLineVersion}"
            };

            root.Name = Outputs.RootCommandName;
            root.Add(BuildExportCommand());
            root.Add(BuildValidateCommand());
            root.Add(BuildImportModelCommand());
            root.Add(BuildRepoIndexCommand());
            root.Add(BuildRepoExpandCommand());

            root.AddGlobalOption(CommonOptions.Debug);
            root.AddGlobalOption(CommonOptions.Silent);

            CommandLineBuilder builder = new CommandLineBuilder(root);

            builder.UseMiddleware(async(context, next) =>
            {
                AzureEventSourceListener listener = null;
                try
                {
                    if (context.ParseResult.Tokens.Any(x => x.Type == TokenType.Option && x.Value == "--debug"))
                    {
                        Outputs.WriteHeader();
                        listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose);
                        Outputs.WriteDebug(context.ParseResult.ToString());
                    }

                    if (context.ParseResult.Tokens.Any(x => x.Type == TokenType.Option && x.Value == "--silent"))
                    {
                        System.Console.SetOut(TextWriter.Null);
                    }

                    await next(context);
                }
                finally
                {
                    if (listener != null)
                    {
                        listener.Dispose();
                    }
                }
            });

            return(builder);
        }
        public void Validators_on_global_options_are_executed_when_invoking_a_subcommand(string commandLine)
        {
            var option = new Option <FileInfo>("--file");

            option.AddValidator(r =>
            {
                return("Invoked validator");
            });

            var subCommand  = new Command("subcommand");
            var rootCommand = new RootCommand
            {
                subCommand
            };

            rootCommand.AddGlobalOption(option);

            var result = rootCommand.Parse(commandLine);

            result.Errors
            .Should()
            .ContainSingle(e => e.SymbolResult.Symbol == option)
            .Which
            .Message
            .Should()
            .Be("Invoked validator");
        }
Exemple #6
0
        public static int Main(string[] args)
        {
            var rootCommand = new RootCommand
            {
                Name        = "learn-cli",
                Description = "Learning System.CommandLine arg parsing"
            };

            // General 'multiplier' available to all sub commands
            rootCommand.AddGlobalOption(new Option <int>("--multiplier", () => 1, "General multiplier (defaults to 1)"));

            // subcommand will parse a number string out print to output
            var parseCommand = new Command("parse", "Parsing operation")
            {
                Handler = CommandHandler.Create <string, int>(Parse),
            };

            rootCommand.AddCommand(parseCommand);
            // 'parse' requires a single argument that is a string
            parseCommand.AddArgument(new Argument("parseArg")
            {
                Arity = ArgumentArity.ExactlyOne
            }
                                     );

            return(rootCommand.Invoke(args));
        }
Exemple #7
0
        public async Task RunAsync(string args)
        {
            var rootCommand = new RootCommand
            {
                Name = "miru"
            };

            rootCommand.AddGlobalOption(
                new Option("--environment", "Executes command in the specified environment").WithAlias("--e"));

            foreach (var consolable in _consolable)
            {
                rootCommand.AddCommand(consolable);
            }

            var result = rootCommand.Parse(args);

            if (result.Errors.None() &&
                result.CommandResult.Command is not RootCommand &&
                result.CommandResult.Command is Command command)
            {
                using var scope = _app.Get <IServiceProvider>().CreateScope();

                var handlerType = command.GetType().Assembly.GetType($"{command.GetType().FullName}+ConsolableHandler");
                var handler     = (IConsolableHandler)scope.ServiceProvider.GetRequiredService(handlerType !);

                command.Handler = CommandHandler.Create(
                    handlerType.GetMethod(nameof(IConsolableHandler.Execute)) !,
                    handler);

                await result.InvokeAsync();
            }
        public async Task A_custom_validator_added_to_a_global_option_is_checked(string commandLine)
        {
            var handlerWasCalled = false;

            var globalOption = new Option <int>("--value");

            globalOption.AddValidator(option => "oops!");

            var grandchildCommand = new Command("grandchild");

            var childCommand = new Command("child")
            {
                grandchildCommand
            };
            var rootCommand = new RootCommand
            {
                childCommand
            };

            rootCommand.AddGlobalOption(globalOption);

            rootCommand.Handler       = CommandHandler.Create((int value) => handlerWasCalled = true);
            childCommand.Handler      = CommandHandler.Create((int value) => handlerWasCalled = true);
            grandchildCommand.Handler = CommandHandler.Create((int value) => handlerWasCalled = true);

            var result = await rootCommand.InvokeAsync(commandLine);

            result.Should().Be(1);
            handlerWasCalled.Should().BeFalse();
        }
Exemple #9
0
        static async Task <int> Main(string[] args)
        {
            // Root command
            var cmd = new RootCommand()
            {
                // Commands
                Marketplace.Command,
            };

            cmd.Handler = CommandHandler.Create <string>(Program.ExecuteCommand);

            // Global options
            cmd.AddGlobalOption(GlobalOptions.AppId);
            cmd.AddGlobalOption(GlobalOptions.Pem);

            return(await cmd.InvokeAsync(args));
        }
        public DefaultOptionsMiddlewareTests()
        {
            var command = new Command("xxx")
            {
                Handler = CommandHandler.Create((IConsole console, ParseResult result) =>
                {
                    foreach (var option in result.CommandResult.Children.OfType <OptionResult>())
                    {
                        console.Out.Write(option.Token.Value);
                        var argument = option.Children.OfType <ArgumentResult>().FirstOrDefault();
                        if (argument?.Tokens.Count > 0)
                        {
                            console.Out.Write($":{argument.Tokens[0].Value}");
                        }
                        console.Out.Write(" ");
                    }
                })
            };

            var subcommand = new Command("yyy");

            command.AddCommand(subcommand);

            var originalOption = new Option("--original");
            var defaultOption  = new Option("--default");
            var implicitOption = new Option("--implicit")
            {
                Argument = new Argument <bool>(() => false)
                {
                    Arity = ArgumentArity.ExactlyOne,
                },
            };

            var rootCommand = new RootCommand();

            rootCommand.AddGlobalOption(originalOption);
            rootCommand.AddGlobalOption(defaultOption);
            rootCommand.AddGlobalOption(implicitOption);
            rootCommand.AddGlobalOption(StandardOptions.NoDefaultOptions);
            rootCommand.AddCommand(command);

            _parser = new CommandLineBuilder(rootCommand)
                      .UseMiddleware(Program.DefaultOptionsMiddleware)
                      .Build();
        }
Exemple #11
0
        /// <summary>
        /// Runs the entry point using the command-line arguments.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        /// <returns>The exit code.</returns>
        public async Task <int> Run(string[] args)
        {
            var simulate = new Command("simulate", "(default) Run the program using a local simulator.")
            {
                Handler = CommandHandler.Create <ParseResult, string>(Simulate)
            };

            AddOptionIfAvailable(simulate, SimulatorOption);

            var submit = new Command("submit", "Submit the program to Azure Quantum.")
            {
                IsHidden = true,
                Handler  = CommandHandler.Create <ParseResult, AzureSettings>(Submit)
            };

            AddOptionIfAvailable(submit, SubscriptionOption);
            AddOptionIfAvailable(submit, ResourceGroupOption);
            AddOptionIfAvailable(submit, WorkspaceOption);
            AddOptionIfAvailable(submit, TargetOption);
            AddOptionIfAvailable(submit, StorageOption);
            AddOptionIfAvailable(submit, AadTokenOption);
            AddOptionIfAvailable(submit, BaseUriOption);
            AddOptionIfAvailable(submit, LocationOption);
            AddOptionIfAvailable(submit, JobNameOption);
            AddOptionIfAvailable(submit, ShotsOption);
            AddOptionIfAvailable(submit, OutputOption);
            AddOptionIfAvailable(submit, DryRunOption);
            AddOptionIfAvailable(submit, VerboseOption);
            MarkOptionsAsMutuallyExclusive(
                submit,
                new[] { BaseUriOption.Aliases.First(), LocationOption.Aliases.First() });

            var root = new RootCommand(entryPoint.Summary)
            {
                simulate, submit
            };

            foreach (var option in entryPoint.Options)
            {
                root.AddGlobalOption(option);
            }

            // Set the simulate command as the default.
            foreach (var option in simulate.Options)
            {
                root.AddOption(option);
            }
            root.Handler = simulate.Handler;

            Console.OutputEncoding = Encoding.UTF8;
            return(await new CommandLineBuilder(root)
                   .UseDefaults()
                   .UseHelpBuilder(context => new QsHelpBuilder(context.Console))
                   .Build()
                   .InvokeAsync(args));
        }
Exemple #12
0
        public static RootCommand Create(Delegate executor = null)
        {
            var cmd = new RootCommand(description: "Easily opt-out from telemetry collection.");

            cmd.AddGlobalOption(UserOptionsOption.Create());

            cmd.Handler = CommandHandler.Create(executor ?? new Func <string, int>(Execute));

            return(cmd);
        }
Exemple #13
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));
        }
    public void ThrowIfInvalid_throws_if_there_are_duplicate_sibling_global_option_aliases_on_the_root_command()
    {
        var option1 = new Option <string>("--dupe");
        var option2 = new Option <string>("-y");

        option2.AddAlias("--dupe");

        var command = new RootCommand();

        command.AddGlobalOption(option1);
        command.AddGlobalOption(option2);

        var config = new CommandLineConfiguration(command);

        var validate = () => config.ThrowIfInvalid();

        validate.Should()
        .Throw <CommandLineConfigurationException>()
        .Which
        .Message
        .Should()
        .Be($"Duplicate alias '--dupe' found on command '{command.Name}'.");
    }
Exemple #15
0
        private static CommandLineBuilder BuildCommandLine()
        {
            var rootCommand = new RootCommand("Egret")
            {
                // commands
                new Command("version", description: "get the version of egret"),
                new Command("test", "Run egret tests")
                {
                    configArg,
                    new Option <DirectoryInfo>("--output", description: "Set the directory to write reports to").WithAlias("-o"),
                    new Option <bool>("--json", description: "Output results to a json file").WithAlias("-j"),
                    new Option <bool>("--csv", description: "Output results to a CSV file").WithAlias("-c"),
                    new Option <bool>("--no-console", description: "Do not output results in the console").WithAlias("-q"),
                    new Option <bool>("--html", description: "Output results to a HTML file").WithAlias("-h"),
                    new Option <bool>("--sequential", description: "Disable parallel execution").WithAlias("-s"),
                },
                new Command("watch", "Runs egret tests every time a change is found")
                {
                    configArg,
                    new Option <bool>("--poll", "Use polling instead of filesystem events").WithAlias("-p")
                }
            };

            // global options
            rootCommand.AddGlobalOption(new Option <LogLevel>("--log-level", "Enable logging and the log level").WithAlias("-l"));
            rootCommand.AddGlobalOption(new Option <bool>("--verbose", "Enable logging at the debug level").WithAlias("-v"));
            rootCommand.AddGlobalOption(new Option <bool>("--very-verbose", "Enable logging at the trace level"));



            rootCommand.Handler = MainCommand.RunHandler;

            var builder = new CommandLineBuilder(rootCommand);


            return(builder);
        }
        public RootCommand Build()
        {
            var root = new RootCommand("The Messerli meta-generator is a versatile generator which can create files, projects, repositories with the right plugins!")
            {
                Handler = CommandHandler.Create <InvocationContext>(HandleContext),
            };

            root.AddGlobalOption(VerboseOption());

            RegisterPluginCommands(root);

            root.AddCommand(CreatePluginManagerCommands());

            return(root);
        }
Exemple #17
0
        private static RootCommand CreateCommands()
        {
            var rootCommand = new RootCommand("Harvest API Command Line Interface")
            {
                //CreateClientCommand(),
                //CreateProjectCommand(),
                CreateMyProjectCommand(),
                CreateTimeEntryCommand(),
                CreateTimerCommand(),
                Me.GetCommand(),
            };

            rootCommand.AddGlobalOption(new Option <bool>(new string[] { "--output-json", "-oj" }, "Output JSON"));

            return(rootCommand);
        }
        static async Task <int> Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            RootCommand rootCommand = new RootCommand();

            rootCommand.AddGlobalOption(new Option(new[] { "-v", "--verbose" }, "Enable verbosity"));

            AddCommand <RewriteCsprojCommandOptions>(rootCommand, RewriteCsprojCommandOptions.GetCommand());
            AddCommand <UndoRewiteCsprojCommandOptions>(rootCommand, UndoRewiteCsprojCommandOptions.GetCommand());
            AddCommand <UpdateSolutionCommandOptions>(rootCommand, UpdateSolutionCommandOptions.GetCommand());

            return(await rootCommand.InvokeAsync(args));
        }
        public static async Task Main(string[] args)
        {
            var rootCommand = new RootCommand("Execute a program and ensure there are no concurrent executions")
            {
                new RunDotNetCommand(),
                new RunExeCommand()
            };

            rootCommand.AddGlobalOption(CommonOptions.VerboseOption);

            await new CommandLineBuilder(rootCommand)
            .UseHost(_ => Host.CreateDefaultBuilder(), ConfigureHost)
            .UseDefaults()
            .Build()
            .InvokeAsync(args)
            .ConfigureAwait(false);
        }
    public void ThrowIfInvalid_does_not_throw_if_global_option_alias_is_the_same_as_subcommand_alias()
    {
        var rootCommand = new RootCommand
        {
            new Command("subcommand")
            {
                new Command("--dupe")
            }
        };

        rootCommand.AddGlobalOption(new Option <string>("--dupe"));

        var config = new CommandLineConfiguration(rootCommand);

        var validate = () => config.ThrowIfInvalid();

        validate.Should().NotThrow();
    }
        public void When_a_required_global_option_is_present_on_child_of_command_it_was_added_to_it_does_not_result_in_an_error()
        {
            var command     = new Command("child");
            var rootCommand = new RootCommand {
                command
            };

            command.SetHandler(() => { });
            var requiredOption = new Option <bool>("--i-must-be-set")
            {
                IsRequired = true
            };

            rootCommand.AddGlobalOption(requiredOption);

            var result = rootCommand.Parse("child --i-must-be-set");

            result.Errors.Should().BeEmpty();
        }
Exemple #22
0
        /// <summary>
        /// Runs the entry point.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        /// <returns>The exit code.</returns>
        private static async Task <int> Main(string[] args)
        {
            var simulate = new Command("simulate", "(default) Run the program using a local simulator.");

            TryCreateOption(
                Constants.SimulatorOptions,
                () => EntryPoint.DefaultSimulator,
                "The name of the simulator to use.").Then(option =>
            {
                option.Argument.AddSuggestions(ImmutableHashSet <string> .Empty
                                               .Add(Constants.QuantumSimulator)
                                               .Add(Constants.ToffoliSimulator)
                                               .Add(Constants.ResourcesEstimator)
                                               .Add(EntryPoint.DefaultSimulator));
                simulate.AddOption(option);
            });
            simulate.Handler = CommandHandler.Create <EntryPoint, string>(Simulate);

            var root = new RootCommand(EntryPoint.Summary)
            {
                simulate
            };

            foreach (var option in EntryPoint.Options)
            {
                root.AddGlobalOption(option);
            }

            // Set the simulate command as the default.
            foreach (var option in simulate.Options)
            {
                root.AddOption(option);
            }
            root.Handler = simulate.Handler;

            return(await new CommandLineBuilder(root)
                   .UseDefaults()
                   .UseHelpBuilder(context => new QsHelpBuilder(context.Console))
                   .Build()
                   .InvokeAsync(args));
        }
Exemple #23
0
        public static Task <int> Main(string[] args)
        {
            var command = new RootCommand()
            {
                Description = "Developer tools and publishing for microservices.",
            };

            command.AddGlobalOption(StandardOptions.NoDefaultOptions);

            command.AddCommand(CreateInitCommand());
            command.AddCommand(CreateGenerateCommand());
            command.AddCommand(CreateRunCommand());
            command.AddCommand(CreateBuildCommand());
            command.AddCommand(CreatePushCommand());
            command.AddCommand(CreateDeployCommand());
            command.AddCommand(CreateUndeployCommand());

            // 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);

            builder.UseMiddleware(DefaultOptionsMiddleware);

            var parser = builder.Build();

            return(parser.InvokeAsync(args));
        }
Exemple #24
0
        private static Parser BuildParser(IServiceProvider serviceProvider)
        {
            var rootCommand = new RootCommand();

            rootCommand.Description = $"Simplify nuget package administration.";

            rootCommand.AddGlobalOption(CommonOptions.SilentOption);

            var commandLineBuilder = new CommandLineBuilder(rootCommand);

            var commands = serviceProvider.GetServices <Command>();

            foreach (var command in commands)
            {
                commandLineBuilder.AddCommand(command);
            }

            return(commandLineBuilder
                   .UseDefaults()
                   .Build());
        }
Exemple #25
0
        public static Task <int> Main(string[] args)
        {
            var root = new RootCommand(CommandLineHost.GetEntryAssemblyDescription())
            {
                Handler = CommandLineHost.GetCommandHandler <ConsoleApplication>()
            };

            root.AddGlobalOption(new Option <string>(new[] { "--site", "-s" })
            {
                Name        = nameof(SharePointAuthorizationDiscoveryOptions.SiteUrl),
                Description = "SharePoint site URL",
                Argument    = { Name = "URL" }
            });

            var parser = new CommandLineBuilder(root)
                         .UseDefaults()
                         .UseHost(CreateHostBuilder)
                         .Build();

            return(parser.InvokeAsync(args ?? Array.Empty <string>()));
        }
Exemple #26
0
        private void ParseArgs(string[] args)
        {
            var rootCommand = new RootCommand
            {
                Description =
                    "Create or modify a PerfToolkit plug-in configuration file. If a directory is not " +
                    "specified, the current directory is assumed."
            };

            var verboseOption = new Option(
                new[] { "-v", "--verbose" },
                description: "Enable verbose logging");

            rootCommand.AddGlobalOption(verboseOption);

            var dirArgument = new Argument <string>(name: "dir", description: "Directory of configuration file.");

            rootCommand.AddCommand(CreateCommandCreate(dirArgument));
            rootCommand.AddCommand(CreateCommandPrint(dirArgument));
            rootCommand.AddCommand(CreateCommandAdd(dirArgument));
            rootCommand.AddCommand(CreateCommandDel(dirArgument));

            try
            {
                rootCommand.Invoke(args);
                if (_parsingException != null)
                {
                    throw _parsingException;
                }
            }
            catch (ConfigurationException e)
            {
                Logger.Error("{0}", e.Message);
            }
            catch (Exception e)
            {
                // We don't expect to hit this. If we do, the code should be updated to catch it at its source.
                Logger.Fatal($"Uncaught exception: {e}");
            }
        }
Exemple #27
0
        [Fact] // https://github.com/dotnet/command-line-api/issues/1563
        public void Command_GetCompletions_returns_available_option_aliases_for_global_options()
        {
            var subcommand = new Command("command")
            {
                new Option <string>("--one", "option one"),
                new Option <string>("--two", "option two")
            };

            var rootCommand = new RootCommand
            {
                subcommand
            };

            rootCommand.AddGlobalOption(new Option <string>("--three", "option three"));

            var completions = subcommand.GetCompletions();

            completions
            .Select(item => item.Label)
            .Should()
            .BeEquivalentTo("--one", "--two", "--three");
        }
        [Fact] // https://github.com/dotnet/command-line-api/issues/1540
        public void When_a_required_global_option_is_omitted_it_results_in_an_error()
        {
            var command     = new Command("child");
            var rootCommand = new RootCommand {
                command
            };

            command.SetHandler(() => { });
            var requiredOption = new Option <bool>("--i-must-be-set")
            {
                IsRequired = true
            };

            rootCommand.AddGlobalOption(requiredOption);

            var result = rootCommand.Parse("child");

            result.Errors
            .Should()
            .ContainSingle()
            .Which.Message.Should().Be("Option '--i-must-be-set' is required.");
        }
Exemple #29
0
    static async Task GlobalOption(string[] args)
    {
        // <defineglobal>
        var delayOption = new Option <int>
                              ("--delay", "An option whose argument is parsed as an int.");
        var messageOption = new Option <string>
                                ("--message", "An option whose argument is parsed as a string.");

        var rootCommand = new RootCommand();

        rootCommand.AddGlobalOption(delayOption);
        rootCommand.Add(messageOption);

        var subCommand1 = new Command("sub1", "First level subcommand");

        rootCommand.Add(subCommand1);

        var subCommand1a = new Command("sub1a", "Second level subcommand");

        subCommand1.Add(subCommand1a);

        subCommand1a.SetHandler((int delayOptionValue) =>
        {
            Console.WriteLine($"--delay = {delayOptionValue}");
        },
                                delayOption);

        await rootCommand.InvokeAsync(args);

        // </defineglobal>

        Console.WriteLine("Request help for second level subcommand.");
        await rootCommand.InvokeAsync("sub1 sub1a -h");

        Console.WriteLine("Global option in second level subcommand.");
        await rootCommand.InvokeAsync("sub1 sub1a --delay 42");
    }
Exemple #30
0
        public static int Main(string[] args)
        {
            // Root Command (psburn)
            var RootCommand = new RootCommand("psburn is cross platform tool to compile dynamic powershell scripts into platform specific executables " +
                                              "by encapsulating it inside a c# or python program.");

            // Global Options
            RootCommand.AddGlobalOption(new Option <string>(
                                            aliases: new string[] { "-o", "--output" },
                                            getDefaultValue: () => "working directory",
                                            description: "path of output files")
                                        );

            RootCommand.AddGlobalOption(new Option <bool>(
                                            aliases: new string[] { "-v", "--verbose" },
                                            getDefaultValue: () => false,
                                            description: "generate more outputs and logs than usual")
                                        );

            // Child Command (create)
            var ChildCommandCreate = new Command("create", "create a psburn c# file");

            RootCommand.AddCommand(ChildCommandCreate);

            // Child Command (create) - Arguments
            ChildCommandCreate.AddArgument(new Argument <string>("psscript", "path of powershell script"));

            // Child Command (create) - Options
            ChildCommandCreate.AddOption(new Option <bool>(
                                             aliases: new string[] { "-e", "--experimental" },
                                             getDefaultValue: () => false,
                                             description: "use experimental features to create script")
                                         );

            ChildCommandCreate.AddOption(new Option <string>(
                                             aliases: new string[] { "--execution-policy" },
                                             getDefaultValue: () => "Bypass",
                                             description: "execution policy for the powershell script")
                                         );

            ChildCommandCreate.AddOption(new Option <string>(
                                             aliases: new string[] { "--script-name" },
                                             getDefaultValue: () => "basename of input file",
                                             description: "set name of script")
                                         );

            ChildCommandCreate.AddOption(new Option <string>(
                                             aliases: new string[] { "--script-version" },
                                             getDefaultValue: () => "1.0.0",
                                             description: "set version of script")
                                         );

            ChildCommandCreate.AddOption(new Option <bool>(
                                             aliases: new string[] { "--blockcat" },
                                             getDefaultValue: () => false,
                                             description: "block cating of script which prevents script exposure")
                                         );

            ChildCommandCreate.AddOption(new Option <bool>(
                                             aliases: new string[] { "--self-contained" },
                                             getDefaultValue: () => false,
                                             description: "enable this option if you are using --powershell-zip")
                                         );

            ChildCommandCreate.AddOption(new Option <bool>(
                                             aliases: new string[] { "--onedir" },
                                             getDefaultValue: () => false,
                                             description: "run powershell from current directory")
                                         );

            ChildCommandCreate.AddOption(new Option <bool>(
                                             aliases: new string[] { "--embed-resources" },
                                             getDefaultValue: () => false,
                                             description: "enable this option if you are using --resources-zip")
                                         );

            ChildCommandCreate.AddOption(new Option <bool>(
                                             aliases: new string[] { "--no-extract" },
                                             getDefaultValue: () => false,
                                             description: "this option allows to host scripts purely from program instead of extracted version of them")
                                         );

            ChildCommandCreate.Handler = CommandHandler.Create <string, bool, string, string, string, bool, bool, bool, bool, bool, string, bool>(PsburnCommand.Create);

            // Child Command (cross)
            var ChildCommandCross = new Command("cross", "create a psburn py script");

            RootCommand.AddCommand(ChildCommandCross);

            // Child Command (cross) - Arguments
            ChildCommandCross.AddArgument(new Argument <string>("psscript", "path of powershell script"));

            // Child Command (cross) - Options
            ChildCommandCross.AddOption(new Option <string>(
                                            aliases: new string[] { "--execution-policy" },
                                            getDefaultValue: () => "Bypass",
                                            description: "execution policy for the powershell script")
                                        );

            ChildCommandCross.AddOption(new Option <bool>(
                                            aliases: new string[] { "--blockcat" },
                                            getDefaultValue: () => false,
                                            description: "block cating of script which prevents script exposure")
                                        );

            ChildCommandCross.AddOption(new Option <bool>(
                                            aliases: new string[] { "--onedir" },
                                            getDefaultValue: () => false,
                                            description: "run powershell from current directory")
                                        );

            ChildCommandCross.Handler = CommandHandler.Create <string, string, bool, bool, string, bool>(PsburnCommand.Cross);

            // Child Command (build)
            var ChildCommandBuild = new Command("build", "build an executable from c# program");

            RootCommand.AddCommand(ChildCommandBuild);

            // Child Command (build) - Arguments
            ChildCommandBuild.AddArgument(new Argument <string>("csfile", "path of c# file"));
            ChildCommandBuild.AddArgument(new Argument <string>("psscript", "path of powershell script"));

            // Child Command (build) - Options
            ChildCommandBuild.AddOption(new Option <bool>(
                                            aliases: new string[] { "-d", "--debug" },
                                            getDefaultValue: () => false,
                                            description: "don't delete runtime generated files")
                                        );

            ChildCommandBuild.AddOption(new Option <string>(
                                            aliases: new string[] { "-p", "--powershell-zip" },
                                            getDefaultValue: () => "no zip",
                                            description: "create a self contained executable")
                                        );

            ChildCommandBuild.AddOption(new Option <string>(
                                            aliases: new string[] { "-r", "--resources-zip" },
                                            getDefaultValue: () => "no zip",
                                            description: "embed resources from a zip file")
                                        );

            ChildCommandBuild.AddOption(new Option <string>(
                                            aliases: new string[] { "--cscpath" },
                                            getDefaultValue: () => "auto detect",
                                            description: "c# compiler path (C:\\Windows\\Microsoft.Net\\Framework\\<version>\\csc.exe)")
                                        );

            ChildCommandBuild.AddOption(new Option <string>(
                                            aliases: new string[] { "--icon" },
                                            getDefaultValue: () => "no icon",
                                            description: "apply icon to generated executable")
                                        );

            ChildCommandBuild.AddOption(new Option <bool>(
                                            aliases: new string[] { "--no-console" },
                                            getDefaultValue: () => false,
                                            description: "create executable without a console, this helps for running scripts in background for gui programs")
                                        );

            ChildCommandBuild.AddOption(new Option <bool>(
                                            aliases: new string[] { "--uac-admin" },
                                            getDefaultValue: () => false,
                                            description: "request elevation upon application restart (windows specific)")
                                        );

            ChildCommandBuild.AddOption(new Option <bool>(
                                            aliases: new string[] { "--onedir" },
                                            getDefaultValue: () => false,
                                            description: "run powershell from current directory")
                                        );

            ChildCommandBuild.Handler = CommandHandler.Create <string, string, bool, string, string, string, string, bool, bool, bool, string, bool>(PsburnCommand.Build);

            // Child Command (cbuild)
            var ChildCommandCBuild = new Command("cbuild", "build an executable from python script");

            RootCommand.AddCommand(ChildCommandCBuild);

            // Child Command (cbuild) - Arguments
            ChildCommandCBuild.AddArgument(new Argument <string>("pyscript", "path of python script"));
            ChildCommandCBuild.AddArgument(new Argument <string>("psscript", "path of powershell script"));

            // Child Command (cbuild) - Options
            ChildCommandCBuild.AddOption(new Option <bool>(
                                             aliases: new string[] { "-d", "--debug" },
                                             getDefaultValue: () => false,
                                             description: "don't delete runtime generated files")
                                         );

            ChildCommandCBuild.AddOption(new Option <string>(
                                             aliases: new string[] { "-p", "--powershell-zip" },
                                             getDefaultValue: () => "no zip",
                                             description: "create a self contained executable")
                                         );

            ChildCommandCBuild.AddOption(new Option <string>(
                                             aliases: new string[] { "-r", "--resources-zip" },
                                             getDefaultValue: () => "no zip",
                                             description: "embed resources from a zip file")
                                         );

            ChildCommandCBuild.AddOption(new Option <bool>(
                                             aliases: new string[] { "--onedir" },
                                             getDefaultValue: () => false,
                                             description: "run powershell from current directory")
                                         );

            ChildCommandCBuild.AddOption(new Option <bool>(
                                             aliases: new string[] { "--no-prompt" },
                                             getDefaultValue: () => false,
                                             description: "don't ask for any prompts")
                                         );

            ChildCommandCBuild.Handler = CommandHandler.Create <string, string, bool, string, string, bool, bool, string, bool>(PsburnCommand.CBuild);

            return(RootCommand.InvokeAsync(args).Result);
        }