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" }); }
public void When_option_is_not_respecified_but_limit_is_not_reached_then_the_following_token_is_used_as_value() { var animalsOption = new Option(new[] { "-a", "--animals" }) { AllowMultipleArgumentsPerToken = true, Arity = ArgumentArity.ZeroOrMore }; var vegetablesOption = new Option(new[] { "-v", "--vegetables" }) { Arity = ArgumentArity.ZeroOrMore }; var command = new RootCommand { animalsOption, vegetablesOption }; var result = command.Parse("-a cat dog -v carrot"); result .FindResultFor(animalsOption) .Tokens .Select(t => t.Value) .Should() .BeEquivalentTo(new[] { "cat", "dog" }); result .FindResultFor(vegetablesOption) .Tokens .Select(t => t.Value) .Should() .BeEquivalentTo("carrot"); result .UnmatchedTokens .Should() .BeNullOrEmpty(); }
public void tokens_that_cannot_be_converted_by_multiple_arity_option_flow_to_next_single_arity_argument() { var option = new Option <int[]>("-i"); var argument = new Argument <string>("arg"); var command = new RootCommand { option, argument }; var result = command.Parse("-i 1 2 3 four"); result.FindResultFor(option) .GetValueOrDefault() .Should() .BeEquivalentTo(new[] { 1, 2, 3 }, options => options.WithStrictOrdering()); result.FindResultFor(argument) .Should() .Be("four"); }
[Fact] // https://github.com/dotnet/command-line-api/issues/1573 public void Multiple_validators_on_the_same_option_do_not_report_duplicate_errors() { var option = new Option <string>("-x"); option.AddValidator(result => result.ErrorMessage = "Wrong"); option.AddValidator(_ => { }); var command = new RootCommand { option }; var parseResult = command.Parse("-x b"); parseResult.Errors .Should() .ContainSingle() .Which .Message .Should() .Be("Wrong"); }
[Fact] // https://github.com/dotnet/command-line-api/issues/1573 public void Multiple_validators_on_the_same_argument_do_not_report_duplicate_errors() { var argument = new Argument <string>(); argument.AddValidator(result => result.ErrorMessage = "Wrong"); argument.AddValidator(_ => { }); var command = new RootCommand { argument }; var parseResult = command.Parse("b"); parseResult.Errors .Should() .ContainSingle() .Which .Message .Should() .Be("Wrong"); }
public void When_a_subcommand_has_been_specified_then_its_child_options_will_be_suggested() { var command = new RootCommand("parent") { new Argument <string>(), new Command("child") { new Option("--child-option") { Argument = new Argument <string>() } } }; var commandLine = "child "; var parseResult = command.Parse(commandLine); parseResult .Suggestions(commandLine.Length + 1) .Should() .Contain("--child-option"); }
public void Response_files_can_refer_to_other_response_files() { var file3 = ResponseFile("--three", "3"); var file2 = ResponseFile($"@{file3}", "--two", "2"); var file1 = ResponseFile("--one", "1", $"@{file2}"); var option1 = new Option <int>("--one"); var option2 = new Option <int>("--two"); var option3 = new Option <int>("--three"); var command = new RootCommand { option1, option2, option3 }; var result = command.Parse($"@{file1}"); result.FindResultFor(option1).GetValueOrDefault().Should().Be(1); result.FindResultFor(option1).GetValueOrDefault().Should().Be(1); result.FindResultFor(option2).GetValueOrDefault().Should().Be(2); result.FindResultFor(option3).GetValueOrDefault().Should().Be(3); result.Errors.Should().BeEmpty(); }
public void CommandLineText_preserves_command_line_prior_to_splitting_when_complete_command_line_is_parsed() { var command = new RootCommand { new Command("verb") { new Option <int>("-x") } }; var commandLine = "verb -x 123"; var parseResult = command.Parse(commandLine); parseResult.GetCompletionContext() .Should() .BeOfType <TextCompletionContext>() .Which .CommandLineText .Should() .Be(commandLine); }
public void tokens_that_cannot_be_converted_by_multiple_arity_argument_flow_to_next_single_arity_argument() { var ints = new Argument <int[]>(); var strings = new Argument <string>(); var root = new RootCommand { ints, strings }; var result = root.Parse("1 2 3 four five"); var _ = new AssertionScope(); result .ValueForArgument(ints) .Should() .BeEquivalentTo(new[] { 1, 2, 3 }, options => options.WithStrictOrdering()); result.ValueForArgument(strings).Should().Be("four"); result.UnparsedTokens.Should().ContainSingle().Which.Should().Be("five"); }
/// <summary> /// Main entry point /// </summary> /// <param name="args">Command Line Parms</param> public static async Task <int> Main(string[] args) { List <string> cmd = MergeEnvVarIntoCommandArgs(args); // build the System.CommandLine.RootCommand RootCommand root = BuildRootCommand(); // parse the command line ParseResult parse = root.Parse(cmd.ToArray()); if (parse.Errors.Count > 0) { return(await root.InvokeAsync(cmd.ToArray()).ConfigureAwait(false)); } // add ctl-c handler AddControlCHandler(); // run the app using Config cfg = Config.LoadFromCommandLine(parse); return(await App.Run(cfg).ConfigureAwait(false)); }
[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."); }
public void Multiple_arguments_of_unspecified_type_are_parsed_correctly() { var sourceArg = new Argument <string>("source"); var destinationArg = new Argument <string>("destination"); var root = new RootCommand { sourceArg, destinationArg }; var result = root.Parse("src.txt dest.txt"); result.FindResultFor(sourceArg) .GetValueOrDefault() .Should() .Be("src.txt"); result.FindResultFor(destinationArg) .GetValueOrDefault() .Should() .Be("dest.txt"); }
public void Unsatisfied_subsequent_argument_with_min_arity_0_parses_as_default_value() { var arg1 = new Argument <string> { Arity = ArgumentArity.ExactlyOne }; var arg2 = new Argument <string> { Arity = ArgumentArity.ZeroOrOne, }; arg2.SetDefaultValue("the-default"); var rootCommand = new RootCommand { arg1, arg2, }; var result = rootCommand.Parse("value-1"); result.GetValueForArgument(arg1).Should().Be("value-1"); result.GetValueForArgument(arg2).Should().Be("the-default"); }
public void When_a_subcommand_with_subcommands_has_been_specified_then_its_sibling_commands_will_not_be_suggested() { var rootCommand = new RootCommand { new Command("apple") { new Command("cortland") }, new Command("banana") { new Command("cavendish") }, new Command("cherry") { new Command("rainier") } }; var commandLine = "cherry"; var result = rootCommand.Parse(commandLine); result.GetSuggestions(commandLine.Length + 1).Should().BeEquivalentTo("rainier"); }
static void Main(string[] args) { var root_command = new RootCommand { new Option <FileInfo>("-f", getDefaultValue: () => new FileInfo("out.wav"), "Where the audio will be stored"), new Option <int>("-s", getDefaultValue: () => 60, "The length of the audio clip"), new Option <int>("-b", getDefaultValue: () => 44100, "The audio bitrate"), new Option <int>("-d", getDefaultValue: () => 16, "The audio bit depth"), new Option <bool>("-m", getDefaultValue: () => false, "Enable stereo audio"), new Option <int>("-l", getDefaultValue: () => 60, "Leakyness of the integrator") }; root_command.Description = "Generates a WAV file containing processed noise."; root_command.Handler = CommandHandler.Create(() => { try { var res = root_command.Parse(args); BrownNoise( ((FileInfo)res.ValueForOption("-f")).FullName, (int)res.ValueForOption("-s"), (int)res.ValueForOption("-b"), (int)res.ValueForOption("-d"), (bool)res.ValueForOption("-m"), (int)res.ValueForOption("-l") ); } catch (Exception ex) { Console.WriteLine("An error occured. The operation has been aborted."); } }); root_command.InvokeAsync(args).Wait(); }
public void When_a_subcommand_has_been_specified_then_its_siblings_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.Suggestions() .Should() .BeEquivalentTo("--rainier"); }
public void When_a_subcommand_has_been_specified_then_its_sibling_commands_aliases_will_not_be_suggested() { var apple = new Command("apple") { new Option("--cortland") }; apple.AddAlias("apl"); var banana = new Command("banana") { new Option("--cavendish") }; banana.AddAlias("bnn"); var rootCommand = new RootCommand { apple, banana }; var result = rootCommand.Parse("banana "); result.GetSuggestions().Should().NotContain(new[] { "apl", "bnn" }); }
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"); }
/// <summary> /// Main entry point /// </summary> /// <param name="args">Command Line Parms</param> public static async Task <int> Main(string[] args) { // merge environment variables into command line for parsing var cmd = MergeEnvVarIntoCommandArgs(args); // build the System.CommandLine.RootCommand RootCommand root = BuildRootCommand(); // handle version // ignores all other parameters if (cmd.Contains("--version")) { Console.WriteLine(CSE.SemanticVersion.Version); return(0); } // parse the command line ParseResult parse = root.Parse(cmd.ToArray()); // display errors and help if (parse.Errors.Count > 0) { return(await root.InvokeAsync(cmd.ToArray()).ConfigureAwait(false)); } // load the config from the ParseResult Config config = Config.LoadFromCommandLine(parse); if (config.DryRun) { return(DoDryRun(config)); } // run the app return(ComplexApp.Run(config)); }
private static int Main(string[] args) { var cmd = new RootCommand() { new Option(new[] { "--foo", "-f" }, "A value used for something.") { Argument = new Argument <string>("foo") } }; // translate from Bullseye to System.CommandLine cmd.Add(new Argument("targets") { Arity = ArgumentArity.ZeroOrMore, Description = "The targets to run or list." }); foreach (var option in Options.Definitions) { cmd.Add(new Option(new[] { option.ShortName, option.LongName }.Where(n => !string.IsNullOrWhiteSpace(n)).ToArray(), option.Description)); } cmd.Handler = CommandHandler.Create <string>(foo => { // translate from System.CommandLine to Bullseye var cmdLine = cmd.Parse(args); var targets = cmdLine.CommandResult.Tokens.Select(token => token.Value); var options = new Options(Options.Definitions.Select(o => (o.LongName, cmdLine.ValueForOption <bool>(o.LongName)))); Target("build", () => System.Console.WriteLine($"foo = {foo}")); Target("default", DependsOn("build")); RunTargetsAndExit(targets, options); }); return(cmd.Invoke(args)); }
public void Multiple_command_arguments_can_have_custom_parse_delegates() { var root = new RootCommand { new Argument <FileInfo[]>( "from", argumentResult => { argumentResult.ErrorMessage = "nope"; return(null); }, true ) { Arity = new ArgumentArity(0, 2) }, new Argument <DirectoryInfo>( "to", argumentResult => { argumentResult.ErrorMessage = "UH UH"; return(null); }, true ) { Arity = ArgumentArity.ExactlyOne } }; var result = root.Parse("a.txt b.txt /path/to/dir"); result.Errors.Select(e => e.Message).Should().Contain("nope"); result.Errors.Select(e => e.Message).Should().Contain("UH UH"); }
public static int Main(string[] args) { object[] attributes = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false); _assemblyTitle = ((AssemblyTitleAttribute)attributes[0]).Title; attributes = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); _assemblyVersion = Attribute.GetCustomAttribute(typeof(MainClass).Assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute; _assemblyCopyright = ((AssemblyCopyrightAttribute)attributes[0]).Copyright; if (args.Length == 1 && args[0].ToLowerInvariant() == "gui") { return(Gui.Main.Start(args)); } AaruConsole.WriteLineEvent += System.Console.WriteLine; AaruConsole.WriteEvent += System.Console.Write; AaruConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine; Settings.Settings.LoadSettings(); AaruContext ctx; try { ctx = AaruContext.Create(Settings.Settings.LocalDbPath); ctx.Database.Migrate(); } catch (NotSupportedException) { File.Delete(Settings.Settings.LocalDbPath); ctx = AaruContext.Create(Settings.Settings.LocalDbPath); ctx.Database.EnsureCreated(); ctx.Database. ExecuteSqlRaw("CREATE TABLE IF NOT EXISTS \"__EFMigrationsHistory\" (\"MigrationId\" TEXT PRIMARY KEY, \"ProductVersion\" TEXT)"); foreach (string migration in ctx.Database.GetPendingMigrations()) { ctx.Database. ExecuteSqlRaw($"INSERT INTO \"__EFMigrationsHistory\" (MigrationId, ProductVersion) VALUES ('{migration}', '0.0.0')"); } ctx.SaveChanges(); } // Remove duplicates foreach (var duplicate in ctx.SeenDevices.AsEnumerable() !.GroupBy(a => new { a.Manufacturer, a.Model, a.Revision, a.Bus }).Where(a => a.Count() > 1).Distinct().Select(a => a.Key)) { ctx.RemoveRange(ctx.SeenDevices !. Where(d => d.Manufacturer == duplicate.Manufacturer && d.Model == duplicate.Model && d.Revision == duplicate.Revision && d.Bus == duplicate.Bus).Skip(1)); } // Remove nulls ctx.RemoveRange(ctx.SeenDevices !.Where(d => d.Manufacturer == null && d.Model == null && d.Revision == null)); ctx.SaveChanges(); bool mainDbUpdate = false; if (!File.Exists(Settings.Settings.MainDbPath)) { mainDbUpdate = true; UpdateCommand.DoUpdate(true); } var mainContext = AaruContext.Create(Settings.Settings.MainDbPath); if (mainContext.Database.GetPendingMigrations().Any()) { AaruConsole.WriteLine("New database version, updating..."); try { File.Delete(Settings.Settings.MainDbPath); } catch (Exception) { AaruConsole.ErrorWriteLine("Exception trying to remove old database version, cannot continue..."); AaruConsole.ErrorWriteLine("Please manually remove file at {0}", Settings.Settings.MainDbPath); } UpdateCommand.DoUpdate(true); } // GDPR level compliance does not match and there are no arguments or the arguments are neither GUI neither configure. if (Settings.Settings.Current.GdprCompliance < DicSettings.GDPR_LEVEL && (args.Length < 1 || (args.Length >= 1 && args[0].ToLowerInvariant() != "gui" && args[0].ToLowerInvariant() != "configure"))) { new ConfigureCommand().DoConfigure(true); } Statistics.LoadStats(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var rootCommand = new RootCommand(); rootCommand.AddGlobalOption(new Option(new[] { "--verbose", "-v" }, "Shows verbose output.") { Argument = new Argument <bool>(() => false) }); rootCommand.AddGlobalOption(new Option(new[] { "--debug", "-d" }, "Shows debug output from plugins.") { Argument = new Argument <bool>(() => false) }); rootCommand.AddGlobalOption(new Option(new[] { "--pause" }, "Pauses before exiting.") { Argument = new Argument <bool>(() => false) }); rootCommand.Description = $"{_assemblyTitle} {_assemblyVersion?.InformationalVersion}\n{_assemblyCopyright}"; rootCommand.AddCommand(new DatabaseFamily(mainDbUpdate)); rootCommand.AddCommand(new DeviceFamily()); rootCommand.AddCommand(new FilesystemFamily()); rootCommand.AddCommand(new ImageFamily()); rootCommand.AddCommand(new MediaFamily()); rootCommand.AddCommand(new ArchiveFamily()); rootCommand.AddCommand(new ConfigureCommand()); rootCommand.AddCommand(new FormatsCommand()); rootCommand.AddCommand(new ListEncodingsCommand()); rootCommand.AddCommand(new ListNamespacesCommand()); rootCommand.AddCommand(new RemoteCommand()); int ret = rootCommand.Invoke(args); Statistics.SaveStats(); if (rootCommand.Parse(args).RootCommandResult.ValueForOption("--pause")?.Equals(true) != true) { return(ret); } AaruConsole.WriteLine("Press any key to exit."); System.Console.ReadKey(); return(ret); }
public static void Main(string[] args) { var cmd = new RootCommand(); cmd.AddOption(new Option("-n", "Max number of requests to make concurrently.") { Argument = new Argument <int>("numWorkers", Environment.ProcessorCount) }); cmd.AddOption(new Option("-maxContentLength", "Max content length for request and response bodies.") { Argument = new Argument <int>("numBytes", 1000) }); cmd.AddOption(new Option("-http", "HTTP version (1.1 or 2.0)") { Argument = new Argument <Version[]>("version", new[] { HttpVersion.Version20 }) }); cmd.AddOption(new Option("-connectionLifetime", "Max connection lifetime length (milliseconds).") { Argument = new Argument <int?>("connectionLifetime", null) }); cmd.AddOption(new Option("-ops", "Indices of the operations to use") { Argument = new Argument <int[]>("space-delimited indices", null) }); cmd.AddOption(new Option("-trace", "Enable Microsoft-System-Net-Http tracing.") { Argument = new Argument <string>("\"console\" or path") }); cmd.AddOption(new Option("-aspnetlog", "Enable ASP.NET warning and error logging.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-listOps", "List available options.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-seed", "Seed for generating pseudo-random parameters for a given -n argument.") { Argument = new Argument <int?>("seed", null) }); cmd.AddOption(new Option("-numParameters", "Max number of query parameters or form fields for a request.") { Argument = new Argument <int>("queryParameters", 1) }); cmd.AddOption(new Option("-cancelRate", "Number between 0 and 1 indicating rate of client-side request cancellation attempts. Defaults to 0.1.") { Argument = new Argument <double>("probability", 0.1) }); cmd.AddOption(new Option("-httpSys", "Use http.sys instead of Kestrel.") { Argument = new Argument <bool>("enable", false) }); ParseResult cmdline = cmd.Parse(args); if (cmdline.Errors.Count > 0) { foreach (ParseError error in cmdline.Errors) { Console.WriteLine(error); } Console.WriteLine(); new HelpBuilder(new SystemConsole()).Write(cmd); return; } Run(httpSys: cmdline.ValueForOption <bool>("-httpSys"), concurrentRequests: cmdline.ValueForOption <int>("-n"), maxContentLength: cmdline.ValueForOption <int>("-maxContentLength"), httpVersions: cmdline.ValueForOption <Version[]>("-http"), connectionLifetime: cmdline.ValueForOption <int?>("-connectionLifetime"), opIndices: cmdline.ValueForOption <int[]>("-ops"), logPath: cmdline.HasOption("-trace") ? cmdline.ValueForOption <string>("-trace") : null, aspnetLog: cmdline.ValueForOption <bool>("-aspnetlog"), listOps: cmdline.ValueForOption <bool>("-listOps"), seed: cmdline.ValueForOption <int?>("-seed") ?? new Random().Next(), numParameters: cmdline.ValueForOption <int>("-numParameters"), cancellationProbability: Math.Max(0, Math.Min(1, cmdline.ValueForOption <double>("-cancelRate")))); }
private static bool TryParseCli(string[] args, [NotNullWhen(true)] out Configuration?config) { var cmd = new RootCommand(); cmd.AddOption(new Option("-n", "Max number of requests to make concurrently.") { Argument = new Argument <int>("numWorkers", Environment.ProcessorCount) }); cmd.AddOption(new Option("-serverUri", "Stress suite server uri.") { Argument = new Argument <string>("serverUri", "https://localhost:5001") }); cmd.AddOption(new Option("-runMode", "Stress suite execution mode. Defaults to Both.") { Argument = new Argument <RunMode>("runMode", RunMode.both) }); cmd.AddOption(new Option("-maxExecutionTime", "Maximum stress execution time, in minutes. Defaults to infinity.") { Argument = new Argument <double?>("minutes", null) }); cmd.AddOption(new Option("-maxContentLength", "Max content length for request and response bodies.") { Argument = new Argument <int>("numBytes", 1000) }); cmd.AddOption(new Option("-maxRequestUriSize", "Max query string length support by the server.") { Argument = new Argument <int>("numChars", 5000) }); cmd.AddOption(new Option("-maxRequestHeaderCount", "Maximum number of headers to place in request") { Argument = new Argument <int>("numHeaders", 90) }); cmd.AddOption(new Option("-maxRequestHeaderTotalSize", "Max request header total size.") { Argument = new Argument <int>("numBytes", 1000) }); cmd.AddOption(new Option("-http", "HTTP version (1.1 or 2.0)") { Argument = new Argument <Version>("version", HttpVersion.Version20) }); cmd.AddOption(new Option("-connectionLifetime", "Max connection lifetime length (milliseconds).") { Argument = new Argument <int?>("connectionLifetime", null) }); cmd.AddOption(new Option("-ops", "Indices of the operations to use") { Argument = new Argument <int[]?>("space-delimited indices", null) }); cmd.AddOption(new Option("-xops", "Indices of the operations to exclude") { Argument = new Argument <int[]?>("space-delimited indices", null) }); cmd.AddOption(new Option("-trace", "Enable System.Net.Http.InternalDiagnostics (client) and/or ASP.NET dignostics (server) tracing.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-aspnetlog", "Enable ASP.NET warning and error logging.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-listOps", "List available options.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-seed", "Seed for generating pseudo-random parameters for a given -n argument.") { Argument = new Argument <int?>("seed", null) }); cmd.AddOption(new Option("-numParameters", "Max number of query parameters or form fields for a request.") { Argument = new Argument <int>("queryParameters", 1) }); cmd.AddOption(new Option("-cancelRate", "Number between 0 and 1 indicating rate of client-side request cancellation attempts. Defaults to 0.1.") { Argument = new Argument <double>("probability", 0.1) }); cmd.AddOption(new Option("-httpSys", "Use http.sys instead of Kestrel.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-winHttp", "Use WinHttpHandler for the stress client.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-displayInterval", "Client stats display interval in seconds. Defaults to 5 seconds.") { Argument = new Argument <int>("seconds", 5) }); cmd.AddOption(new Option("-clientTimeout", "Default HttpClient timeout in seconds. Defaults to 60 seconds.") { Argument = new Argument <int>("seconds", 60) }); cmd.AddOption(new Option("-serverMaxConcurrentStreams", "Overrides kestrel max concurrent streams per connection.") { Argument = new Argument <int?>("streams", null) }); cmd.AddOption(new Option("-serverMaxFrameSize", "Overrides kestrel max frame size setting.") { Argument = new Argument <int?>("bytes", null) }); cmd.AddOption(new Option("-serverInitialConnectionWindowSize", "Overrides kestrel initial connection window size setting.") { Argument = new Argument <int?>("bytes", null) }); cmd.AddOption(new Option("-serverMaxRequestHeaderFieldSize", "Overrides kestrel max request header field size.") { Argument = new Argument <int?>("bytes", null) }); ParseResult cmdline = cmd.Parse(args); if (cmdline.Errors.Count > 0) { foreach (ParseError error in cmdline.Errors) { Console.WriteLine(error); } Console.WriteLine(); new HelpBuilder(new SystemConsole()).Write(cmd); config = null; return(false); } config = new Configuration() { RunMode = cmdline.ValueForOption <RunMode>("-runMode"), ServerUri = cmdline.ValueForOption <string>("-serverUri"), ListOperations = cmdline.ValueForOption <bool>("-listOps"), HttpVersion = cmdline.ValueForOption <Version>("-http"), UseWinHttpHandler = cmdline.ValueForOption <bool>("-winHttp"), ConcurrentRequests = cmdline.ValueForOption <int>("-n"), RandomSeed = cmdline.ValueForOption <int?>("-seed") ?? new Random().Next(), MaxContentLength = cmdline.ValueForOption <int>("-maxContentLength"), MaxRequestUriSize = cmdline.ValueForOption <int>("-maxRequestUriSize"), MaxRequestHeaderCount = cmdline.ValueForOption <int>("-maxRequestHeaderCount"), MaxRequestHeaderTotalSize = cmdline.ValueForOption <int>("-maxRequestHeaderTotalSize"), OpIndices = cmdline.ValueForOption <int[]>("-ops"), ExcludedOpIndices = cmdline.ValueForOption <int[]>("-xops"), MaxParameters = cmdline.ValueForOption <int>("-numParameters"), DisplayInterval = TimeSpan.FromSeconds(cmdline.ValueForOption <int>("-displayInterval")), DefaultTimeout = TimeSpan.FromSeconds(cmdline.ValueForOption <int>("-clientTimeout")), ConnectionLifetime = cmdline.ValueForOption <double?>("-connectionLifetime").Select(TimeSpan.FromMilliseconds), CancellationProbability = Math.Max(0, Math.Min(1, cmdline.ValueForOption <double>("-cancelRate"))), MaximumExecutionTime = cmdline.ValueForOption <double?>("-maxExecutionTime").Select(TimeSpan.FromMinutes), UseHttpSys = cmdline.ValueForOption <bool>("-httpSys"), LogAspNet = cmdline.ValueForOption <bool>("-aspnetlog"), Trace = cmdline.ValueForOption <bool>("-trace"), ServerMaxConcurrentStreams = cmdline.ValueForOption <int?>("-serverMaxConcurrentStreams"), ServerMaxFrameSize = cmdline.ValueForOption <int?>("-serverMaxFrameSize"), ServerInitialConnectionWindowSize = cmdline.ValueForOption <int?>("-serverInitialConnectionWindowSize"), ServerMaxRequestHeaderFieldSize = cmdline.ValueForOption <int?>("-serverMaxRequestHeaderFieldSize"), }; return(true); }
public TCommand Get <TCommand>(String input = "") where TCommand : class, ICommand => _root.Parse(input).CommandResult.Command as TCommand;
public static RunTestsOptions Parse(string[] args) { var command = new RootCommand() { new Option( aliases: new string[] { "--target", "-t" }, description: "The test dll to run") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--runtime" }, description: "The version of the ASP.NET runtime being installed and used") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--queue" }, description: "The name of the Helix queue being run on") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--arch" }, description: "The architecture being run on") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--quarantined" }, description: "Whether quarantined tests should run or not") { Argument = new Argument <bool>(), Required = true }, new Option( aliases: new string[] { "--ef" }, description: "The version of the EF tool to use") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--aspnetruntime" }, description: "The path to the aspnet runtime nupkg to install") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--aspnetref" }, description: "The path to the aspnet ref nupkg to install") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--helixTimeout" }, description: "The timeout duration of the Helix job") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--source" }, description: "The restore sources to use during testing") { Argument = new Argument <string>() { Arity = ArgumentArity.ZeroOrMore }, Required = true } }; var parseResult = command.Parse(args); var options = new RunTestsOptions(); options.Target = parseResult.ValueForOption <string>("--target"); options.RuntimeVersion = parseResult.ValueForOption <string>("--runtime"); options.HelixQueue = parseResult.ValueForOption <string>("--queue"); options.Architecture = parseResult.ValueForOption <string>("--arch"); options.Quarantined = parseResult.ValueForOption <bool>("--quarantined"); options.EfVersion = parseResult.ValueForOption <string>("--ef"); options.AspNetRuntime = parseResult.ValueForOption <string>("--aspnetruntime"); options.AspNetRef = parseResult.ValueForOption <string>("--aspnetref"); options.Timeout = TimeSpan.Parse(parseResult.ValueForOption <string>("--helixTimeout")); options.Source = parseResult.ValueForOption <IEnumerable <string> >("--source"); options.HELIX_WORKITEM_ROOT = Environment.GetEnvironmentVariable("HELIX_WORKITEM_ROOT"); options.Path = Environment.GetEnvironmentVariable("PATH"); options.DotnetRoot = Environment.GetEnvironmentVariable("DOTNET_ROOT"); return(options); }
public static void Main(string[] args) { var cmd = new RootCommand(); cmd.AddOption(new Option("-n", "Max number of requests to make concurrently.") { Argument = new Argument <int>("numWorkers", 1) }); cmd.AddOption(new Option("-maxContentLength", "Max content length for request and response bodies.") { Argument = new Argument <int>("numBytes", 1000) }); cmd.AddOption(new Option("-http", "HTTP version (1.1 or 2.0)") { Argument = new Argument <Version[]>("version", new[] { HttpVersion.Version20 }) }); cmd.AddOption(new Option("-connectionLifetime", "Max connection lifetime length (milliseconds).") { Argument = new Argument <int?>("connectionLifetime", null) }); cmd.AddOption(new Option("-ops", "Indices of the operations to use") { Argument = new Argument <int[]>("space-delimited indices", null) }); cmd.AddOption(new Option("-trace", "Enable Microsoft-System-Net-Http tracing.") { Argument = new Argument <string>("\"console\" or path") }); cmd.AddOption(new Option("-aspnetlog", "Enable ASP.NET warning and error logging.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-listOps", "List available options.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-seed", "Seed for generating pseudo-random parameters for a given -n argument.") { Argument = new Argument <int?>("seed", null) }); ParseResult cmdline = cmd.Parse(args); if (cmdline.Errors.Count > 0) { foreach (ParseError error in cmdline.Errors) { Console.WriteLine(error); } Console.WriteLine(); new HelpBuilder(new SystemConsole()).Write(cmd); return; } Run(concurrentRequests: cmdline.ValueForOption <int>("-n"), maxContentLength: cmdline.ValueForOption <int>("-maxContentLength"), httpVersions: cmdline.ValueForOption <Version[]>("-http"), connectionLifetime: cmdline.ValueForOption <int?>("-connectionLifetime"), opIndices: cmdline.ValueForOption <int[]>("-ops"), logPath: cmdline.HasOption("-trace") ? cmdline.ValueForOption <string>("-trace") : null, aspnetLog: cmdline.ValueForOption <bool>("-aspnetlog"), listOps: cmdline.ValueForOption <bool>("-listOps"), seed: cmdline.ValueForOption <int?>("-seed") ?? Random.Shared.Next()); }
public static RunTestsOptions Parse(string[] args) { var command = new RootCommand() { new Option( aliases: new string[] { "--target", "-t" }, description: "The test dll to run") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--sdk" }, description: "The version of the sdk being used") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--runtime" }, description: "The version of the runtime being used") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--queue" }, description: "The name of the Helix queue being run on") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--arch" }, description: "The architecture being run on") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--quarantined" }, description: "Whether quarantined tests should run or not") { Argument = new Argument <bool>(), Required = true }, new Option( aliases: new string[] { "--ef" }, description: "The version of the EF tool to use") { Argument = new Argument <string>(), Required = true }, }; var parseResult = command.Parse(args); var options = new RunTestsOptions(); options.Target = parseResult.ValueForOption <string>("--target"); options.SdkVersion = parseResult.ValueForOption <string>("--sdk"); options.RuntimeVersion = parseResult.ValueForOption <string>("--runtime"); options.HelixQueue = parseResult.ValueForOption <string>("--queue"); options.Architecture = parseResult.ValueForOption <string>("--arch"); options.Quarantined = parseResult.ValueForOption <bool>("--quarantined"); options.EfVersion = parseResult.ValueForOption <string>("--ef"); options.HELIX_WORKITEM_ROOT = Environment.GetEnvironmentVariable("HELIX_WORKITEM_ROOT"); options.Path = Environment.GetEnvironmentVariable("PATH"); options.DotnetRoot = Environment.GetEnvironmentVariable("DOTNET_ROOT"); return(options); }
public static RunTestsOptions Parse(string[] args) { var command = new RootCommand() { new Option( aliases: new string[] { "--target", "-t" }, description: "The test dll to run") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--runtime" }, description: "The version of the ASP.NET runtime being installed and used") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--queue" }, description: "The name of the Helix queue being run on") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--arch" }, description: "The architecture being run on") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--quarantined" }, description: "Whether quarantined tests should run or not") { Argument = new Argument <bool>(), Required = true }, new Option( aliases: new string[] { "--ef" }, description: "The version of the EF tool to use") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--helixTimeout" }, description: "The timeout duration of the Helix job") { Argument = new Argument <string>(), Required = true }, new Option( aliases: new string[] { "--source" }, description: "The restore sources to use during testing") { Argument = new Argument <string>() { Arity = ArgumentArity.ZeroOrMore }, Required = true } }; var parseResult = command.Parse(args); var sharedFxVersion = parseResult.ValueForOption <string>("--runtime"); var options = new RunTestsOptions { Architecture = parseResult.ValueForOption <string>("--arch"), EfVersion = parseResult.ValueForOption <string>("--ef"), HelixQueue = parseResult.ValueForOption <string>("--queue"), Quarantined = parseResult.ValueForOption <bool>("--quarantined"), RuntimeVersion = sharedFxVersion, Target = parseResult.ValueForOption <string>("--target"), Timeout = TimeSpan.Parse(parseResult.ValueForOption <string>("--helixTimeout"), CultureInfo.InvariantCulture), // When targeting pack builds, it has exactly the same version as the shared framework. AspNetRef = $"Microsoft.AspNetCore.App.Ref.{sharedFxVersion}.nupkg", AspNetRuntime = $"Microsoft.AspNetCore.App.Runtime.win-x64.{sharedFxVersion}.nupkg", DotnetRoot = Environment.GetEnvironmentVariable("DOTNET_ROOT"), HELIX_WORKITEM_ROOT = Environment.GetEnvironmentVariable("HELIX_WORKITEM_ROOT"), Path = Environment.GetEnvironmentVariable("PATH"), }; return(options); }
private static bool TryParseCli(string[] args, out Configuration config) { var cmd = new RootCommand(); cmd.AddOption(new Option("-n", "Max number of requests to make concurrently.") { Argument = new Argument <int>("numWorkers", Environment.ProcessorCount) }); cmd.AddOption(new Option("-serverUri", "Stress suite server uri.") { Argument = new Argument <Uri>("serverUri", new Uri("https://localhost:5001")) }); cmd.AddOption(new Option("-runMode", "Stress suite execution mode. Defaults to Both.") { Argument = new Argument <RunMode>("runMode", RunMode.both) }); cmd.AddOption(new Option("-maxContentLength", "Max content length for request and response bodies.") { Argument = new Argument <int>("numBytes", 1000) }); cmd.AddOption(new Option("-maxRequestUriSize", "Max query string length support by the server.") { Argument = new Argument <int>("numChars", 8000) }); cmd.AddOption(new Option("-http", "HTTP version (1.1 or 2.0)") { Argument = new Argument <Version>("version", HttpVersion.Version20) }); cmd.AddOption(new Option("-connectionLifetime", "Max connection lifetime length (milliseconds).") { Argument = new Argument <int?>("connectionLifetime", null) }); cmd.AddOption(new Option("-ops", "Indices of the operations to use") { Argument = new Argument <int[]>("space-delimited indices", null) }); cmd.AddOption(new Option("-xops", "Indices of the operations to exclude") { Argument = new Argument <int[]>("space-delimited indices", null) }); cmd.AddOption(new Option("-trace", "Enable Microsoft-System-Net-Http tracing.") { Argument = new Argument <string>("\"console\" or path") }); cmd.AddOption(new Option("-aspnetlog", "Enable ASP.NET warning and error logging.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-listOps", "List available options.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-seed", "Seed for generating pseudo-random parameters for a given -n argument.") { Argument = new Argument <int?>("seed", null) }); cmd.AddOption(new Option("-numParameters", "Max number of query parameters or form fields for a request.") { Argument = new Argument <int>("queryParameters", 1) }); cmd.AddOption(new Option("-cancelRate", "Number between 0 and 1 indicating rate of client-side request cancellation attempts. Defaults to 0.1.") { Argument = new Argument <double>("probability", 0.1) }); cmd.AddOption(new Option("-httpSys", "Use http.sys instead of Kestrel.") { Argument = new Argument <bool>("enable", false) }); cmd.AddOption(new Option("-displayInterval", "Client stats display interval in seconds. Defaults to 5 seconds.") { Argument = new Argument <int>("seconds", 5) }); cmd.AddOption(new Option("-clientTimeout", "Default HttpClient timeout in seconds. Defaults to 10 seconds.") { Argument = new Argument <int>("seconds", 10) }); ParseResult cmdline = cmd.Parse(args); if (cmdline.Errors.Count > 0) { foreach (ParseError error in cmdline.Errors) { Console.WriteLine(error); } Console.WriteLine(); new HelpBuilder(new SystemConsole()).Write(cmd); config = null; return(false); } config = new Configuration() { RunMode = cmdline.ValueForOption <RunMode>("-runMode"), ServerUri = cmdline.ValueForOption <Uri>("-serverUri"), ListOperations = cmdline.ValueForOption <bool>("-listOps"), HttpVersion = cmdline.ValueForOption <Version>("-http"), ConcurrentRequests = cmdline.ValueForOption <int>("-n"), RandomSeed = cmdline.ValueForOption <int?>("-seed") ?? new Random().Next(), MaxContentLength = cmdline.ValueForOption <int>("-maxContentLength"), MaxRequestUriSize = cmdline.ValueForOption <int>("-maxRequestUriSize"), OpIndices = cmdline.ValueForOption <int[]>("-ops"), ExcludedOpIndices = cmdline.ValueForOption <int[]>("-xops"), MaxParameters = cmdline.ValueForOption <int>("-numParameters"), DisplayInterval = TimeSpan.FromSeconds(cmdline.ValueForOption <int>("-displayInterval")), DefaultTimeout = TimeSpan.FromSeconds(cmdline.ValueForOption <int>("-clientTimeout")), ConnectionLifetime = cmdline.ValueForOption <double?>("-connectionLifetime").Select(TimeSpan.FromMilliseconds), CancellationProbability = Math.Max(0, Math.Min(1, cmdline.ValueForOption <double>("-cancelRate"))), UseHttpSys = cmdline.ValueForOption <bool>("-httpSys"), LogAspNet = cmdline.ValueForOption <bool>("-aspnetlog"), LogPath = cmdline.HasOption("-trace") ? cmdline.ValueForOption <string>("-trace") : null }; return(true); }