Esempio n. 1
0
    static async Task Main(string[] args)
    {
        var delayOption   = new Option <int>("--delay");
        var messageOption = new Option <string>("--message");

        var rootCommand = new RootCommand("Middleware example");

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

        rootCommand.SetHandler((int delayOptionValue, string messageOptionValue) =>
        {
            DoRootCommand(delayOptionValue, messageOptionValue);
        },
                               delayOption, messageOption);

        // <middleware>
        var commandLineBuilder = new CommandLineBuilder(rootCommand);

        commandLineBuilder.AddMiddleware(async(context, next) =>
        {
            if (context.ParseResult.Directives.Contains("just-say-hi"))
            {
                context.Console.WriteLine("Hi!");
            }
            else
            {
                await next(context);
            }
        });

        commandLineBuilder.UseDefaults();
        var parser = commandLineBuilder.Build();
        await parser.InvokeAsync("[just-say-hi] --delay 42 --message \"Hello world!\"");

        // </middleware>
    }
Esempio n. 2
0
        static int Main(string[] args)
        {
            // Create a root command with some options
            var rootCommand = new RootCommand
            {
                new Option(
                    "--int-option",
                    "An option whose argument is parsed as an int")
                {
                    Argument = new Argument <int>(defaultValue: () => 42)
                },
                new Option(
                    "--bool-option",
                    "An option whose argument is parsed as a bool")
                {
                    Argument = new Argument <bool>()
                },
                new Option(
                    "--file-option",
                    "An option whose argument is parsed as a FileInfo")
                {
                    Argument = new Argument <FileInfo>()
                }
            };

            rootCommand.Description = "My sample app";

            rootCommand.Handler = CommandHandler.Create <int, bool, FileInfo>((intOption, boolOption, fileOption) =>
            {
                Console.WriteLine($"The value for --int-option is: {intOption}");
                Console.WriteLine($"The value for --bool-option is: {boolOption}");
                Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
            });

            // Parse the incoming args and invoke the handler
            return(rootCommand.InvokeAsync(args).Result);
        }
Esempio n. 3
0
        public static void Main(string[] args)
        {
            var rootCommand = new RootCommand
            {
                new Option("--list", "List all audio devices"),
                new Option <string>("--set", "Set device"),
                new Option <string>("--set-comm", "Set communication device")
            };

            rootCommand.Description = "AudioDeviceSelector";

            // Note that the parameters of the handler method are matched according to the names of the options
            rootCommand.Handler = CommandHandler.Create <string, string>(
                (set, setComm) =>
            {
                var controller = new CoreAudioController();
                var devices    = controller.GetDevices();

                if (args.Count() < 1)
                {
                    Console.WriteLine($"{Assembly.GetExecutingAssembly().GetName().Name}.exe --help");
                }

                if (args.Any(x => x.ToString().ToLower() == "--list"))
                {
                    devices
                    .OrderBy(d => d.DeviceType)
                    .ToList()
                    .ForEach(d => Console.WriteLine($"DeviceType: {d.DeviceType}, Id: {d.Id}, InterfaceName: {d.InterfaceName}, Name: {d.Name}"));
                }

                _ = set != null && controller.SetDeviceByName(set);
                _ = setComm != null && controller.SetCommDeviceByName(setComm);
            });

            rootCommand.Invoke(args);
        }
Esempio n. 4
0
            public void An_option_can_have_multiple_parents_with_the_same_name()
            {
                var option = new Option <string>("--the-option");

                var sprocket = new Command("sprocket")
                {
                    new Command("add")
                    {
                        option
                    }
                };

                var widget = new Command("widget")
                {
                    new Command("add")
                    {
                        option
                    }
                };

                var root = new RootCommand
                {
                    sprocket,
                    widget
                };

                option.Parents
                .Select(p => p.Name)
                .Should()
                .BeEquivalentTo("add", "add");

                option.Parents
                .SelectMany(p => p.Parents)
                .Select(p => p.Name)
                .Should()
                .BeEquivalentTo("sprocket", "widget");
            }
                public void When_option_is_not_respecified_and_limit_is_reached_then_the_following_token_is_unmatched()
                {
                    var animalsOption = new Option(new[] { "-a", "--animals" })
                    {
                        AllowMultipleArgumentsPerToken = true,
                        Arity = ArgumentArity.ZeroOrOne
                    };
                    var vegetablesOption = new Option(new[] { "-v", "--vegetables" })
                    {
                        Arity = ArgumentArity.ZeroOrMore
                    };

                    var command = new RootCommand
                    {
                        animalsOption,
                        vegetablesOption
                    };

                    var result = command.Parse("-a cat some-arg -v carrot");

                    result.FindResultFor(animalsOption)
                    .Tokens
                    .Select(t => t.Value)
                    .Should()
                    .BeEquivalentTo("cat");

                    result.FindResultFor(vegetablesOption)
                    .Tokens
                    .Select(t => t.Value)
                    .Should()
                    .BeEquivalentTo("carrot");

                    result
                    .UnmatchedTokens
                    .Should()
                    .BeEquivalentTo("some-arg");
                }
Esempio n. 6
0
        private static Task <int> Main(string[] args)
        {
            var toolDirectory    = AppDomain.CurrentDomain.BaseDirectory;
            var workingDirectory = Directory.GetCurrentDirectory();
            var version          = Assembly.GetExecutingAssembly().GetName().Version;

            Console.WriteLine($@"
{asciiart}
tool directory: { toolDirectory }
work directory: { workingDirectory }
tool version  : {version.Major}.{version.Minor}.{version.Build}
            ");

            var service     = GetService(workingDirectory);
            var rootCommand = new RootCommand {
                new Option("--config-file")
                {
                    Argument = new Argument <string>()
                }
            };

            rootCommand.Description = "larnaca mssql collector";

            rootCommand.Handler = CommandHandler.Create <string>(async(configFile) =>
            {
                var resp = await service.WriteDatabaseMetaToFile(workingDirectory);

                Console.WriteLine(resp.StatusMessage);
                if (resp.Fail())
                {
                    Environment.Exit(resp.StatusCode);
                }
            });

            // Parse the incoming args and invoke the handler
            return(rootCommand.InvokeAsync(args));
        }
Esempio n. 7
0
        private static int Main(string[] args)
        {
            System.Console.WriteLine("====================================================");
            System.Console.WriteLine($"{SokoSolveApp.Name} :: v{SokoSolveApp.Version}");
            System.Console.WriteLine(DevHelper.FullDevelopmentContext());
            System.Console.WriteLine("----------------------------------------------------");
            System.Console.WriteLine();

            var root = new RootCommand();

            root.AddCommand(BenchmarkCommand.GetCommand());

            //------------------------------------------------------------------------------------------------------------
            var play = new Command("play", "Play SokoSolve game in the console")
            {
                Handler = CommandHandler.Create(PlayCommand.Run)
            };

            root.AddCommand(play);
            //------------------------------------------------------------------------------------------------------------
            var micro = new Command("micro", "Micro Benchmarks (BenchmarkDotNet)")
            {
                new Argument <string>(() => "BaseLineSolvers")
                {
                    Name        = "target",
                    Description = "Target Type"
                },
            };

            micro.Handler = CommandHandler.Create <string>(MicroCommand.Run);
            root.AddCommand(micro);
            //------------------------------------------------------------------------------------------------------------

            root.Add(AnalyseCommand.GetCommand());

            return(root.Invoke(args));
        }
Esempio n. 8
0
        public static Task <int> Main(string[] args)
        {
            var command = new RootCommand()
            {
                Description = "Developer tools and publishing for microservices.",
            };

            command.AddCommand(CreateInitCommand());
            command.AddCommand(CreateGenerateCommand());
            command.AddCommand(CreateRunCommand(args));
            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);

            var parser = builder.Build();

            return(parser.InvokeAsync(args));
        }
        public void All_custom_validators_are_called(string commandLine)
        {
            var commandValidatorWasCalled  = false;
            var optionValidatorWasCalled   = false;
            var argumentValidatorWasCalled = false;

            var option = new Option <string>("-o");

            option.AddValidator(_ =>
            {
                optionValidatorWasCalled = true;
            });

            var argument = new Argument <string>("the-arg");

            argument.AddValidator(_ =>
            {
                argumentValidatorWasCalled = true;
            });

            var rootCommand = new RootCommand
            {
                option,
                argument
            };

            rootCommand.AddValidator(_ =>
            {
                commandValidatorWasCalled = true;
            });

            rootCommand.Invoke(commandLine);

            commandValidatorWasCalled.Should().BeTrue();
            optionValidatorWasCalled.Should().BeTrue();
            argumentValidatorWasCalled.Should().BeTrue();
        }
Esempio n. 10
0
        public void Batch_Query_UpdateFail(string batchMethod, string settingsFile)
        {
            string overrideFile = Path.GetFullPath("TestConfig/databasetargets.cfg");
            string outputFile   = Path.GetFullPath($"{Guid.NewGuid().ToString()}.csv");
            string updatequery  = Path.GetFullPath("updatequery.sql");

            if (!File.Exists(updatequery))
            {
                File.WriteAllText(updatequery, Properties.Resources.updatequery);
            }
            //get the size of the log file before we start
            int startingLine = LogFileCurrentLineCount();

            settingsFile = Path.GetFullPath(settingsFile);
            var args = new string[] {
                "batch", batchMethod,
                "--settingsfile", settingsFile,
                "--settingsfilekey", this.settingsFileKeyPath,
                "--override", overrideFile,
                "--outputfile", outputFile,
                "--queryfile", updatequery,
                "--silent"
            };

            RootCommand rootCommand = CommandLineBuilder.SetUp();
            var         val         = rootCommand.InvokeAsync(args);

            val.Wait();
            var result = val.Result;

            ;

            var logFileContents = ReleventLogFileContents(startingLine);

            Assert.AreEqual(5, result, StandardExecutionErrorMessage(logFileContents));
            //Assert.IsTrue(logFileContents.Contains("An INSERT, UPDATE or DELETE keyword was found"), "An UPDATE statement should have been found");
        }
Esempio n. 11
0
    static async Task FileSystemInfoExample(string[] args)
    {
        // <filesysteminfo>
        var fileOrDirectoryOption = new Option <FileSystemInfo>("--file-or-directory");

        var command = new RootCommand();

        command.Add(fileOrDirectoryOption);

        command.SetHandler(
            (FileSystemInfo? fileSystemInfo) =>
        {
            switch (fileSystemInfo)
            {
            case FileInfo file:
                Console.WriteLine($"File name: {file.FullName}");
                break;

            case DirectoryInfo directory:
                Console.WriteLine($"Directory name: {directory.FullName}");
                break;

            default:
                Console.WriteLine("Not a valid file or directory name.");
                break;
            }
        }, fileOrDirectoryOption);

        await command.InvokeAsync(args);

        // </filesysteminfo>
        await command.InvokeAsync("--file-or-directory scl.runtimeconfig.json");

        await command.InvokeAsync("--file-or-directory ../net6.0");

        await command.InvokeAsync("--file-or-directory newfile.json");
    }
        static void Main(string[] args)
        {
            System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.High;

            var rootCommand = new RootCommand("Benchmarks scatter/gather")
            {
                TreatUnmatchedTokensAsErrors = true,
            };

            var remoteCommand = new Command("r", "Runs the remote host.");

            remoteCommand.AddOption(new Option <string>("--ip", "The IP to bind to."));
            remoteCommand.AddOption(new Option <int>("--port", "The port to bind to."));
            remoteCommand.Handler = CommandHandler.Create <string, int>((ip, port) =>
            {
                if (ip == null)
                {
                    ip = "::1";
                }
                RunRemoteHost(ip, port);
            });

            var benchmarkCommand = new Command("b", "Runs the benchmark.");

            benchmarkCommand.AddOption(new Option <string>("--host", "The host to connect to.")
            {
                IsRequired = true
            });
            benchmarkCommand.Handler = CommandHandler.Create <string>(host =>
            {
                new Program().RunBenchmarkAsync(host).AsTask().GetAwaiter().GetResult();
            });

            rootCommand.AddCommand(remoteCommand);
            rootCommand.AddCommand(benchmarkCommand);
            rootCommand.Invoke(args);
        }
Esempio n. 13
0
        public void When_response_file_parse_as_space_separated_returns_expected_values(string input)
        {
            var responseFile = ResponseFile(input);

            var rootCommand = new RootCommand
            {
                new Option("--flag")
                {
                    Argument = new Argument <string>()
                },
                new Option("--flag2")
                {
                    Argument = new Argument <int>()
                }
            };
            var parser = new CommandLineBuilder(rootCommand)
                         .ParseResponseFileAs(ResponseFileHandling.ParseArgsAsSpaceSeparated)
                         .Build();

            var result = parser.Parse($"@{responseFile}");

            result.ValueForOption("--flag").Should().Be("first value");
            result.ValueForOption("--flag2").Should().Be(123);
        }
        public static int Main(string[] args)
        {
            RootCommand rootCommand = CommandLineUtilities.GenerateRootCommand();

            rootCommand.Handler = CommandHandler.Create <Configuration>((config) =>
            {
                BenchmarkCoordinator.Config = config;
                var mode = config.Benchmark;


                if (mode == BenchmarkMode.Custom)
                {
                    Console.Write(config.ToFormattedString());
                    RunCustomBenchmark();
                    return(0);
                }

                Console.Write(config.ExecutionEnvironmentToString());
                RunPredefinedBenchmarks(mode);
                return(0);
            });

            return(rootCommand.Invoke(args));
        }
Esempio n. 15
0
        public void Parser_options_can_supply_context_sensitive_matches()
        {
            var parser = new RootCommand
            {
                new Option("--bread", arity: ArgumentArity.ExactlyOne)
                .FromAmong("wheat", "sourdough", "rye"),
                new Option("--cheese", arity: ArgumentArity.ExactlyOne)
                .FromAmong("provolone", "cheddar", "cream cheese")
            };

            var commandLine = "--bread";
            var result      = parser.Parse(commandLine);

            result.GetSuggestions(commandLine.Length + 1)
            .Should()
            .BeEquivalentTo("rye", "sourdough", "wheat");

            commandLine = "--bread wheat --cheese ";
            result      = parser.Parse(commandLine);

            result.GetSuggestions(commandLine.Length + 1)
            .Should()
            .BeEquivalentTo("cheddar", "cream cheese", "provolone");
        }
Esempio n. 16
0
        public static RootCommand RootCommand()
        {
            RootCommand command = new RootCommand();

            command.AddOption(new Option <FileInfo[]>(new[] { "--in", "-i" }, "Input file(s) to dump. Expects them to by ReadyToRun images"));
            command.AddOption(new Option <FileInfo>(new[] { "--out", "-o" }, "Output file path. Dumps everything to the specified file except for help message and exception messages"));
            command.AddOption(new Option <bool>(new[] { "--raw" }, "Dump the raw bytes of each section or runtime function"));
            command.AddOption(new Option <bool>(new[] { "--header" }, "Dump R2R header"));
            command.AddOption(new Option <bool>(new[] { "--disasm", "-d" }, "Show disassembly of methods or runtime functions"));
            command.AddOption(new Option <bool>(new[] { "--naked" }, "Naked dump suppresses most compilation details like placement addresses"));
            command.AddOption(new Option <bool>(new[] { "--hide-offsets", "--ho" }, "Hide offsets in naked disassembly"));
            command.AddOption(new Option <string[]>(new[] { "--query", "-q" }, "Query method by exact name, signature, row ID or token"));
            command.AddOption(new Option <string[]>(new[] { "--keyword", "-k" }, "Search method by keyword"));
            command.AddOption(new Option <string[]>(new[] { "--runtimefunction", "-f" }, "Get one runtime function by id or relative virtual address"));
            command.AddOption(new Option <string[]>(new[] { "--section", "-s" }, "Get section by keyword"));
            command.AddOption(new Option <bool>(new[] { "--unwind" }, "Dump unwindInfo"));
            command.AddOption(new Option <bool>(new[] { "--gc" }, "Dump gcInfo and slot table"));
            command.AddOption(new Option <bool>(new[] { "--pgo" }, "Dump embedded pgo instrumentation data"));
            command.AddOption(new Option <bool>(new[] { "--sectionContents", "--sc" }, "Dump section contents"));
            command.AddOption(new Option <bool>(new[] { "--entrypoints", "-e" }, "Dump list of method / instance entrypoints in the R2R file"));
            command.AddOption(new Option <bool>(new[] { "--normalize", "-n" }, "Normalize dump by sorting the various tables and methods (default = unsorted i.e. file order)"));
            command.AddOption(new Option <bool>(new[] { "--hide-transitions", "--ht" }, "Don't include GC transitions in disassembly output"));
            command.AddOption(new Option <bool>(new[] { "--verbose", "-v" }, "Dump disassembly, unwindInfo, gcInfo and sectionContents"));
            command.AddOption(new Option <bool>(new[] { "--diff" }, "Compare two R2R images"));
            command.AddOption(new Option <bool>(new[] { "--diff-hide-same-disasm" }, "In matching method diff dump, hide functions with identical disassembly"));
            command.AddOption(new Option <FileInfo[]>(new[] { "--reference", "-r" }, "Explicit reference assembly files"));
            command.AddOption(new Option <DirectoryInfo[]>(new[] { "--referencePath", "--rp" }, "Search paths for reference assemblies"));
            command.AddOption(new Option <bool>(new[] { "--inlineSignatureBinary", "--isb" }, "Embed binary signature into its textual representation"));
            command.AddOption(new Option <bool>(new[] { "--signatureBinary", "--sb" }, "Append signature binary to its textual representation"));
            command.AddOption(new Option <bool>(new[] { "--create-pdb" }, "Create PDB"));
            command.AddOption(new Option <string>(new[] { "--pdb-path" }, "PDB output path for --create-pdb"));
            command.AddOption(new Option <bool>(new[] { "--create-perfmap" }, "Create PerfMap"));
            command.AddOption(new Option <string>(new[] { "--perfmap-path" }, "PerfMap output path for --create-perfmap"));
            command.AddOption(new Option <int>(new[] { "--perfmap-format-version" }, "PerfMap format version for --create-perfmap"));
            return(command);
        }
        internal static async Task <int> MultipleArgs()
        {
            #region MultipleArgs

            var command = new RootCommand
            {
                new Option <string>("--a-string"),
                new Option <int>("--an-int")
            };

            command.Handler = CommandHandler.Create(
                (string aString, int anInt) =>
            {
                Console.WriteLine($"{aString}");
                Console.WriteLine($"{anInt}");
            }
                );

            await command.InvokeAsync("--an-int 123 --a-string \"Hello world!\" ");

            #endregion

            return(0);
        }
Esempio n. 18
0
        public void When_a_subcommand_has_been_specified_then_its_sibling_commands_will_not_be_suggested()
        {
            var rootCommand = new RootCommand
            {
                new Command("apple")
                {
                    new Option("--cortland")
                },
                new Command("banana")
                {
                    new Option("--cavendish")
                },
                new Command("cherry")
                {
                    new Option("--rainier")
                }
            };

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

            result.GetSuggestions()
            .Should()
            .NotContain(new[] { "apple", "banana", "cherry" });
        }
Esempio n. 19
0
        public static void UseHost_binds_parsed_arguments_to_options()
        {
            const int myValue     = 4224;
            string    commandLine = $"-{nameof(MyOptions.MyArgument)} {myValue}";
            MyOptions options     = null;

            var rootCmd = new RootCommand();

            rootCmd.AddOption(
                new Option($"-{nameof(MyOptions.MyArgument)}")
            {
                Argument = new Argument <int>()
            }
                );
            rootCmd.Handler = CommandHandler.Create((IHost host) =>
            {
                options = host.Services
                          .GetRequiredService <IOptions <MyOptions> >()
                          .Value;
            });

            int result = new CommandLineBuilder(rootCmd)
                         .UseHost(host =>
            {
                host.ConfigureServices(services =>
                {
                    services.AddOptions <MyOptions>().BindCommandLine();
                });
            })
                         .Build()
                         .Invoke(commandLine);

            Assert.Equal(0, result);
            Assert.NotNull(options);
            Assert.Equal(myValue, options.MyArgument);
        }
Esempio n. 20
0
        public void Default_values_from_options_with_the_same_type_are_bound_and_use_their_own_defaults()
        {
            int first = 0, second = 0;

            var rootCommand = new RootCommand
            {
                new Option <int>("one", () => 1),
                new Option <int>("two", () => 2)
            };

            rootCommand.Handler = CommandHandler.Create <int, int>((one, two) =>
            {
                first  = one;
                second = two;
            });

            var parser = new CommandLineBuilder(rootCommand)
                         .Build();

            parser.Invoke("");

            first.Should().Be(1);
            second.Should().Be(2);
        }
Esempio n. 21
0
        public static int Main(string[] args)
        {
            var rootcmd = new RootCommand("Audiobookbuilder")
            {
                new Option <DirectoryInfo>("--d", () => new DirectoryInfo(Directory.GetCurrentDirectory()), "directory"),
                new Option <bool>("--r", "Create audiobooks recursivly")
            };


            rootcmd.Handler = CommandHandler.Create <DirectoryInfo, bool>((d, r) => {
                var folders = new List <DirectoryInfo>();

                if (r)
                {
                    folders.AddRange(d.EnumerateDirectories("*", SearchOption.AllDirectories));
                }
                else
                {
                    folders.Add(d);
                }

                Parallel.ForEach(folders, folder => {
                    Console.WriteLine($"Begin Convert {folder.Name}");
                    var result = AudioConverter.Convert(folder);
                    if (result == null)
                    {
                        Console.WriteLine($"Nothing to do for folder: {folder.Name}");
                    }
                    else
                    {
                        Console.WriteLine($"Convert Done for: {folder.Name} Created File {result.Name}");
                    }
                });
            });
            return(rootcmd.InvokeAsync(args).Result);
        }
Esempio n. 22
0
        /// <summary>
        /// Some useful tools for writers
        ///
        /// </summary>
        public static int Main(string[] args)
        {
            var rootOption = new Option("--root", "The location of the project folder. Defaults to current directory.")
            {
                Argument = new Argument <string>(getDefaultValue: () => Directory.GetCurrentDirectory())
            };

            var verboseOption = new Option("--verbose", "wtk tries to be silent unless you're in verbose mode.")
            {
                Argument = new Argument <bool>(getDefaultValue: () => false)
            };

            var rootCommand = new RootCommand("A bunch of useful writing tools");

            rootCommand.AddOption(rootOption);
            rootCommand.AddOption(verboseOption);
            rootCommand.AddCommand(Init());
            rootCommand.AddCommand(Count());
            rootCommand.AddCommand(Compile());
            rootCommand.AddCommand(Status());
            rootCommand.AddCommand(Todo());
            rootCommand.AddCommand(Config());
            return(rootCommand.InvokeAsync(args).Result);
        }
Esempio n. 23
0
        /// <summary>
        /// Build the RootCommand for parsing
        /// </summary>
        /// <returns>RootCommand</returns>
        public static RootCommand BuildRootCommand()
        {
            RootCommand root = new RootCommand
            {
                Name        = "helium",
                Description = "helium-csharp web app",
                TreatUnmatchedTokensAsErrors = true,
            };

            // add options
            Option optKv = new Option <string>(new string[] { "-k", "--keyvault-name" }, "The name or URL of the Azure Keyvault")
            {
                Argument   = new Argument <string>(),
                IsRequired = true,
            };

            optKv.AddValidator(v =>
            {
                if (v.Tokens == null ||
                    v.Tokens.Count != 1 ||
                    !KeyVaultHelper.ValidateName(v.Tokens[0].Value))
                {
                    return("--keyvault-name must be 3-20 characters [a-z][0-9]");
                }

                return(string.Empty);
            });

            // add the options
            root.AddOption(optKv);
            root.AddOption(new Option <AuthenticationType>(new string[] { "-a", "--auth-type" }, "Authentication type (Release builds require MI; Debug builds support all 3 options)"));
            root.AddOption(new Option <LogLevel>(new string[] { "-l", "--log-level" }, "Log Level"));
            root.AddOption(new Option(new string[] { "-d", "--dry-run" }, "Validates configuration"));

            return(root);
        }
Esempio n. 24
0
        public static int Main(string[] args)
        {
            RootCommand rootCommand = new RootCommand();
            Command     build       = new Command("build", "Builds a generic package with or without shortcuts from a directory")
            {
                new Option <string>("--binDir", "Directory to package"),
                new Option <string>("--mainBin", () => "FIND_BIN", "The applications main binary"),
                new Option <string>("--packageFile", "Directory to package"),
                new Option <string>("--postInstall", () => "",
                                    "Command(s) to run after installing the package (This will be pasted into the .bat AND .sh file)"),
                new Option <string>("--postRemove", () => "",
                                    "Command(s) to run after removing the package (This will be pasted into the .bat AND .sh file)"),
                new Option <bool>("--noLogo", "Disables the logo"),
                new Option <bool>("--noShortcuts",
                                  "When this is enabled the scripts will not generate a start-menu item"),
                new Option <bool>("--noWine",
                                  "This indicates that your program supports multiple platforms natively and doesn't require WINE")
            };

            build.Handler =
                CommandHandler.Create((Action <string, string, string, string, string, bool, bool, bool>)Build);
            rootCommand.AddCommand(build);
            return(rootCommand.InvokeAsync(args).Result);
        }
Esempio n. 25
0
        public static CommandLineOptions Parse(string[] args)
        {
            var options             = new CommandLineOptions();
            var configurationReader = new ConfigurationReader();
            var config = configurationReader.GetConfiguration();

            options.Endpoint   = config.Endpoint;
            options.LoginToken = config.LoginToken;

            var app = new CommandLineApplication
            {
                Name     = "apollo",
                FullName = "Apollo CommandLine Interface"
            };

            app.HelpOption("-h|--help");

            var verboseSwitch = app.Option("--verbose", "Verbose Output", CommandOptionType.NoValue);
            var requestSwitch =
                app.Option("--showRequest", "Write request object to stdout", CommandOptionType.NoValue);
            var fullResultSwitch = app.Option("--fullResults", "Display full result object and not just command result",
                                              CommandOptionType.NoValue);

            RootCommand.Configure(app, options);
            var result = app.Execute(args);

            if (result != 0)
            {
                return(null);
            }

            options.Verbose     = verboseSwitch.HasValue();
            options.ShowRequest = requestSwitch.HasValue();
            options.FullResults = fullResultSwitch.HasValue();
            return(options);
        }
Esempio n. 26
0
        public void Parser_root_Options_can_be_specified_multiple_times_and_their_arguments_are_collated()
        {
            var animalsOption    = new Option <string[]>(new[] { "-a", "--animals" });
            var vegetablesOption = new Option <string[]>(new[] { "-v", "--vegetables" });
            var parser           = new RootCommand
            {
                animalsOption,
                vegetablesOption
            };

            var result = parser.Parse("-a cat -v carrot -a dog");

            result.FindResultFor(animalsOption)
            .Tokens
            .Select(t => t.Value)
            .Should()
            .BeEquivalentTo("cat", "dog");

            result.FindResultFor(vegetablesOption)
            .Tokens
            .Select(t => t.Value)
            .Should()
            .BeEquivalentTo("carrot");
        }
    public static void Register(RootCommand rootCommand, string commandText, string className)
    {
        Command command = new(commandText);

        MethodInfo[] methods = Assembly.GetExecutingAssembly()
                               .GetTypes()
                               .Single(t => t.Name == className)
                               .GetMethods()
                               .Where(m => m.IsPublic && m.IsStatic)
                               .ToArray();

        foreach (var method in methods)
        {
            Command featureCommand = new(method.Name.ToLower());
            featureCommand.SetHandler(() =>
            {
                MethodInfo m = method;
                m.Invoke(null, null);
            });
            command.AddCommand(featureCommand);
        }

        rootCommand.AddCommand(command);
    }
Esempio n. 28
0
        public Task <int> ExecuteAsync(string[] args)
        {
            var command = new RootCommand
            {
                new Option(new[] { "--str", "-s" })
                {
                    Argument = new Argument <string?>()
                },
                new Option(new[] { "--int", "-i" })
                {
                    Argument = new Argument <int>()
                },
                new Option(new[] { "--bool", "-b" })
                {
                    Argument = new Argument <bool>()
                }
            };

            command.Handler = CommandHandler.Create(
                typeof(SystemCommandLineCommand).GetMethod(nameof(ExecuteHandler)) !
                );

            return(command.InvokeAsync(args));
        }
Esempio n. 29
0
        public static void Main(string[] args)
        {
            if (!Oodle.Load())
            {
                Console.Error.WriteLine("Failed to load any oodle libraries. Aborting");
                return;
            }

            var rootCommand = new RootCommand
            {
                new ArchiveCommand(),

                new UnbundleCommand(),
                new UncookCommand(),
                new ImportCommand(),
                new PackCommand(),
                new ExportCommand(),

                new DumpCommand(),
                new CR2WCommand(),

                new HashCommand(),
                new OodleCommand(),

                new TweakCommand(),

                new SettingsCommand(),
            };

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

            parser.Invoke(args);
        }
Esempio n. 30
0
        public void Should_three_full_line_string()
        {
            //Arrange
            var consoleManager = new FakeConsoleManager();
            var console        = new TestConsole(consoleManager);
            var command        = new RootCommand(console);
            var commandEngine  = new CommandEngine(command);

            Task.Run(() => { commandEngine.Start(new string[] { }); }).Wait(100);
            console.Output(new WriteEventArgs(new string('A', console.BufferWidth * (console.BufferHeight - 2))));

            //Act
            console.Output(new WriteEventArgs(new string('B', 3 * console.BufferWidth)));

            //Assert
            Assert.That(consoleManager.LineOutput[0], Is.EqualTo(new string('A', consoleManager.BufferWidth)));
            Assert.That(consoleManager.LineOutput[consoleManager.BufferHeight - 5], Is.EqualTo(new string('A', consoleManager.BufferWidth)));
            Assert.That(consoleManager.LineOutput[consoleManager.BufferHeight - 4], Is.EqualTo(new string('B', console.BufferWidth)));
            Assert.That(consoleManager.LineOutput[consoleManager.BufferHeight - 3], Is.EqualTo(new string('B', console.BufferWidth)));
            Assert.That(consoleManager.LineOutput[consoleManager.BufferHeight - 2], Is.EqualTo(new string('B', console.BufferWidth)));
            //TODO: Fix on build server! Assert.That(consoleManager.LineOutput[consoleManager.BufferHeight - 1], Is.EqualTo("> "));
            //TODO: Fix on build server! Assert.That(consoleManager.CursorTop, Is.EqualTo(consoleManager.BufferHeight - 1));
            //TODO: Fix on build server! Assert.That(consoleManager.CursorLeft, Is.EqualTo(2));
        }
Esempio n. 31
0
 private static void Main(string[] args)
 {
     var cmd = new RootCommand(new HelixCommand());
     cmd.Execute(args);
 }