Ejemplo n.º 1
0
        private static void RegisterAddSubcommand(CommandLineApplication packagesCmd, ReportsFactory reportsFactory)
        {
            packagesCmd.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 () =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var options = new AddOptions
                    {
                        Reports = reportsFactory.CreateReports(quiet: false),
                        SourcePackages = argSource.Value,
                        NuGetPackage = argNupkg.Value
                    };
                    var command = new Packages.AddCommand(options);
                    var success = await command.Execute();
                    return success ? 0 : 1;
                });
            });
        }
        public void Arguments_HaveCorrectDescription_Returns_CorrectValue(
            string propertyName,
            string expectedDescription)
        {
            //Arrange
            var command = new CommandLineApplication();
            var property = typeof(TestClass).GetProperty(propertyName);
            var descriptor = new ParameterDescriptor(property);

            //Act
            descriptor.AddCommandLineParameterTo(command);

            //Assert
            var actualOption = command.Arguments.First();
            Assert.Equal(propertyName, actualOption.Name);
            Assert.Equal(expectedDescription, actualOption.Description);

            //Arrange
            command.Execute(new string[0] { });

            //Assert
            Assert.Equal(null, descriptor.Value); //Is this right assumption to test?

            //Arrange
            command.Execute(new string[] { "PassedValue" });

            //Assert
            Assert.Equal("PassedValue", descriptor.Value);
        }
Ejemplo n.º 3
0
        public void Main(string[] args)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false);
            app.Name = app.FullName = "Nine.Graphics.Test";
            app.HelpOption("-?|--help");

            var width = app.Option("--width <WIDTH>", "Set the width of the host window", CommandOptionType.SingleValue);
            var height = app.Option("--height <HEIGHT>", "Set the height of the host window", CommandOptionType.SingleValue);
            var topMost = app.Option("--pin", "Enables the host window to be top most", CommandOptionType.NoValue);
            var channel = app.Option("--channel <CHANNEL>", "", CommandOptionType.SingleValue);

            app.Execute(args);

            if (app.IsShowingInformation)
            {
                return;
            }
            
            if (!channel.HasValue())
            {
                new Host(shutdown, serviceProvider).Run(
                    width.HasValue() ? int.Parse(width.Value()) : (int?)null,
                    width.HasValue() ? int.Parse(height.Value()) : (int?)null,
                    topMost.HasValue(),
                    app.RemainingArguments.ToArray());
            }
            else
            {
                new Guest(channel.Value(), shutdown, serviceProvider).Run(app.RemainingArguments.ToArray());
            }
        }
Ejemplo n.º 4
0
        private static void RegisterUninstallSubcommand(CommandLineApplication commandsCmd, ReportsFactory reportsFactory)
        {
            commandsCmd.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(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var command = new UninstallCommand(
                        AppCommandsFolderRepository.CreateDefault(),
                        reports: reportsFactory.CreateReports(quiet: false));

                    command.NoPurge = optNoPurge.HasValue();

                    var success = command.Execute(argCommand.Value);
                    return success ? 0 : 1;
                });
            });
        }
Ejemplo n.º 5
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment applicationEnvironment, IServiceProvider serviceProvider)
        {
            cmdApp.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 optionIncludeSymbols = c.Option("--include-symbols", "Include symbols in output bundle",
                    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(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var options = new PublishOptions
                    {
                        OutputDir = optionOut.Value(),
                        ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        Configuration = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = applicationEnvironment.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(),
                        IncludeSymbols = optionIncludeSymbols.HasValue(),
                        Reports = reportsFactory.CreateReports(optionQuiet.HasValue())
                    };

                    var manager = new PublishManager(serviceProvider, options);
                    if (!manager.Publish())
                    {
                        return -1;
                    }

                    return 0;
                });
            });
        }
Ejemplo n.º 6
0
        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;
            }
        }
Ejemplo n.º 7
0
        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);
        }
Ejemplo n.º 8
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment appEnvironment)
        {
            cmdApp.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 details = c.Option("--details",
                    "Show the details of how each dependency is introduced",
                    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(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var options = new DependencyListOptions(reportsFactory.CreateReports(verbose: true, quiet: false), argProject)
                    {
                        TargetFrameworks = frameworks.Values,
                        ShowAssemblies = showAssemblies.HasValue(),
                        RuntimeFolder = runtimeFolder.Value(),
                        Details = details.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, appEnvironment.RuntimeFramework);
                    return command.Execute();
                });
            });
        }
Ejemplo n.º 9
0
        public void Main(string[] args)
        {
            var cmdlineApp = new CommandLineApplication();
            cmdlineApp.HelpOption("--help");
            cmdlineApp.Command("build", c =>
            {
                c.Option("--foo", "Foo bar", CommandOptionType.NoValue);
            });

            cmdlineApp.Execute(args);
        }
Ejemplo n.º 10
0
        internal void BuildCommandLine(CommandLineApplication command)
        {
            foreach (var param in ActionDescriptor.Parameters)
            {
                param.AddCommandLineParameterTo(command);
            }

            command.Invoke = () =>
            {
                object modelInstance;
                try
                {
                    modelInstance = Activator.CreateInstance(ActionDescriptor.ActionModel);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("There was an error attempting to create an instace of model for GenerateCode method: " + ex.Message);
                }

                foreach (var param in ActionDescriptor.Parameters)
                {
                    param.Property.SetValue(modelInstance, param.Value);
                }

                var codeGeneratorInstance = ActionDescriptor.Generator.CodeGeneratorInstance;

                try
                {
                    var result = ActionDescriptor.ActionMethod.Invoke(codeGeneratorInstance, new[] { modelInstance });

                    if (result is Task)
                    {
                        ((Task)result).Wait();
                    }
                }
                catch (Exception ex)
                {
                    while (ex is TargetInvocationException)
                    {
                        ex = ex.InnerException;
                    }

                    if (ex is AggregateException)
                    {
                        ex = ex.GetBaseException();
                    }

                    throw new InvalidOperationException(ex.Message);
                }

                return 0;
            };
        }
Ejemplo n.º 11
0
        public void Execute(string[] args)
        {
            var app = new CommandLineApplication();

            app.Command(ActionDescriptor.Generator.Name, c =>
            {
                c.HelpOption("--help|-h|-?");
                BuildCommandLine(c);
            });

            app.Execute(args);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        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;
        }
Ejemplo n.º 14
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory)
        {
            cmdApp.Command("feeds", c =>
            {
                c.Description = "Commands related to managing package feeds currently in use";
                c.HelpOption("-?|-h|--help");
                c.OnExecute(() =>
                {
                    c.ShowHelp();
                    return 2;
                });

                RegisterListCommand(c, reportsFactory);
            });
        }
Ejemplo n.º 15
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory)
        {
            cmdApp.Command("sources", cmd =>
            {
                cmd.Description = "Commands related managing packages source code from external repositories.";
                cmd.HelpOption("-?|-h|--help");
                cmd.OnExecute(() =>
                {
                    cmd.ShowHelp();
                    return 2;
                });

                RegisterGetSubcommand(cmd, reportsFactory);
            });
        }
Ejemplo n.º 16
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment appEnvironment)
        {
            cmdApp.Command("commands", cmd =>
            {
                cmd.Description = "Commands related to managing application commands (install, uninstall)";
                cmd.HelpOption("-?|-h|--help");
                cmd.OnExecute(() =>
                {
                    cmd.ShowHelp();
                    return 2;
                });

                RegisterInstallSubcommand(cmd, reportsFactory, appEnvironment);
                RegisterUninstallSubcommand(cmd, reportsFactory);
            });
        }
Ejemplo n.º 17
0
        public void AllowNoThrowBehaviorOnUnexpectedShortOption()
        {
            var unexpectedOption = "-uexp";
            var app = new CommandLineApplication();

            var testCmd = app.Command("test", c =>
            {
                c.OnExecute(() => 0);
            },
            throwOnUnexpectedArg: false);

            // (does not throw)
            app.Execute("test", unexpectedOption);
            Assert.Equal(1, testCmd.RemainingArguments.Count);
            Assert.Equal(unexpectedOption, testCmd.RemainingArguments[0]);
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        private static void RegisterInstallSubcommand(CommandLineApplication commandsCmd, ReportsFactory reportsFactory, IApplicationEnvironment appEnvironment)
        {
            commandsCmd.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 package and conflicting commands", CommandOptionType.NoValue);

                var feedCommandLineOptions = FeedCommandLineOptions.Add(c);

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

                c.OnExecute(async () =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var feedOptions = feedCommandLineOptions.GetOptions();
                    var command = new InstallGlobalCommand(
                            appEnvironment,
                            string.IsNullOrEmpty(feedOptions.TargetPackagesFolder) ?
                                AppCommandsFolderRepository.CreateDefault() :
                                AppCommandsFolderRepository.Create(feedOptions.TargetPackagesFolder));

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

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

                    if (argPackage.Value == null)
                    {
                        c.ShowHelp();
                        return 2;
                    }

                    var success = await command.Execute(argPackage.Value, argVersion.Value);
                    return success ? 0 : 1;
                });
            });
        }
Ejemplo n.º 20
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory)
        {
            cmdApp.Command("packages", packagesCommand =>
            {
                packagesCommand.Description = "Commands related to managing local and remote packages folders";
                packagesCommand.HelpOption("-?|-h|--help");
                packagesCommand.OnExecute(() =>
                {
                    packagesCommand.ShowHelp();
                    return 2;
                });

                RegisterAddSubcommand(packagesCommand, reportsFactory);
                RegisterPushSubcommand(packagesCommand, reportsFactory);
                RegisterPullSubcommand(packagesCommand, reportsFactory);
            });
        }
Ejemplo n.º 21
0
        private static void RegisterPullSubcommand(CommandLineApplication packagesCmd, ReportsFactory reportsFactory)
        {
            packagesCmd.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(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var reports = reportsFactory.CreateReports(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;
                });
            });
        }
Ejemplo n.º 22
0
        public static void RegisterListCommand(CommandLineApplication cmdApp, ReportsFactory reportsFactory)
        {
            cmdApp.Command("list", c =>
            {
                c.Description = "Displays a list of package sources in effect for a project";
                var argRoot = c.Argument("[root]",
                    "The path of the project to calculate effective package sources for (defaults to the current directory)");

                c.OnExecute(() =>
                {
                    var command = new ListFeedsCommand(
                        reportsFactory.CreateReports(quiet: false),
                        string.IsNullOrEmpty(argRoot.Value) ? "." : argRoot.Value);

                    return command.Execute();
                });
            });
        }
Ejemplo n.º 23
0
        public void AllowNoThrowBehaviorOnUnexpectedOptionAfterSubcommand()
        {
            var unexpectedOption = "--unexpected";
            CommandLineApplication subCmd = null;
            var app = new CommandLineApplication();

            var testCmd = app.Command("k", c =>
            {
                subCmd = c.Command("run", _ => { }, addHelpCommand: false, throwOnUnexpectedArg: false);
                c.OnExecute(() => 0);
            });

            // (does not throw)
            app.Execute("k", "run", unexpectedOption);
            Assert.Equal(0, testCmd.RemainingArguments.Count);
            Assert.Equal(1, subCmd.RemainingArguments.Count);
            Assert.Equal(unexpectedOption, subCmd.RemainingArguments[0]);
        }
Ejemplo n.º 24
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IServiceProvider serviceProvider)
        {
            cmdApp.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(
                    "[projects]",
                    "One or more projects build. If not specified, the project in the current directory will be used.",
                    multipleValues: true);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var buildOptions = new BuildOptions();
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectPatterns = argProjectDir.Values;
                    if (buildOptions.ProjectPatterns.Count == 0)
                    {
                        buildOptions.ProjectPatterns.Add(Path.Combine(Directory.GetCurrentDirectory(), "project.json"));
                    }
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.GeneratePackages = false;
                    buildOptions.Reports = reportsFactory.CreateReports(optionQuiet.HasValue());

                    var projectManager = new BuildManager(serviceProvider, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });
        }
Ejemplo n.º 25
0
        internal static FeedCommandLineOptions Add(CommandLineApplication app)
        {
            var options = new FeedCommandLineOptions();

            options.SourceOptions = app.Option(
                "-s|--source <FEED>",
                "A list of packages sources to use for this command",
                CommandOptionType.MultipleValue);

            options.FallbackSourceOptions = app.Option(
                "-f|--fallbacksource <FEED>",
                "A list of packages sources to use as a fallback",
                CommandOptionType.MultipleValue);

            options.ProxyOptions = app.Option(
                "-p|--proxy <ADDRESS>",
                "The HTTP proxy to use when retrieving packages",
                CommandOptionType.SingleValue);

            options.NoCacheOptions = app.Option(
                "--no-cache",
                "Do not use local cache",
                CommandOptionType.NoValue);

            options.TargetPackagesFolderOptions = app.Option(
                "--packages",
                "Path to restore packages",
                CommandOptionType.SingleValue);

            options.IgnoreFailedSourcesOptions = app.Option(
                "--ignore-failed-sources",
                "Ignore failed remote sources if there are local packages meeting version requirements",
                CommandOptionType.NoValue);

            options.QuietOptions = app.Option(
                "--quiet", "Do not show output such as HTTP request/cache information",
                CommandOptionType.NoValue);

            options.ParallelOptions = app.Option("--parallel",
                "Restores in parallel when more than one project.json is discovered.",
                CommandOptionType.NoValue);

            return options;
        }
Ejemplo n.º 26
0
        internal void AddCommandLineParameterTo(CommandLineApplication command)
        {
            var isBoolProperty = Property.PropertyType == typeof(bool);
            var optionAttribute = Property.GetOptionAttribute();

            //Note: This means all bool properties are treated as options by default.
            //ArgumentAttribute on such a property is ignored.
            if (isBoolProperty || optionAttribute != null)
            {
                //This is just so that all the below code does not need to
                //check for null on attribute. Not pure but works.
                var nullSafeOptionAttribute = optionAttribute ?? new OptionAttribute();

                var template = GetOptionTemplate(nullSafeOptionAttribute);
                var optionType = isBoolProperty ? CommandOptionType.NoValue : CommandOptionType.SingleValue;

                var option = command.Option(template, nullSafeOptionAttribute.Description ?? "", optionType);

                _valueAccessor = () =>
                {
                    if (isBoolProperty)
                    {
                        return option.HasValue() ? true : (nullSafeOptionAttribute.DefaultValue ?? false);
                    }
                    else
                    {
                        return option.HasValue() ? option.Value() : (nullSafeOptionAttribute.DefaultValue ?? "");
                    }
                };
            }
            else
            {
                //And all other string properties are considered arguments by default
                //even if the ArgumentAttribute is not mentioned on them.
                var argumentAttribute = Property.GetArgumentAttribute();
                var description = argumentAttribute != null && !string.IsNullOrWhiteSpace(argumentAttribute.Description)
                    ? argumentAttribute.Description
                    : "";

                var argument = command.Argument(Property.Name, description);
                _valueAccessor = () => argument.Value;
            }
        }
Ejemplo n.º 27
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment applicationEnvironment)
        {
            cmdApp.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot = c.Argument("[root]",
                    "List of projects and project folders to restore. Each value can be: a path to a project.json or global.json file, or a folder to recursively search for project.json files.",
                    multipleValues: true);
                var feedCommandLineOptions = FeedCommandLineOptions.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);

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

                c.OnExecute(async () =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var feedOptions = feedCommandLineOptions.GetOptions();
                    var command = new RestoreCommand(applicationEnvironment);
                    command.Reports = reportsFactory.CreateReports(feedOptions.Quiet);
                    command.RestoreDirectories.AddRange(argRoot.Values);
                    command.FeedOptions = feedOptions;
                    command.Lock = optLock.HasValue();
                    command.Unlock = optUnlock.HasValue();

                    if (!string.IsNullOrEmpty(feedOptions.Proxy))
                    {
                        Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy);
                    }

                    var success = await command.Execute();

                    return success ? 0 : 1;
                });
            });
        }
Ejemplo n.º 28
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory)
        {
            cmdApp.Command("wrap", c =>
            {
                c.Description = "Wrap a csproj/assembly into a project.json, which can be referenced by project.json files";

                var argPath = c.Argument("[path]", "Path to csproj/assembly 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(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    var reports = reportsFactory.CreateReports(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.Execute();

                    return success ? 0 : 1;
                });
            });
        }
Ejemplo n.º 29
0
        private static void RegisterGetSubcommand(CommandLineApplication sourcesCmd, ReportsFactory reportsFactory)
        {
            sourcesCmd.Command("get", c =>
            {
                c.Description = "Retrieves the source code for packages used by projects";

                var packagesArgument = c.Argument(
                    "[package]",
                    "The name of the package for which to retrieve the sources. Can only specify packages used by the project.",
                    multipleValues: true);

                var projectFileOption = c.Option(
                    "-p|--project",
                    "Optional. The path to a project.json file. If not specified, the project in the current folder is used.",
                    CommandOptionType.SingleValue);
                var packagesFolderOption = c.Option(
                    "--packages",
                    "Optional. The local packages folder",
                    CommandOptionType.SingleValue);
                var sourceFolderOption = c.Option(
                    "-o|--output",
                    "Optional. The path to the folder that will hold the source files.",
                    CommandOptionType.SingleValue);

                c.OnExecute(() =>
                {
                    var command = new SourceCommand(packagesArgument.Value, reportsFactory.CreateReports(quiet: false));
                    command.ProjectFile = projectFileOption.Value();
                    command.PackagesFolder = packagesFolderOption.Value();
                    command.SourcesFolder = sourceFolderOption.Value();

                    if (!command.Execute())
                    {
                        return -1;
                    }

                    return 0;
                });
            });
        }
Ejemplo n.º 30
0
        public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IServiceProvider serviceProvider)
        {
            cmdApp.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(() =>
                {
                    c.ShowRootCommandFullNameAndVersion();

                    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 = reportsFactory.CreateReports(optionQuiet.HasValue());

                    var projectManager = new BuildManager(serviceProvider, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });
        }