public void Arguments_HaveCorrectDescription_Returns_CorrectValue( string propertyName, string expectedDescription) { //Arrange var command = new CommandLineApplication(); var property = typeof(TestClass).GetProperty(propertyName); var descriptor = new ParameterDescriptor(property); //Act descriptor.AddCommandLineParameterTo(command); //Assert var actualOption = command.Arguments.First(); Assert.Equal(propertyName, actualOption.Name); Assert.Equal(expectedDescription, actualOption.Description); //Arrange command.Execute(new string[0] { }); //Assert Assert.Equal(null, descriptor.Value); //Is this right assumption to test? //Arrange command.Execute(new string[] { "PassedValue" }); //Assert Assert.Equal("PassedValue", descriptor.Value); }
public void Main(string[] args) { var app = new CommandLineApplication(throwOnUnexpectedArg: false); app.Name = app.FullName = "Nine.Graphics.Test"; app.HelpOption("-?|--help"); var width = app.Option("--width <WIDTH>", "Set the width of the host window", CommandOptionType.SingleValue); var height = app.Option("--height <HEIGHT>", "Set the height of the host window", CommandOptionType.SingleValue); var topMost = app.Option("--pin", "Enables the host window to be top most", CommandOptionType.NoValue); var channel = app.Option("--channel <CHANNEL>", "", CommandOptionType.SingleValue); app.Execute(args); if (app.IsShowingInformation) { return; } if (!channel.HasValue()) { new Host(shutdown, serviceProvider).Run( width.HasValue() ? int.Parse(width.Value()) : (int?)null, width.HasValue() ? int.Parse(height.Value()) : (int?)null, topMost.HasValue(), app.RemainingArguments.ToArray()); } else { new Guest(channel.Value(), shutdown, serviceProvider).Run(app.RemainingArguments.ToArray()); } }
public void Main(string[] args) { var cmdlineApp = new CommandLineApplication(); cmdlineApp.HelpOption("--help"); cmdlineApp.Command("build", c => { c.Option("--foo", "Foo bar", CommandOptionType.NoValue); }); cmdlineApp.Execute(args); }
public void Execute(string[] args) { var app = new CommandLineApplication(); app.Command(ActionDescriptor.Generator.Name, c => { c.HelpOption("--help|-h|-?"); BuildCommandLine(c); }); app.Execute(args); }
public int Main(string[] args) { var app = new CommandLineApplication(); app.Name = "dpa"; var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue); var optionToolsPath = app.Option("--tools-path", "", CommandOptionType.SingleValue); app.HelpOption("-?|-h|--help"); app.VersionOption("--version", GetVersion()); // Show help information if no subcommand/option was specified app.OnExecute(() => { app.ShowHelp(); return 2; }); app.Command("tpa", c => { c.Description = "Build minimal trusted platform assembly list"; var assemblyFolder = c.Argument("[assemblies]", "Path to the folder contains the assemblies from which the TPA is built from."); var tpaSourceFile = c.Argument("[tpa.cpp]", "Path to the source file where the TPA list is generated in place."); c.HelpOption("-?|-h|-help"); c.OnExecute(() => { var command = new BuildTpaCommand(_environment, assemblyFolder.Value, tpaSourceFile.Value); return command.Execute(); }); }); app.Command("runtime", c => { c.Description = "Build the minimal required runtime assemblies"; var assemblyFolder = c.Argument("[assemblies]", "Path to the folder contains the assemblies from which the TPA is built from."); var outputFile = c.Argument("[output]", "Path to the file where the TPA list is saved to. If omitted, output to console"); c.HelpOption("-?|-h|-help"); c.OnExecute(() => { var command = new BuildRuntimeCommand(_environment, assemblyFolder.Value, outputFile.Value); return command.Execute(); }); }); return app.Execute(args); }
public int Main(string[] args) { var app = new CommandLineApplication(throwOnUnexpectedArg: false); app.Name = "Microsoft.Framework.Project"; app.FullName = app.Name; app.HelpOption("-?|-h|--help"); // Show help information if no subcommand/option was specified app.OnExecute(() => { app.ShowHelp(); return 2; }); app.Command("crossgen", c => { c.Description = "Do CrossGen"; var optionIn = c.Option("--in <INPUT_DIR>", "Input directory", CommandOptionType.MultipleValue); var optionOut = c.Option("--out <OUTOUT_DIR>", "Output directory", CommandOptionType.SingleValue); var optionExePath = c.Option("--exePath", "Exe path", CommandOptionType.SingleValue); var optionRuntimePath = c.Option("--runtimePath <PATH>", "Runtime path", CommandOptionType.SingleValue); var optionSymbols = c.Option("--symbols", "Use symbols", CommandOptionType.NoValue); var optionPartial = c.Option("--partial", "Allow partial NGEN", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var crossgenOptions = new CrossgenOptions(); crossgenOptions.InputPaths = optionIn.Values; crossgenOptions.RuntimePath = optionRuntimePath.Value(); crossgenOptions.CrossgenPath = optionExePath.Value(); crossgenOptions.Symbols = optionSymbols.HasValue(); crossgenOptions.Partial = optionPartial.HasValue(); var gen = new CrossgenManager(crossgenOptions); if (!gen.GenerateNativeImages()) { return -1; } return 0; }); }); app.Execute(args); return 0; }
public void AllowNoThrowBehaviorOnUnexpectedLongOption() { var unexpectedOption = "--UnexpectedOption"; var app = new CommandLineApplication(); var testCmd = app.Command("test", c => { c.OnExecute(() => 0); }, throwOnUnexpectedArg: false); // (does not throw) app.Execute("test", unexpectedOption); Assert.Equal(1, testCmd.RemainingArguments.Count); Assert.Equal(unexpectedOption, testCmd.RemainingArguments[0]); }
public void AllowNoThrowBehaviorOnUnexpectedOptionAfterSubcommand() { var unexpectedOption = "--unexpected"; CommandLineApplication subCmd = null; var app = new CommandLineApplication(); var testCmd = app.Command("k", c => { subCmd = c.Command("run", _ => { }, addHelpCommand: false, throwOnUnexpectedArg: false); c.OnExecute(() => 0); }); // (does not throw) app.Execute("k", "run", unexpectedOption); Assert.Equal(0, testCmd.RemainingArguments.Count); Assert.Equal(1, subCmd.RemainingArguments.Count); Assert.Equal(unexpectedOption, subCmd.RemainingArguments[0]); }
public void OptionValueMustBeProvided() { CommandOption first = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Option("--first <NAME>", "First argument", CommandOptionType.SingleValue); c.OnExecute(() => 0); }); var ex = Assert.Throws<Exception>(() => app.Execute("test", "--first")); Assert.Contains("missing value for option", ex.Message); }
public void HandlesAsyncExecutes() { bool called = false; var app = new CommandLineApplication(); app.OnExecute(async () => { await Task.Delay(5); called = true; return 2; }); var result = app.Execute(); Assert.True(called); Assert.Equal(2, result); }
public void ExtraArgumentCausesException() { CommandArgument first = null; CommandArgument second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Argument("first", "First argument"); second = c.Argument("second", "Second argument"); c.OnExecute(() => 0); }); var ex = Assert.Throws<Exception>(() => app.Execute("test", "one", "two", "three")); Assert.Contains("three", ex.Message); }
public void CommandNameCanBeMatched() { var called = false; var app = new CommandLineApplication(); app.Command("test", c => { c.OnExecute(() => { called = true; return 5; }); }); var result = app.Execute("test"); Assert.Equal(5, result); Assert.True(called); }
public int Main(string[] args) { #if DEBUG if (args.Contains("--debug")) { args = args.Skip(1).ToArray(); System.Diagnostics.Debugger.Launch(); } #endif // Set up logging _log = new CommandOutputLogger(); var app = new CommandLineApplication(); app.Name = "nuget3"; app.FullName = ".NET Package Manager"; app.HelpOption("-h|--help"); app.VersionOption("--version", GetType().GetTypeInfo().Assembly.GetName().Version.ToString()); app.Command("restore", restore => { restore.Description = "Restores packages for a project and writes a lock file"; var sources = restore.Option("-s|--source <source>", "Specifies a NuGet package source to use during the restore", CommandOptionType.MultipleValue); var packagesDirectory = restore.Option("--packages <packagesDirectory>", "Directory to install packages in", CommandOptionType.SingleValue); var parallel = restore.Option("-p|--parallel <noneOrNumberOfParallelTasks>", $"The number of concurrent tasks to use when restoring. Defaults to {RestoreRequest.DefaultDegreeOfConcurrency}; pass 'none' to run without concurrency.", CommandOptionType.SingleValue); var projectFile = restore.Argument("[project file]", "The path to the project to restore for, either a project.json or the directory containing it. Defaults to the current directory"); restore.OnExecute(async () => { // Figure out the project directory IEnumerable<string> externalProjects = null; PackageSpec project; var projectPath = Path.GetFullPath(projectFile.Value ?? "."); if (string.Equals(PackageSpec.PackageSpecFileName, Path.GetFileName(projectPath), StringComparison.OrdinalIgnoreCase)) { _log.LogVerbose($"Reading project file {projectFile.Value}"); projectPath = Path.GetDirectoryName(projectPath); project = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(projectFile.Value), Path.GetFileName(projectPath), projectFile.Value); } else if (MsBuildUtility.IsMsBuildBasedProject(projectPath)) { #if DNXCORE50 throw new NotSupportedException(); #else externalProjects = MsBuildUtility.GetProjectReferences(projectPath); projectPath = Path.GetDirectoryName(Path.GetFullPath(projectPath)); var packageSpecFile = Path.Combine(projectPath, PackageSpec.PackageSpecFileName); project = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(packageSpecFile), Path.GetFileName(projectPath), projectFile.Value); _log.LogVerbose($"Reading project file {projectFile.Value}"); #endif } else { var file = Path.Combine(projectPath, PackageSpec.PackageSpecFileName); _log.LogVerbose($"Reading project file {file}"); project = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(file), Path.GetFileName(projectPath), file); } _log.LogVerbose($"Loaded project {project.Name} from {project.FilePath}"); // Resolve the root directory var rootDirectory = PackageSpecResolver.ResolveRootDirectory(projectPath); _log.LogVerbose($"Found project root directory: {rootDirectory}"); // Resolve the packages directory var packagesDir = packagesDirectory.HasValue() ? packagesDirectory.Value() : Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), ".nuget", "packages"); _log.LogVerbose($"Using packages directory: {packagesDir}"); var packageSources = sources.Values.Select(s => new PackageSource(s)); if (!packageSources.Any()) { var settings = Settings.LoadDefaultSettings(projectPath, configFileName: null, machineWideSettings: null); var packageSourceProvider = new PackageSourceProvider(settings); packageSources = packageSourceProvider.LoadPackageSources(); } var request = new RestoreRequest( project, packageSources, packagesDir); if (externalProjects != null) { foreach (var externalReference in externalProjects) { request.ExternalProjects.Add( new ExternalProjectReference( externalReference, Path.Combine(Path.GetDirectoryName(externalReference), PackageSpec.PackageSpecFileName), projectReferences: Enumerable.Empty<string>())); } } // Run the restore if (parallel.HasValue()) { int parallelDegree; if (string.Equals(parallel.Value(), "none", StringComparison.OrdinalIgnoreCase)) { request.MaxDegreeOfConcurrency = 1; } else if (int.TryParse(parallel.Value(), out parallelDegree)) { request.MaxDegreeOfConcurrency = parallelDegree; } } if (request.MaxDegreeOfConcurrency <= 1) { _log.LogInformation("Running non-parallel restore"); } else { _log.LogInformation($"Running restore with {request.MaxDegreeOfConcurrency} concurrent jobs"); } var command = new RestoreCommand(_log); var sw = Stopwatch.StartNew(); var result = await command.ExecuteAsync(request); sw.Stop(); _log.LogInformation($"Restore completed in {sw.ElapsedMilliseconds:0.00}ms!"); return 0; }); }); app.Command("diag", diag => { diag.Description = "Diagnostic commands for debugging package dependency graphs"; diag.Command("lockfile", lockfile => { lockfile.Description = "Dumps data from the project lock file"; var project = lockfile.Option("--project <project>", "Path containing the project lockfile, or the patht to the lockfile itself", CommandOptionType.SingleValue); var target = lockfile.Option("--target <target>", "View information about a specific project target", CommandOptionType.SingleValue); var library = lockfile.Argument("<library>", "Optionally, get detailed information about a specific library"); lockfile.OnExecute(() => { var diagnostics = new DiagnosticCommands(_log); var projectFile = project.HasValue() ? project.Value() : Path.GetFullPath("."); return diagnostics.Lockfile(projectFile, target.Value(), library.Value); }); }); diag.OnExecute(() => { diag.ShowHelp(); return 0; }); }); app.OnExecute(() => { app.ShowHelp(); return 0; }); return app.Execute(args); }
public int Main(string[] args) { try { var description = "Creates table and indexes in Microsoft SQL Server database " + "to be used for distributed caching"; var app = new CommandLineApplication(); app.Name = "sqlservercache"; app.Description = description; app.HelpOption("-?|-h|--help"); app.Command("create", command => { command.Description = description; var connectionStringArg = command.Argument( "[connectionString]", "The connection string to connect to the database."); var schemaNameArg = command.Argument("[schemaName]", "Name of the table schema."); var tableNameArg = command.Argument("[tableName]", "Name of the table to be created."); command.HelpOption("-?|-h|--help"); command.OnExecute(() => { if (string.IsNullOrEmpty(connectionStringArg.Value) || string.IsNullOrEmpty(schemaNameArg.Value) || string.IsNullOrEmpty(tableNameArg.Value)) { _logger.LogWarning("Invalid input"); app.ShowHelp(); return 2; } _connectionString = connectionStringArg.Value; _schemaName = schemaNameArg.Value; _tableName = tableNameArg.Value; CreateTableAndIndexes(); return 0; }); }); // Show help information if no subcommand/option was specified. app.OnExecute(() => { app.ShowHelp(); return 2; }); return app.Execute(args); } catch (Exception exception) { _logger.LogCritical("An error occurred. {Message}", exception.Message); return 1; } }
public void ThrowsExceptionOnUnexpectedOptionBeforeValidSubcommandByDefault() { var unexpectedOption = "--unexpected"; CommandLineApplication subCmd = null; var app = new CommandLineApplication(); app.Command("k", c => { subCmd = c.Command("run", _=> { }); c.OnExecute(() => 0); }); var exception = Assert.Throws<Exception>(() => app.Execute("k", unexpectedOption, "run")); Assert.Equal(string.Format("TODO: Error: unrecognized {0} '{1}'", "option", unexpectedOption), exception.Message); }
public void UnknownCommandCausesException() { var app = new CommandLineApplication(); app.Command("test", c => { c.Argument("first", "First argument"); c.Argument("second", "Second argument"); c.OnExecute(() => 0); }); var ex = Assert.Throws<Exception>(() => app.Execute("test2", "one", "two", "three")); Assert.Contains("test2", ex.Message); }
public int Main(string[] args) { _originalForeground = Console.ForegroundColor; var app = new CommandLineApplication(); app.Name = "kpm"; var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue); app.HelpOption("-?|-h|--help"); app.VersionOption("--version", GetVersion()); // Show help information if no subcommand was specified app.OnExecute(() => { app.ShowHelp(); return 0; }); app.Command("restore", c => { c.Description = "Restore packages"; var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json."); var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command", CommandOptionType.MultipleValue); var optFallbackSource = c.Option("-f|--fallbacksource <FEED>", "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue); var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages", CommandOptionType.SingleValue); var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue); var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { try { var command = new RestoreCommand(_environment); command.Reports = new Reports() { Information = this, Verbose = optionVerbose.HasValue() ? (this as IReport) : new NullReport() }; // If the root argument is a directory if (Directory.Exists(argRoot.Value)) { command.RestoreDirectory = argRoot.Value; } // If the root argument is a project.json file else if (string.Equals( Project.ProjectFileName, Path.GetFileName(argRoot.Value), StringComparison.OrdinalIgnoreCase)) { command.RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(argRoot.Value)); } // If the root argument is a global.json file else if (string.Equals( GlobalSettings.GlobalFileName, Path.GetFileName(argRoot.Value), StringComparison.OrdinalIgnoreCase)) { command.RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(argRoot.Value)); command.GlobalJsonFile = argRoot.Value; } else if (!string.IsNullOrEmpty(argRoot.Value)) { throw new InvalidOperationException("The given root is invalid."); } if (optSource.HasValue()) { command.Sources = optSource.Values; } if (optFallbackSource.HasValue()) { command.FallbackSources = optFallbackSource.Values; } if (optProxy.HasValue()) { Environment.SetEnvironmentVariable("http_proxy", optProxy.Value()); } command.NoCache = optNoCache.HasValue(); command.PackageFolder = optPackageFolder.Value(); var success = command.ExecuteCommand(); return success ? 0 : 1; } catch (Exception ex) { this.WriteLine("----------"); this.WriteLine(ex.ToString()); this.WriteLine("----------"); this.WriteLine("Restore failed"); this.WriteLine(ex.Message); return 1; } }); }); app.Command("pack", c => { c.Description = "Bundle application for deployment"; var argProject = c.Argument("[project]", "Path to project, default is current directory"); var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment", CommandOptionType.SingleValue); var optionOverwrite = c.Option("--overwrite", "Remove existing files in target folders", CommandOptionType.NoValue); var optionNoSource = c.Option("--no-source", "Don't include sources of project dependencies", CommandOptionType.NoValue); var optionRuntime = c.Option("--runtime <KRE>", "Names or paths to KRE files to include", CommandOptionType.MultipleValue); var optionAppFolder = c.Option("--appfolder <NAME>", "Determine the name of the application primary folder", CommandOptionType.SingleValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { Console.WriteLine("verbose:{0} out:{1} project:{2}", optionVerbose.HasValue(), optionOut.Value(), argProject.Value); var options = new PackOptions { OutputDir = optionOut.Value(), ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(), AppFolder = optionAppFolder.Value(), Configuration = optionConfiguration.Value() ?? "Debug", RuntimeTargetFramework = _environment.TargetFramework, Overwrite = optionOverwrite.HasValue(), NoSource = optionNoSource.HasValue(), Runtimes = optionRuntime.HasValue() ? string.Join(";", optionRuntime.Values). Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) : new string[0], }; var manager = new PackManager(_hostServices, options); if (!manager.Package()) { return -1; } return 0; }); }); app.Command("build", c => { c.Description = "Build NuGet packages for the project in given directory"; var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue); var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue); var optionCheck = c.Option("--check", "Check diagnostics", CommandOptionType.NoValue); var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue); var argProjectDir = c.Argument("[project]", "Project to build, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var buildOptions = new BuildOptions(); buildOptions.RuntimeTargetFramework = _environment.TargetFramework; buildOptions.OutputDir = optionOut.Value(); buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory(); buildOptions.CheckDiagnostics = optionCheck.HasValue(); buildOptions.Configurations = optionConfiguration.Values; buildOptions.TargetFrameworks = optionFramework.Values; var projectManager = new BuildManager(_hostServices, buildOptions); if (!projectManager.Build()) { return -1; } return 0; }); }); app.Command("add", c => { c.Description = "Add a dependency into dependencies section of project.json"; var argName = c.Argument("[name]", "Name of the dependency to add"); var argVersion = c.Argument("[version]", "Version of the dependency to add"); var argProject = c.Argument("[project]", "Path to project, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var command = new AddCommand(); command.Report = this; command.Name = argName.Value; command.Version = argVersion.Value; command.ProjectDir = argProject.Value; var success = command.ExecuteCommand(); return success ? 0 : 1; }); }); return app.Execute(args); }
private bool ParseArgs(string[] args, out DefaultHostOptions defaultHostOptions, out string[] outArgs, out int exitCode) { var app = new CommandLineApplication(throwOnUnexpectedArg: false); app.Name = "Microsoft.Framework.ApplicationHost"; app.FullName = app.Name; var optionWatch = app.Option("--watch", "Watch file changes", CommandOptionType.NoValue); var optionPackages = app.Option("--packages <PACKAGE_DIR>", "Directory containing packages", CommandOptionType.SingleValue); var optionConfiguration = app.Option("--configuration <CONFIGURATION>", "The configuration to run under", CommandOptionType.SingleValue); var optionCompilationServer = app.Option("--port <PORT>", "The port to the compilation server", CommandOptionType.SingleValue); var runCmdExecuted = false; app.HelpOption("-?|-h|--help"); var env = (IRuntimeEnvironment)_serviceProvider.GetService(typeof(IRuntimeEnvironment)); app.VersionOption("--version", () => env.GetShortVersion(), () => env.GetFullVersion()); var runCmd = app.Command("run", c => { // We don't actually execute "run" command here // We are adding this command for the purpose of displaying correct help information c.Description = "Run application"; c.OnExecute(() => { runCmdExecuted = true; return 0; }); }, addHelpCommand: false, throwOnUnexpectedArg: false); app.Execute(args); defaultHostOptions = null; outArgs = null; exitCode = 0; if (app.IsShowingInformation) { // If help option or version option was specified, exit immediately with 0 exit code return true; } else if (!(app.RemainingArguments.Any() || runCmdExecuted)) { // If no subcommand was specified, show error message // and exit immediately with non-zero exit code Console.WriteLine("Please specify the command to run"); exitCode = 2; return true; } defaultHostOptions = new DefaultHostOptions(); defaultHostOptions.WatchFiles = optionWatch.HasValue(); defaultHostOptions.PackageDirectory = optionPackages.Value(); defaultHostOptions.TargetFramework = _environment.RuntimeFramework; defaultHostOptions.Configuration = optionConfiguration.Value() ?? _environment.Configuration ?? "Debug"; defaultHostOptions.ApplicationBaseDirectory = _environment.ApplicationBasePath; var portValue = optionCompilationServer.Value() ?? Environment.GetEnvironmentVariable(EnvironmentNames.CompilationServerPort); int port; if (!string.IsNullOrEmpty(portValue) && int.TryParse(portValue, out port)) { defaultHostOptions.CompilationServerPort = port; } var remainingArgs = new List<string>(); if (runCmdExecuted) { // Later logic will execute "run" command // So we put this argment back after it was consumed by parser remainingArgs.Add("run"); remainingArgs.AddRange(runCmd.RemainingArguments); } else { remainingArgs.AddRange(app.RemainingArguments); } if (remainingArgs.Any()) { defaultHostOptions.ApplicationName = remainingArgs[0]; outArgs = remainingArgs.Skip(1).ToArray(); } else { outArgs = remainingArgs.ToArray(); } return false; }
public int Main(string[] args) { // We want to allow unexpected args, in case future VS needs to pass anything in that we don't current. // This will allow us to retain backwards compatibility. var application = new CommandLineApplication(throwOnUnexpectedArg: false); application.HelpOption("-?|-h|--help"); var env = (IApplicationEnvironment)_services.GetService(typeof(IApplicationEnvironment)); var portOption = application.Option("--port", "Port number to listen for a connection.", CommandOptionType.SingleValue); var projectOption = application.Option("--project", "Path to a project file.", CommandOptionType.SingleValue); var debugOption = application.Option("--debug", "Launch the debugger", CommandOptionType.NoValue); var waitOption = application.Option("--wait", "Wait for attach", CommandOptionType.NoValue); // If no command was specified at the commandline, then wait for a command via message. application.OnExecute(async () => { if (debugOption.HasValue()) { Debugger.Launch(); } if (waitOption.HasValue()) { Thread.Sleep(10 * 1000); } var projectPath = projectOption.Value() ?? env.ApplicationBasePath; var port = int.Parse(portOption.Value()); Console.WriteLine("Listening on port {0}", port); using (var channel = await ReportingChannel.ListenOn(port)) { Console.WriteLine("Client accepted {0}", channel.Socket.LocalEndPoint); try { string testCommand = null; Project project = null; if (Project.TryGetProject(projectPath, out project, diagnostics: null)) { project.Commands.TryGetValue("test", out testCommand); } if (testCommand == null) { // No test command means no tests. Trace.TraceInformation("[ReportingChannel]: OnTransmit(ExecuteTests)"); channel.Send(new Message() { MessageType = "TestExecution.Response", }); return -1; } var message = channel.ReadQueue.Take(); // The message might be a request to negotiate protocol version. For now we only know // about version 1. if (message.MessageType == "ProtocolVersion") { var version = message.Payload?.ToObject<ProtocolVersionMessage>().Version; var supportedVersion = 1; Trace.TraceInformation( "[ReportingChannel]: Requested Version: {0} - Using Version: {1}", version, supportedVersion); channel.Send(new Message() { MessageType = "ProtocolVersion", Payload = JToken.FromObject(new ProtocolVersionMessage() { Version = supportedVersion, }), }); // Take the next message, which should be the command to execute. message = channel.ReadQueue.Take(); } if (message.MessageType == "TestDiscovery.Start") { var commandArgs = new string[] { "--list", "--designtime" }; var testServices = TestServices.CreateTestServices(_services, project, channel); await ProjectCommand.Execute(testServices, project, "test", commandArgs); Trace.TraceInformation("[ReportingChannel]: OnTransmit(DiscoverTests)"); channel.Send(new Message() { MessageType = "TestDiscovery.Response", }); return 0; } else if (message.MessageType == "TestExecution.Start") { var commandArgs = new List<string>() { "--designtime" }; var tests = message.Payload?.ToObject<RunTestsMessage>().Tests; if (tests != null) { foreach (var test in tests) { commandArgs.Add("--test"); commandArgs.Add(test); } } var testServices = TestServices.CreateTestServices(_services, project, channel); await ProjectCommand.Execute(testServices, project, "test", commandArgs.ToArray()); Trace.TraceInformation("[ReportingChannel]: OnTransmit(ExecuteTests)"); channel.Send(new Message() { MessageType = "TestExecution.Response", }); return 0; } else { var error = string.Format("Unexpected message type: '{0}'.", message.MessageType); Trace.TraceError(error); channel.SendError(error); return -1; } } catch (Exception ex) { Trace.TraceError(ex.ToString()); channel.SendError(ex); return -2; } } }); application.Command("list", command => { command.Name = "list"; command.Description = "Lists all available tests."; command.OnExecute(async () => { if (debugOption.HasValue()) { Debugger.Launch(); } if (waitOption.HasValue()) { Thread.Sleep(10 * 1000); } var projectPath = projectOption.Value() ?? env.ApplicationBasePath; var port = int.Parse(portOption.Value()); return await DiscoverTests(port, projectPath); }); }); application.Command("run", command => { command.Name = "run"; command.Description = "Runs specified tests."; var tests = command.Option("--test <test>", "test to run", CommandOptionType.MultipleValue); command.OnExecute(async () => { if (debugOption.HasValue()) { Debugger.Launch(); } if (waitOption.HasValue()) { Thread.Sleep(10 * 1000); } var projectPath = projectOption.Value() ?? env.ApplicationBasePath; var port = int.Parse(portOption.Value()); return await ExecuteTests(port, projectPath, tests.Values); }); }); return application.Execute(args); }
public int Main(string[] args) { var app = new CommandLineApplication(); app.Name = "kpm"; var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue); app.HelpOption("-?|-h|--help"); app.VersionOption("--version", GetVersion()); // Show help information if no subcommand/option was specified app.OnExecute(() => { app.ShowHelp(); return 2; }); app.Command("restore", c => { c.Description = "Restore packages"; var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json."); var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command", CommandOptionType.MultipleValue); var optFallbackSource = c.Option("-f|--fallbacksource <FEED>", "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue); var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages", CommandOptionType.SingleValue); var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue); var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue); var optQuiet = c.Option("--quiet", "Do not show output such as HTTP request/cache information", CommandOptionType.NoValue); var optIgnoreFailedSources = c.Option("--ignore-failed-sources", "Ignore failed remote sources if there are local packages meeting version requirements", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var command = new RestoreCommand(_environment); command.Reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue()); command.RestoreDirectory = argRoot.Value; command.Sources = optSource.Values; command.FallbackSources = optFallbackSource.Values; command.NoCache = optNoCache.HasValue(); command.PackageFolder = optPackageFolder.Value(); command.IgnoreFailedSources = optIgnoreFailedSources.HasValue(); if (optProxy.HasValue()) { Environment.SetEnvironmentVariable("http_proxy", optProxy.Value()); } var success = await command.ExecuteCommand(); return success ? 0 : 1; }); }); app.Command("bundle", c => { c.Description = "Bundle application for deployment"; var argProject = c.Argument("[project]", "Path to project, default is current directory"); var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})", CommandOptionType.SingleValue); var optionOverwrite = c.Option("--overwrite", "Remove existing files in target folders", CommandOptionType.NoValue); var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages", CommandOptionType.NoValue); var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include", CommandOptionType.MultipleValue); var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.", CommandOptionType.NoValue); var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory", CommandOptionType.SingleValue); var optionWwwRootOut = c.Option("--wwwroot-out <NAME>", "Name of public folder in the bundle, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified", CommandOptionType.SingleValue); var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of bundled files", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var options = new BundleOptions { OutputDir = optionOut.Value(), ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(), Configuration = optionConfiguration.Value() ?? "Debug", RuntimeTargetFramework = _environment.RuntimeFramework, WwwRoot = optionWwwRoot.Value(), WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(), Overwrite = optionOverwrite.HasValue(), NoSource = optionNoSource.HasValue(), Runtimes = optionRuntime.HasValue() ? string.Join(";", optionRuntime.Values). Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) : new string[0], Native = optionNative.HasValue(), Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()) }; var manager = new BundleManager(_hostServices, options); if (!manager.Bundle()) { return -1; } return 0; }); }); app.Command("pack", c => { c.Description = "Build NuGet packages for the project in given directory"; var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue); var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue); var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue); var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of nupkgs", CommandOptionType.NoValue); var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var buildOptions = new BuildOptions(); buildOptions.OutputDir = optionOut.Value(); buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory(); buildOptions.Configurations = optionConfiguration.Values; buildOptions.TargetFrameworks = optionFramework.Values; buildOptions.GeneratePackages = true; buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()); var projectManager = new BuildManager(_hostServices, buildOptions); if (!projectManager.Build()) { return -1; } return 0; }); }); app.Command("build", c => { c.Description = "Produce assemblies for the project in given directory"; var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue); var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue); var optionQuiet = c.Option("--quiet", "Do not show output such as dependencies in use", CommandOptionType.NoValue); var argProjectDir = c.Argument("[project]", "Project to build, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var buildOptions = new BuildOptions(); buildOptions.OutputDir = optionOut.Value(); buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory(); buildOptions.Configurations = optionConfiguration.Values; buildOptions.TargetFrameworks = optionFramework.Values; buildOptions.GeneratePackages = false; buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()); var projectManager = new BuildManager(_hostServices, buildOptions); if (!projectManager.Build()) { return -1; } return 0; }); }); app.Command("add", c => { c.Description = "Add a dependency into dependencies section of project.json"; var argName = c.Argument("[name]", "Name of the dependency to add"); var argVersion = c.Argument("[version]", "Version of the dependency to add"); var argProject = c.Argument("[project]", "Path to project, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); var command = new AddCommand(); command.Reports = reports; command.Name = argName.Value; command.Version = argVersion.Value; command.ProjectDir = argProject.Value; var success = command.ExecuteCommand(); return success ? 0 : 1; }); }); app.Command("install", c => { c.Description = "Install the given dependency"; var argName = c.Argument("[name]", "Name of the dependency to add"); var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version."); var argProject = c.Argument("[project]", "Path to project, default is current directory"); var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command", CommandOptionType.MultipleValue); var optFallbackSource = c.Option("-f|--fallbacksource <FEED>", "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue); var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages", CommandOptionType.SingleValue); var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue); var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue); var optQuiet = c.Option("--quiet", "Do not show output such as HTTP request/cache information", CommandOptionType.NoValue); var optIgnoreFailedSources = c.Option("--ignore-failed-sources", "Ignore failed remote sources if there are local packages meeting version requirements", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue()); var addCmd = new AddCommand(); addCmd.Reports = reports; addCmd.Name = argName.Value; addCmd.Version = argVersion.Value; addCmd.ProjectDir = argProject.Value; var restoreCmd = new RestoreCommand(_environment); restoreCmd.Reports = reports; restoreCmd.RestoreDirectory = argProject.Value; restoreCmd.Sources = optSource.Values; restoreCmd.FallbackSources = optFallbackSource.Values; restoreCmd.NoCache = optNoCache.HasValue(); restoreCmd.PackageFolder = optPackageFolder.Value(); restoreCmd.IgnoreFailedSources = optIgnoreFailedSources.HasValue(); if (optProxy.HasValue()) { Environment.SetEnvironmentVariable("http_proxy", optProxy.Value()); } var installCmd = new InstallCommand(addCmd, restoreCmd); installCmd.Reports = reports; var success = await installCmd.ExecuteCommand(); return success ? 0 : 1; }); }); app.Command("packages", packagesCommand => { packagesCommand.Description = "Commands related to managing local and remote packages folders"; packagesCommand.HelpOption("-?|-h|--help"); packagesCommand.OnExecute(() => { packagesCommand.ShowHelp(); return 2; }); packagesCommand.Command("add", c => { c.Description = "Add a NuGet package to the specified packages folder"; var argNupkg = c.Argument("[nupkg]", "Path to a NuGet package"); var argSource = c.Argument("[source]", "Path to packages folder"); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var options = new AddOptions { Reports = CreateReports(optionVerbose.HasValue(), quiet: false), SourcePackages = argSource.Value, NuGetPackage = argNupkg.Value }; var command = new Packages.AddCommand(options); var success = await command.Execute(); return success ? 0 : 1; }); }); packagesCommand.Command("push", c => { c.Description = "Incremental copy of files from local packages to remote location"; var argRemote = c.Argument("[remote]", "Path to remote packages folder"); var argSource = c.Argument("[source]", "Path to source packages folder, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); // Implicitly commit changes before push var commitOptions = new CommitOptions { Reports = reports, SourcePackages = argSource.Value }; var commitCommand = new CommitCommand(commitOptions); var success = commitCommand.Execute(); if (!success) { return 1; } var pushOptions = new PushOptions { Reports = reports, SourcePackages = argSource.Value, RemotePackages = argRemote.Value }; var pushCommand = new PushCommand(pushOptions); success = pushCommand.Execute(); return success ? 0 : 1; }); }); packagesCommand.Command("pull", c => { c.Description = "Incremental copy of files from remote location to local packages"; var argRemote = c.Argument("[remote]", "Path to remote packages folder"); var argSource = c.Argument("[source]", "Path to source packages folder, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); bool success; if (Directory.Exists(argSource.Value)) { // Implicitly commit changes before pull var commitOptions = new CommitOptions { Reports = reports, SourcePackages = argSource.Value }; var commitCommand = new CommitCommand(commitOptions); success = commitCommand.Execute(); if (!success) { return 1; } } var pullOptions = new PullOptions { Reports = reports, SourcePackages = argSource.Value, RemotePackages = argRemote.Value }; var pullCommand = new PullCommand(pullOptions); success = pullCommand.Execute(); return success ? 0 : 1; }); }); }); app.Command("list", c => { c.Description = "Print the dependencies of a given project."; var showAssemblies = c.Option("-a|--assemblies", "Show the assembly files that are depended on by given project.", CommandOptionType.NoValue); var framework = c.Option("--framework", "Show dependencies for only the given framework.", CommandOptionType.SingleValue); var runtimeFolder = c.Option("--runtime", "The folder containing all available framework assemblies.", CommandOptionType.SingleValue); var argProject = c.Argument("[project]", "The path to project. If omitted, the command will use the project in the current directory."); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject, framework) { ShowAssemblies = showAssemblies.HasValue(), RuntimeFolder = runtimeFolder.Value(), }; if (!options.Valid) { if (options.Project == null) { options.Reports.Error.WriteLine(string.Format("A project could not be found in {0}.", options.Path).Red()); return 1; } else { options.Reports.Error.WriteLine("Invalid options.".Red()); return 2; } } var command = new DependencyListCommand(options); return command.Execute(); }); }); // "kpm wrap" invokes MSBuild, which is not available on *nix if (!PlatformHelper.IsMono) { app.Command("wrap", c => { c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files"; var argPath = c.Argument("[path]", "Path to csproj to be wrapped"); var optConfiguration = c.Option("--configuration <CONFIGURATION>", "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue); var optMsBuildPath = c.Option("--msbuild <PATH>", @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'", CommandOptionType.SingleValue); var optInPlace = c.Option("-i|--in-place", "Generate or update project.json files in project directories of csprojs", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); var command = new WrapCommand(); command.Reports = reports; command.CsProjectPath = argPath.Value; command.Configuration = optConfiguration.Value(); command.MsBuildPath = optMsBuildPath.Value(); command.InPlace = optInPlace.HasValue(); var success = command.ExecuteCommand(); return success ? 0 : 1; }); }); } return app.Execute(args); }
public int Main(string[] args) { #if DEBUG // Add our own debug helper because DNU is usually run from a wrapper script, // making it too late to use the DNX one. Technically it's possible to use // the DNX_OPTIONS environment variable, but that's difficult to do per-command // on Windows if (args.Any(a => string.Equals(a, "--debug", StringComparison.OrdinalIgnoreCase))) { args = args.Where(a => !string.Equals(a, "--debug", StringComparison.OrdinalIgnoreCase)).ToArray(); Console.WriteLine($"Process Id: {Process.GetCurrentProcess().Id}"); Console.WriteLine("Waiting for Debugger to attach..."); SpinWait.SpinUntil(() => Debugger.IsAttached); } #endif var app = new CommandLineApplication(); app.Name = "dnu"; app.FullName = "Microsoft .NET Development Utility"; var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue); app.HelpOption("-?|-h|--help"); app.VersionOption("--version", () => _runtimeEnv.GetShortVersion(), () => _runtimeEnv.GetFullVersion()); // Show help information if no subcommand/option was specified app.OnExecute(() => { app.ShowHelp(); return 2; }); var reportsFactory = new ReportsFactory(_runtimeEnv, optionVerbose.HasValue()); BuildConsoleCommand.Register(app, reportsFactory, _hostServices); CommandsConsoleCommand.Register(app, reportsFactory, _environment); InstallConsoleCommand.Register(app, reportsFactory, _environment); ListConsoleCommand.Register(app, reportsFactory, _environment); PackConsoleCommand.Register(app, reportsFactory, _hostServices); PackagesConsoleCommand.Register(app, reportsFactory); PublishConsoleCommand.Register(app, reportsFactory, _environment, _hostServices); RestoreConsoleCommand.Register(app, reportsFactory, _environment); WrapConsoleCommand.Register(app, reportsFactory); return app.Execute(args); }
public void PropagatesAsyncExceptions() { var app = new CommandLineApplication(); app.OnExecute(async () => { await Task.Delay(5); throw new InvalidOperationException("this should throw"); }); var ex = Assert.Throws<AggregateException>(() => app.Execute()).InnerException; Assert.NotNull(ex); Assert.IsType<InvalidOperationException>(ex); Assert.Equal("this should throw", ex.Message); }
public void RemainingArgsArePassed() { CommandArgument first = null; CommandArgument second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Argument("first", "First argument"); second = c.Argument("second", "Second argument"); c.OnExecute(() => 0); }); app.Execute("test", "one", "two"); Assert.Equal("one", first.Value); Assert.Equal("two", second.Value); }
public virtual int Main([NotNull] string[] args) { Check.NotNull(args, nameof(args)); // TODO: Enable subcommands in help _app = new CommandLineApplication { Name = "ef" }; _app.VersionOption( "-v|--version", typeof(Program).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>() .InformationalVersion); _app.HelpOption("-h|--help"); _app.Command( "context", context => { context.Description = "Commands to manage your DbContext"; context.HelpOption("-h|--help"); context.Command( "list", list => { list.Description = "List the contexts"; list.HelpOption("-h|--help"); list.OnExecute(() => ListContexts()); }, addHelpCommand: false); context.OnExecute( () => { _app.ShowHelp(context.Name); return 0; }); }, addHelpCommand: false); _app.Command( "migration", migration => { migration.Description = "Commands to manage your Code First Migrations"; migration.HelpOption("-h|--help"); migration.Command( "add", add => { add.Description = "Add a new migration"; var name = add.Argument("[name]", "The name of the migration"); var context = add.Option( "-c|--context <context>", "The context class to use", CommandOptionType.SingleValue); var startupProject = add.Option( "-s|--startupProjectName <projectName>", "The name of the project to use as the startup project", CommandOptionType.SingleValue); add.HelpOption("-h|--help"); add.OnExecute( () => { if (name.Value == null) { _logger.LogError("Missing required argument '{0}'.", name.Name); migration.ShowHelp(add.Name); return 1; } return AddMigration(name.Value, context.Value(), startupProject.Value()); }); }, addHelpCommand: false); migration.Command( "apply", apply => { apply.Description = "Apply migrations to the database"; var migrationName = apply.Argument( "[migration]", "The migration to apply. Use '0' to unapply all migrations"); var context = apply.Option( "-c|--context <context>", "The context class to use", CommandOptionType.SingleValue); var startupProject = apply.Option( "-s|--startupProjectName <projectName>", "The name of the project to use as the startup project", CommandOptionType.SingleValue); apply.HelpOption("-h|--help"); apply.OnExecute(() => ApplyMigration(migrationName.Value, context.Value(), startupProject.Value())); }, addHelpCommand: false); migration.Command( "list", list => { list.Description = "List the migrations"; var context = list.Option( "-c|--context <context>", "The context class to use", CommandOptionType.SingleValue); list.HelpOption("-h|--help"); list.OnExecute(() => ListMigrations(context.Value())); }, addHelpCommand: false); migration.Command( "script", script => { script.Description = "Generate a SQL script from migrations"; var from = script.Argument("[from]", "The starting migration"); var to = script.Argument("[to]", "The ending migration"); var output = script.Option( "-o|--output <file>", "The file to write the script to instead of stdout", CommandOptionType.SingleValue); var idempotent = script.Option( "-i|--idempotent", "Generate an idempotent script", CommandOptionType.NoValue); var context = script.Option( "-c|--context <context>", "The context class to use", CommandOptionType.SingleValue); var startupProject = script.Option( "-s|--startupProjectName <projectName>", "The name of the project to use as the startup project", CommandOptionType.SingleValue); script.HelpOption("-h|--help"); script.OnExecute(() => ScriptMigration(from.Value, to.Value, output.Value(), idempotent.HasValue(), context.Value(), startupProject.Value())); }, addHelpCommand: false); migration.Command( "remove", remove => { remove.Description = "Remove the last migration"; var context = remove.Option( "-c|--context <context>", "The context class to use", CommandOptionType.SingleValue); remove.HelpOption("-h|--help"); remove.OnExecute(() => RemoveMigration(context.Value())); }, addHelpCommand: false); migration.OnExecute( () => { _app.ShowHelp(migration.Name); return 0; }); }, addHelpCommand: false); _app.Command( "revEng", revEng => { revEng.Description = "Command to reverse engineer code from a database"; revEng.HelpOption("-h|--help"); var connectionString = revEng.Argument( "[connectionString]", "The connection string of the database"); revEng.OnExecute(() => ReverseEngineer(connectionString.Value)); }, addHelpCommand: false); _app.Command( "help", help => { help.Description = "Show help information"; var command = help.Argument("[command]", "Command that help information explains"); help.OnExecute( () => { if (command.Value != null) { _app.ShowHelp(command.Value); return 0; } return ShowHelp(); }); }, addHelpCommand: false); _app.OnExecute(() => ShowHelp()); return _app.Execute(args); }
public void ThrowsExceptionOnUnexpectedSymbolOptionByDefault() { var unexpectedOption = "-?"; var app = new CommandLineApplication(); app.Command("test", c => { c.OnExecute(() => 0); }); var exception = Assert.Throws<Exception>(() => app.Execute("test", unexpectedOption)); Assert.Equal(string.Format("TODO: Error: unrecognized {0} '{1}'", "option", unexpectedOption), exception.Message); }
public int Main(string[] args) { try { #if NET45 || ASPNET50 if (args.Length > 0 && string.Equals(args[0], "dbg", StringComparison.OrdinalIgnoreCase)) { args = args.Skip(1).ToArray(); System.Diagnostics.Debugger.Launch(); } #endif var app = new CommandLineApplication(throwOnUnexpectedArg: false); app.Name = "ksigntool"; app.Description = "Signing tool for NuGet/ASP.Net 5 Packages"; app.HelpOption("-h|--help"); app.VersionOption("-v|--version", String.Format("{0} {1} (Runtime: {2}; Configuration: {3})", app.Name, _env.Version, _env.RuntimeFramework, _env.Configuration)); app.Command("sigreq", sigreq => { sigreq.Description = "Creates a signing request for the specific file"; var fileName = sigreq.Argument( "filename", "the name of the file to create a signature request for"); var outputFile = sigreq.Option( "-o|--output", "the name of the signature request file to create (defaults to the input filename with the '.sigreq' extension added)", CommandOptionType.SingleValue); var digestAlgorithm = sigreq.Option( "-alg|--algorithm", "the name of the digest algorithm to use", CommandOptionType.SingleValue); sigreq.OnExecute(() => Commands.CreateSigningRequest( fileName.Value, outputFile.Value(), digestAlgorithm.Value())); }, addHelpCommand: false); app.Command("sign", sign => { sign.Description = "Signs a file"; var fileName = sign.Argument("filename", "the name of the file to sign"); sign.Option("-a|--auto-select", "select the best signing cert automatically (the one valid for the longest time from now)", CommandOptionType.NoValue); sign.Option("-f|--file <certificateFile>", "the path to a file containing certificates to sign with", CommandOptionType.SingleValue); sign.Option("-ac|--add-certs <addCertificatesFile>", "add additional certficiates from <certificatesFile> to the signature block", CommandOptionType.SingleValue); sign.Option("-i|--issuer <issuerName>", "specify the Issuer of the signing cert, or a substring", CommandOptionType.SingleValue); sign.Option("-n|--subject <subjectName>", "specify the Subject Name of the signing cert, or a substring", CommandOptionType.SingleValue); sign.Option("-p|--password <password>", "the password for the file specified by <certificateFile>", CommandOptionType.SingleValue); sign.Option("-s|--store <storeName>", "specify the Store to open when searching for the cert (defaults to the 'My' Store)", CommandOptionType.SingleValue); sign.Option("-sm|--machine-store", "open a machine Store instead of a user Store", CommandOptionType.SingleValue); sign.Option("-sha1|--thumbprint <certhash>", "specifies the SHA1 thumbprint of the certificate to use to sign the file", CommandOptionType.SingleValue); sign.Option("-csp|--key-provider <cspname>", "specify the CSP containing the Private Key Container", CommandOptionType.SingleValue); sign.Option("-kc|--key-container <containername>", "specify the Key Container Name of the Private Key", CommandOptionType.SingleValue); sign.Option("-o|--output <outputFile>", "the path to the signature file to output (by default, the existing file name plus '.sig' is used)", CommandOptionType.SingleValue); sign.Option("-t|-tr|--timestamper <timestampAuthorityUrl>", "a URL to an RFC3161-compliant timestamping authority to timestamp the signature with", CommandOptionType.SingleValue); sign.Option("-td|--timestamper-algorithm <algorithmName>", "the name of the hash algorithm to use for the timestamp", CommandOptionType.SingleValue); sign.OnExecute(() => Commands.Sign(fileName.Value, sign.Options)); }, addHelpCommand: false); app.Command("timestamp", timestamp => { timestamp.Description = "Timestamps an existing signature"; var signature = timestamp.Argument("signature", "the path to the signature file"); var authority = timestamp.Argument("url", "the path to a Authenticode trusted timestamping authority"); var algorithm = timestamp.Option("-alg|--algorithm <algorithmName>", "the name of the hash algorithm to use for the timestamp", CommandOptionType.SingleValue); timestamp.OnExecute(() => Commands.Timestamp(signature.Value, authority.Value, algorithm.Value())); }, addHelpCommand: false); app.Command("verify", verify => { verify.Description = "Verifies a signature file"; var fileName = verify.Argument("filename", "the name of the signature file to view"); var noCheckCerts = verify.Option("-nocerts|--ignore-certificate-errors", "set this switch to ignore errors caused by untrusted certificates", CommandOptionType.NoValue); var skipRevocation = verify.Option("-norevoke|--skip-revocation-check", "set this switch to ignore revocation check failures", CommandOptionType.NoValue); var targetFile = verify.Option("-t|--target-file <targetFile>", "check the signature against <targetFile> (usually read from signature data)", CommandOptionType.SingleValue); verify.OnExecute(() => Commands.Verify(fileName.Value, targetFile.Value(), !noCheckCerts.HasValue(), skipRevocation.HasValue())); }, addHelpCommand: false); app.Command("help", help => { help.Description = "Get help on the application, or a specific command"; var command = help.Argument("command", "the command to get help on"); help.OnExecute(() => { app.ShowHelp(command.Value); return 0; }); }, addHelpCommand: false); app.OnExecute(() => { app.ShowHelp(commandName: null); return 0; }); return app.Execute(args); } catch(Exception ex) { AnsiConsole.Error.WriteLine(ex.ToString()); return 1; } }
public void ValuesMayBeAttachedToSwitch() { CommandOption first = null; CommandOption second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Option("--first <NAME>", "First argument", CommandOptionType.SingleValue); second = c.Option("--second <NAME>", "Second argument", CommandOptionType.SingleValue); c.OnExecute(() => 0); }); app.Execute("test", "--first=one", "--second:two"); Assert.Equal("one", first.Values[0]); Assert.Equal("two", second.Values[0]); }
static int Main(string[] args) { var app = new CommandLineApplication(); var pkgRoot = app.Option("--root|-r", "Package root directory", CommandOptionType.SingleValue); var outputRoot = app.Option("--out|-o", "Output directory", CommandOptionType.SingleValue); app.OnExecute(() => { var di = new DirectoryInfo(pkgRoot.Value()); var outRoot = String.IsNullOrEmpty(outputRoot.Value()) ? "help" : outputRoot.Value(); foreach (var indexDir in di.EnumerateDirectories("_indexes", SearchOption.AllDirectories)) { var pkgName = indexDir.Parent.Parent.Name; var cmdletIndexFilePath = Path.Combine(indexDir.FullName, "_cmdlets.idx"); if (File.Exists(cmdletIndexFilePath)) { var contentDir = Path.Combine(indexDir.Parent.FullName, "content"); var helpDir = Path.Combine(outRoot, pkgName); var libDir = Path.Combine(indexDir.Parent.FullName, "lib"); foreach (var cmdletRow in File.ReadAllLines(cmdletIndexFilePath)) { var keys = cmdletRow.Split(':')[0]; var assemblyAndType = cmdletRow.Split(':')[1]; var assembly = assemblyAndType.Split('/')[0]; var typeName = assemblyAndType.Split('/')[1]; var libDirectoryInfo = new DirectoryInfo(libDir); var assemblyFileInfo = libDirectoryInfo.GetFiles(assembly, SearchOption.AllDirectories).FirstOrDefault(); if (assemblyFileInfo != null) { var loader = new Loader(assemblyFileInfo.DirectoryName); PlatformServices.Default.AssemblyLoaderContainer.AddLoader(loader); var assemblyName = assembly.Substring(0, assembly.Length - ".dll".Length); var loadedAssembly = loader.LoadFromAssemblyName(new System.Reflection.AssemblyName(assemblyName)); var type = loadedAssembly.GetType(typeName); var help = GenerateHelp(contentDir, assembly, keys, type); var helpFile = Path.Combine(helpDir, keys.Replace(';', '.') + ".hlp"); if (!Directory.Exists(helpDir)) { Directory.CreateDirectory(helpDir); } if (File.Exists(helpFile)) { Console.WriteLine($"File {helpFile} already exists - skipping!"); } else { File.WriteAllLines(helpFile, help); } } } } } return 0; }); return app.Execute(args); }
public virtual int Main(string[] args) { var app = new CommandLineApplication { Name = "ef", FullName = "Entity Framework 6 Commands" }; app.VersionOption( "--version", typeof(Program).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>() .InformationalVersion); app.HelpOption("-?|-h|--help"); app.OnExecute( () => { app.ShowHelp(); return 0; }); app.Command("add", add => { add.Description = "Add a new migration"; AddHelp(add); var name = add.Argument("[name]", "Migration name label"); var connectionString = add.Option("-c|--connectionstring", "The connection string", CommandOptionType.SingleValue); var providerName = add.Option("-p|--provider", "The provider name", CommandOptionType.SingleValue); var ignoreChanges = add.Option( "-i|--ignore", "Ignore model changes", CommandOptionType.NoValue); add.OnExecute(() => { if (string.IsNullOrEmpty(name.Value)) { _logger.LogError("Missing required argument '{0}'", name.Name); add.ShowHelp(); return 1; } _migrator.AddMigration(name.Value, GetConfiguration(connectionString, providerName), ignoreChanges.HasValue()); return 0; } ); }); app.Command("update", update => { update.Description = "Update a target database with any schema changes"; AddHelp(update); var connectionString = update.Option("-c|--connectionstring", "The connection string", CommandOptionType.SingleValue); var providerName = update.Option("-p|--provider", "The provider name", CommandOptionType.SingleValue); update.OnExecute(() => { var config = GetConfiguration(connectionString, providerName); return _migrator.UpdateDatabase(config); }); }); return app.Execute(args); }
public static Task<int> ExecuteAsync(string[] args) { var app = new CommandLineApplication(throwOnUnexpectedArg: false); app.Name = Constants.BootstrapperExeName; app.FullName = Constants.BootstrapperFullName; // These options were handled in the native code, but got passed through here. // We just need to capture them and clean them up. var optionAppbase = app.Option("--appbase <PATH>", "Application base directory path", CommandOptionType.SingleValue); var optionLib = app.Option("--lib <LIB_PATHS>", "Paths used for library look-up", CommandOptionType.MultipleValue); var optionDebug = app.Option("--debug", "Waits for the debugger to attach before beginning execution.", CommandOptionType.NoValue); var env = new RuntimeEnvironment(); app.HelpOption("-?|-h|--help"); app.VersionOption("--version", () => env.GetShortVersion(), () => env.GetFullVersion()); // Options below are only for help info display // They will be forwarded to Microsoft.Framework.ApplicationHost var optionsToForward = new[] { app.Option("--watch", "Watch file changes", CommandOptionType.NoValue), app.Option("--packages <PACKAGE_DIR>", "Directory containing packages", CommandOptionType.SingleValue), app.Option("--configuration <CONFIGURATION>", "The configuration to run under", CommandOptionType.SingleValue), app.Option("--port <PORT>", "The port to the compilation server", CommandOptionType.SingleValue) }; app.Execute(args); // Help information was already shown because help option was specified if (app.IsShowingInformation) { return Task.FromResult(0); } // Show help information if no subcommand/option was specified if (!app.IsShowingInformation && app.RemainingArguments.Count == 0) { app.ShowHelp(); return Task.FromResult(2); } // Some options should be forwarded to Microsoft.Framework.ApplicationHost var appHostName = "Microsoft.Framework.ApplicationHost"; var appHostIndex = app.RemainingArguments.FindIndex(s => string.Equals(s, appHostName, StringComparison.OrdinalIgnoreCase)); foreach (var option in optionsToForward) { if (option.HasValue()) { if (appHostIndex < 0) { Console.WriteLine("The option '--{0}' can only be used with {1}", option.LongName, appHostName); return Task.FromResult(1); } if (option.OptionType == CommandOptionType.NoValue) { app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName); } else if (option.OptionType == CommandOptionType.SingleValue) { app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName); app.RemainingArguments.Insert(appHostIndex + 2, option.Value()); } else if (option.OptionType == CommandOptionType.MultipleValue) { foreach (var value in option.Values) { app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName); app.RemainingArguments.Insert(appHostIndex + 2, value); } } } } // Resolve the lib paths IEnumerable<string> searchPaths = ResolveSearchPaths(optionLib.Values, app.RemainingArguments); var bootstrapper = new Bootstrapper(searchPaths); return bootstrapper.RunAsync(app.RemainingArguments, env); }