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);
        }
示例#2
0
文件: Program.cs 项目: nagyistoce/dnx
        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);
        }
示例#3
0
文件: Program.cs 项目: noahfalk/dnx
        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;
        }
示例#4
0
文件: Program.cs 项目: noahfalk/dnx
        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);
            SourcesConsoleCommand.Register(app, reportsFactory);
            WrapConsoleCommand.Register(app, reportsFactory);
            FeedsConsoleCommand.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 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);
        }
示例#7
0
        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);
        }
示例#8
0
        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);
        }
示例#9
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);
        }
示例#10
0
        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);
        }
示例#11
0
        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);
        }
示例#12
0
文件: Program.cs 项目: nagyistoce/dnx
        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);
        }
示例#13
0
文件: Program.cs 项目: hy7pcq/Caching
        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;
            }
        }
示例#14
0
        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;
            }
        }
示例#15
0
文件: Program.cs 项目: elanwu123/dnx
        public int Main(string[] args)
        {
            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", 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 feedOptions = FeedOptions.Add(c);
                var optLock = c.Option("--lock",
                    "Creates dependencies file with locked property set to true. Overwrites file if it exists.",
                    CommandOptionType.NoValue);
                var optUnlock = c.Option("--unlock",
                    "Creates dependencies file with locked property set to false. Overwrites file if it exists.",
                    CommandOptionType.NoValue);
                var optParallel = c.Option("--parallel",
                    "Restores in parallel when more than one project.json is discovered.",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var command = new RestoreCommand(_environment);
                    command.Reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);
                    command.RestoreDirectory = argRoot.Value;
                    command.FeedOptions = feedOptions;
                    command.Lock = optLock.HasValue();
                    command.Unlock = optUnlock.HasValue();
                    command.Parallel = optParallel.HasValue();

                    if (feedOptions.ProxyOptions.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var success = await command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            app.Command("publish", c =>
            {
                c.Description = "Publish 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 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, or \"active\" for current runtime on PATH",
                    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 output, 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 published files",
                    CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new PublishOptions
                    {
                        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(),
                        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 PublishManager(_hostServices, options);
                    if (!manager.Publish())
                    {
                        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("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 feedOptions = FeedOptions.Add(c);

                c.HelpOption("-?|-h|--help");

                c.OnExecute(async () =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);

                    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.FeedOptions = feedOptions;

                    restoreCmd.RestoreDirectory = argProject.Value;

                    if (feedOptions.ProxyOptions.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    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 frameworks = c.Option("--framework <TARGET_FRAMEWORK>",
                    "Show dependencies for only the given frameworks",
                    CommandOptionType.MultipleValue);
                var runtimeFolder = c.Option("--runtime <PATH>",
                    "The folder containing all available framework assemblies",
                    CommandOptionType.SingleValue);
                var hideDependents = c.Option("--hide-dependents",
                    "Hide the immediate dependents of libraries referenced in the project",
                    CommandOptionType.NoValue);
                var resultsFilter = c.Option("--filter <PATTERN>",
                    "Filter the libraries referenced by the project base on their names. The matching pattern supports * and ?",
                    CommandOptionType.SingleValue);
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject)
                    {
                        TargetFrameworks = frameworks.Values,
                        ShowAssemblies = showAssemblies.HasValue(),
                        RuntimeFolder = runtimeFolder.Value(),
                        HideDependents = hideDependents.HasValue(),
                        ResultsFilter = resultsFilter.Value()
                    };

                    if (!options.Valid)
                    {
                        if (options.Project == null)
                        {
                            options.Reports.Error.WriteLine(string.Format("Unable to locate {0}.".Red(), Runtime.Project.ProjectFileName));
                            return 1;
                        }
                        else
                        {
                            options.Reports.Error.WriteLine("Invalid options.".Red());
                            return 2;
                        }
                    }

                    var command = new DependencyListCommand(options, _environment.RuntimeFramework);
                    return command.Execute();
                });
            });

            app.Command("commands", cmd =>
            {
                cmd.Description = "Commands related to managing application commands (add, remove)";
                cmd.HelpOption("-?|-h|--help");
                cmd.OnExecute(() =>
                {
                    cmd.ShowHelp();
                    return 2;
                });

                cmd.Command("install", c =>
                {
                    c.Description = "Installs application commands";

                    var argPackage = c.Argument("[package]", "The name of the application package");
                    var argVersion = c.Argument("[version]", "The version of the application package");

                    var optOverwrite = c.Option("-o|--overwrite", "Overwrites conflicting commands", CommandOptionType.NoValue);

                    var feedOptions = FeedOptions.Add(c);

                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(async () =>
                    {
                        var command = new InstallGlobalCommand(
                                _environment,
                                string.IsNullOrEmpty(feedOptions.TargetPackagesFolder) ?
                                    AppCommandsFolderRepository.CreateDefault() :
                                    AppCommandsFolderRepository.Create(feedOptions.TargetPackagesFolder));

                        command.FeedOptions = feedOptions;
                        command.Reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet);
                        command.OverwriteCommands = optOverwrite.HasValue();

                        if (feedOptions.Proxy != null)
                        {
                            Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                        }

                        var success = await command.Execute(argPackage.Value, argVersion.Value);
                        return success ? 0 : 1;
                    });

                });

                cmd.Command("uninstall", c =>
                {
                    c.Description = "Uninstalls application commands";

                    var argCommand = c.Argument("[command]", "The name of the command to uninstall");

                    var optNoPurge = c.Option("--no-purge", "Do not try to remove orphaned packages", CommandOptionType.NoValue);

                    c.HelpOption("-?|-h|--help");

                    c.OnExecute(() =>
                    {
                        var command = new UninstallCommand(
                            _environment,
                            AppCommandsFolderRepository.CreateDefault(),
                            reports: CreateReports(optionVerbose.HasValue(), quiet: false));

                        command.NoPurge = optNoPurge.HasValue();

                        var success = command.Execute(argCommand.Value);
                        return success ? 0 : 1;
                    });
                });
            });

            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);
                var optFramework = c.Option("-f|--framework",
                    "Target framework of assembly to be wrapped",
                    CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                    var command = new WrapCommand();
                    command.Reports = reports;
                    command.InputFilePath = argPath.Value;
                    command.Configuration = optConfiguration.Value();
                    command.MsBuildPath = optMsBuildPath.Value();
                    command.InPlace = optInPlace.HasValue();
                    command.Framework = optFramework.Value();

                    var success = command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            return app.Execute(args);
        }