• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# CommandLineApplication类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中CommandLineApplication的典型用法代码示例。如果您正苦于以下问题:C# CommandLineApplication类的具体用法?C# CommandLineApplication怎么用?C# CommandLineApplication使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



CommandLineApplication类属于命名空间,在下文中一共展示了CommandLineApplication类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Main

        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();
            app.Name = "dotnet compile csc";
            app.FullName = "CSharp compiler";
            app.Description = "CSharp Compiler for the .NET Platform";
            app.HelpOption("-h|--help");

            var responseFileArg = app.Argument("<CONFIG>", "The response file to pass to the compiler.");

            app.OnExecute(() =>
            {
                // Execute CSC!
                var result = RunCsc($"-noconfig @\"{responseFileArg.Value}\"")
                    .ForwardStdErr()
                    .ForwardStdOut()
                    .Execute();

                return result.ExitCode;
            });

            return app.Execute(args);
        }
开发者ID:krwq,项目名称:cli-1,代码行数:25,代码来源:Program.cs


示例2: Register

        public static void Register(CommandLineApplication cmdApp, IApplicationEnvironment appEnvironment)
        {
            cmdApp.Command("scan", c => {
            c.Description = "Scan a directory tree and produce a JSON array of source units";

            var repoName = c.Option ("--repo <REPOSITORY_URL>",   "The URI of the repository that contains the directory tree being scanned", CommandOptionType.SingleValue);
            var subdir   = c.Option ("--subdir <SUBDIR_PATH>", "The path of the current directory (in which the scanner is run), relative to the root directory of the repository being scanned", CommandOptionType.SingleValue);

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

            c.OnExecute(() => {
              var repository = repoName.Value();
              var dir = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), subdir.Value()));

              //Console.WriteLine($"Repository: {repository}");
              //Console.WriteLine($"Directory: {dir}");

              var sourceUnits = new List<SourceUnit>();
              foreach(var proj in Scan(dir))
              {
            //Console.WriteLine($"Found project: {proj.Name} ({proj.Version}, {proj.CompilerServices})");
            sourceUnits.Add(SourceUnit.FromProject(proj, dir));
              }

              //Console.Error.Write($"Current dir: {Environment.CurrentDirectory}\n");
              Console.WriteLine(JsonConvert.SerializeObject(sourceUnits, Formatting.Indented));

              return 0;
            });
              });
        }
开发者ID:YoloDev,项目名称:srclib-csharp,代码行数:31,代码来源:ScanConsoleCommand.cs


示例3: Main

        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();
            app.Name = "dotnet init";
            app.FullName = ".NET Initializer";
            app.Description = "Initializes empty project for .NET Platform";
            app.HelpOption("-h|--help");

            var dotnetInit = new Program();
            app.OnExecute((Func<int>)dotnetInit.CreateEmptyProject);

            try
            {
                return app.Execute(args);
            }
            catch (Exception ex)
            {
            #if DEBUG
                Reporter.Error.WriteLine(ex.ToString());
            #else
                Reporter.Error.WriteLine(ex.Message);
            #endif
                return 1;
            }
        }
开发者ID:niemyjski,项目名称:cli,代码行数:27,代码来源:Program.cs


示例4: Register

    public static void Register(CommandLineApplication cmdApp, IApplicationEnvironment appEnv, IRuntimeEnvironment runtimeEnv)
    {
      if (runtimeEnv.OperatingSystem == "Windows")
      {
        _dnuPath = new Lazy<string>(FindDnuWindows);
      }
      else
      {
        _dnuPath = new Lazy<string>(FindDnuNix);
      }

      cmdApp.Command("depresolve", c => {
        c.Description = "Perform a combination of parsing, static analysis, semantic analysis, and type inference";

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

        c.OnExecute(async () => {
          //System.Diagnostics.Debugger.Launch();
          var jsonIn = await Console.In.ReadToEndAsync();
          var sourceUnit = JsonConvert.DeserializeObject<SourceUnit>(jsonIn);

          var dir = Path.Combine(Directory.GetCurrentDirectory(), sourceUnit.Dir);
          var deps = await DepResolve(dir);

          var result = new List<Resolution>();
          foreach(var dep in deps)
          {
            result.Add(Resolution.FromLibrary(dep));
          }

          Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
          return 0;
        });
      });
    }
开发者ID:YoloDev,项目名称:srclib-csharp,代码行数:35,代码来源:DepresolveConsoleCommand.cs


示例5: Arguments_HaveCorrectDescription_Returns_CorrectValue

        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);
        }
开发者ID:robbert229,项目名称:Scaffolding,代码行数:29,代码来源:ParameterDescriptorTests.cs


示例6: Main

        public static int Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name = "guardrex-json-to-csproj-converter",
                FullName = "GuardRex JSON to CSPROJ Converter",
                Description = "Converts project.json into a .csproj file for the project",
            };
            app.HelpOption("-h|--help");

            var frameworkOption = app.Option("-f|--framework <FRAMEWORK>", "Target framework of application being published", CommandOptionType.SingleValue);
            var configurationOption = app.Option("-c|--configuration <CONFIGURATION>", "Target configuration of application being published", CommandOptionType.SingleValue);
            var projectPath = app.Argument("<PROJECT>", "The path to the project (project folder or project.json) being published. If empty the current directory is used.");

            app.OnExecute(() =>
            {
                var exitCode = new ConvertCommand(frameworkOption.Value(), configurationOption.Value(), projectPath.Value).Run();

                return exitCode;
            });

            try
            {
                return app.Execute(args);
            }
            catch (Exception e)
            {
                Reporter.Error.WriteLine(e.Message.Red());
                Reporter.Output.WriteLine(e.ToString().Yellow());
            }

            return 1;
        }
开发者ID:GuardRex,项目名称:GuardRex.JsonToCsprojConverter,代码行数:33,代码来源:Program.cs


示例7: AddOption

        private static CommandOption AddOption(CommandLineApplication app, string optionName, string description, CommandOptionType optionType)
        {
            string argSuffix = optionType == CommandOptionType.MultipleValue ? "..." : null;
            string argString = optionType == CommandOptionType.BoolValue ? null : $" <arg>{argSuffix}";

            return app.Option($"--{optionName}{argString}", description, optionType);
        }
开发者ID:akrisiun,项目名称:dotnet-cli,代码行数:7,代码来源:CommonCompilerOptionsCommandLine.cs


示例8: Run

        private static void Run(CommandLineApplication cmd)
        {
            cmd.Description = "Set imports for project.json files";

            var argRoot = cmd.Argument(
                "[root]",
                "directory",
                multipleValues: true);

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

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

                foreach (var arg in argRoot.Values)
                {
                    var dir = new DirectoryInfo(arg);

                    foreach (var file in dir.GetFiles("project.json", SearchOption.AllDirectories))
                    {
                        Process(file);
                    }
                }

                return 0;
            });
        }
开发者ID:emgarten,项目名称:Trestle,代码行数:28,代码来源:ImportsCommand.cs


示例9: Run

        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication(false)
            {
                Name = "dotnet restore",
                FullName = ".NET project dependency restorer",
                Description = "Restores dependencies listed in project.json"
            };


            app.OnExecute(() =>
            {
                try
                {
                    return NuGet3.Restore(args);
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);

                    return -1;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);

                    return -2;
                }
            });

            return app.Execute(args);
        }
开发者ID:akrisiun,项目名称:dotnet-cli,代码行数:34,代码来源:Program.cs


示例10: Run

        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();
            app.Name = "dotnet publish";
            app.FullName = ".NET Publisher";
            app.Description = "Publisher for the .NET Platform";
            app.HelpOption("-h|--help");

            var framework = app.Option("-f|--framework <FRAMEWORK>", "Target framework to compile for", CommandOptionType.SingleValue);
            var runtime = app.Option("-r|--runtime <RUNTIME_IDENTIFIER>", "Target runtime to publish for", CommandOptionType.SingleValue);
            var buildBasePath = app.Option("-b|--build-base-path <OUTPUT_DIR>", "Directory in which to place temporary outputs", CommandOptionType.SingleValue);
            var output = app.Option("-o|--output <OUTPUT_PATH>", "Path in which to publish the app", CommandOptionType.SingleValue);
            var versionSuffix = app.Option("--version-suffix <VERSION_SUFFIX>", "Defines what `*` should be replaced with in version field in project.json", CommandOptionType.SingleValue);
            var configuration = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue);
            var projectPath = app.Argument("<PROJECT>", "The project to publish, defaults to the current directory. Can be a path to a project.json or a project directory");
            var nativeSubdirectories = app.Option("--native-subdirectory", "Temporary mechanism to include subdirectories from native assets of dependency packages in output", CommandOptionType.NoValue);
            var noBuild = app.Option("--no-build", "Do not build projects before publishing", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                var publish = new PublishCommand();

                publish.Framework = framework.Value();
                publish.Runtime = runtime.Value();
                publish.BuildBasePath = buildBasePath.Value();
                publish.OutputPath = output.Value();
                publish.Configuration = configuration.Value() ?? Constants.DefaultConfiguration;
                publish.NativeSubdirectories = nativeSubdirectories.HasValue();
                publish.ProjectPath = projectPath.Value;
                publish.VersionSuffix = versionSuffix.Value();
                publish.ShouldBuild = !noBuild.HasValue();

                if (string.IsNullOrEmpty(publish.ProjectPath))
                {
                    publish.ProjectPath = Directory.GetCurrentDirectory();
                }

                if (!publish.TryPrepareForPublish())
                {
                    return 1;
                }

                publish.PublishAllProjects();
                Reporter.Output.WriteLine($"Published {publish.NumberOfPublishedProjects}/{publish.NumberOfProjects} projects successfully");
                return (publish.NumberOfPublishedProjects == publish.NumberOfProjects) ? 0 : 1;
            });

            try
            {
                return app.Execute(args);
            }
            catch (Exception ex)
            {
                Reporter.Error.WriteLine(ex.Message.Red());
                Reporter.Verbose.WriteLine(ex.ToString().Yellow());
                return 1;
            }
        }
开发者ID:krytarowski,项目名称:cli,代码行数:60,代码来源:Program.cs


示例11: Register

    public static void Register(CommandLineApplication cmdApp, Microsoft.Extensions.PlatformAbstractions.IApplicationEnvironment appEnvironment, Microsoft.Extensions.PlatformAbstractions.IAssemblyLoadContextAccessor loadContextAccessor, Microsoft.Extensions.PlatformAbstractions.IRuntimeEnvironment runtimeEnvironment)
    {
      cmdApp.Command("graph", (Action<CommandLineApplication>)(c => {
        c.Description = "Perform parsing, static analysis, semantic analysis, and type inference";

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

        c.OnExecute((Func<System.Threading.Tasks.Task<int>>)(async () => {
          var jsonIn = await Console.In.ReadToEndAsync();
          var sourceUnit = JsonConvert.DeserializeObject<SourceUnit>(jsonIn);

          var root = Directory.GetCurrentDirectory();
          var dir = Path.Combine(root, sourceUnit.Dir);
          var context = new GraphContext
          {
            RootPath = root,
            SourceUnit = sourceUnit,
            ProjectDirectory = dir,
            HostEnvironment = appEnvironment,
            LoadContextAccessor = loadContextAccessor,
            RuntimeEnvironment = runtimeEnvironment
          };

          var result = await GraphRunner.Graph(context);

          Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
          return 0;
        }));
      }));
    }
开发者ID:ildarisaev,项目名称:srclib-csharp,代码行数:30,代码来源:GraphConsoleCommand.cs


示例12: Main

        public int Main(string[] args)
        {
            try
            {
                var app = new CommandLineApplication
                {
                    Name = "razor-tooling",
                    FullName = "Microsoft Razor Tooling Utility",
                    Description = "Resolves Razor tooling specific information.",
                    ShortVersionGetter = GetInformationalVersion,
                };
                app.HelpOption("-?|-h|--help");

                ResolveProtocolCommand.Register(app);
                ResolveTagHelpersCommand.Register(app, _assemblyLoadContext);

                app.OnExecute(() =>
                {
                    app.ShowHelp();
                    return 2;
                });

                return app.Execute(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {Environment.NewLine}{ex.Message}.");
                return 1;
            }
        }
开发者ID:IlyaKhD,项目名称:RazorTooling,代码行数:30,代码来源:Program.cs


示例13: ExecuteApp

        private static int ExecuteApp(CommandLineApplication app, string[] args)
        {
            // Support Response File
            foreach(var arg in args)
            {
                if(arg.Contains(".rsp"))
                {
                    args = ParseResponseFile(arg);

                    if (args == null)
                    {
                        return 1;
                    }
                }
            }

            try
            {
                return app.Execute(args);
            }
            catch (Exception ex)
            {
            #if DEBUG
                System.Console.WriteLine(ex);
            #else
                Reporter.Error.WriteLine(ex.Message);
            #endif
                return 1;
            }
        }
开发者ID:niemyjski,项目名称:cli,代码行数:30,代码来源:Program.cs


示例14: Main

        public static int Main(string[] args)
        {
            var app = new CommandLineApplication();
            app.Name = "dotnet";
            app.Description = "The .NET CLI";

            // Most commonly used commands
            app.Command("init", c =>
            {
                c.Description = "Scaffold a basic .NET application";

                c.OnExecute(() => Exec("dotnet-init", c.RemainingArguments));
            });

            app.Command("compile", c =>
            {
                c.Description = "Produce assemblies for the project in given directory";

                c.OnExecute(() => Exec("dotnet-compile", c.RemainingArguments));
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                c.OnExecute(() => Exec("dotnet-restore", c.RemainingArguments));
            });

            app.Command("pack", c =>
            {
                c.Description = "Produce a NuGet package";

                c.OnExecute(() => Exec("dotnet-pack", c.RemainingArguments));
            });

            app.Command("publish", c =>
            {
                c.Description = "Produce deployable assets";

                c.OnExecute(() => Exec("dotnet-publish", c.RemainingArguments));
            });

            // TODO: Handle unknown commands

            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 2;
            });

            try
            {
                return app.Execute(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return 1;
        }
开发者ID:Sridhar-MS,项目名称:cli-old,代码行数:60,代码来源:Program.cs


示例15: RegisterAddSubcommand

        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;
                });
            });
        }
开发者ID:leloulight,项目名称:dnx,代码行数:25,代码来源:PackagesConsoleCommand.cs


示例16: RegisterUninstallSubcommand

        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;
                });
            });
        }
开发者ID:leloulight,项目名称:dnx,代码行数:27,代码来源:CommandsConsoleCommand.cs


示例17: Register

        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;
                });
            });
        }
开发者ID:henghu-bai,项目名称:dnx,代码行数:59,代码来源:PublishConsoleCommand.cs


示例18: Main

        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;
            }
        }
开发者ID:benaadams,项目名称:Caching,代码行数:59,代码来源:Program.cs


示例19: Register

        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 mismatched = c.Option("--mismatched",
                    "Show the mismatch dependencies.",
                    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)
                    {
                        ShowAssemblies = showAssemblies.HasValue(),
                        RuntimeFolder = runtimeFolder.Value(),
                        Details = details.HasValue(),
                        ResultsFilter = resultsFilter.Value(),
                        Mismatched = mismatched.HasValue()
                    };
                    options.AddFrameworkMonikers(frameworks.Values);

                    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();
                });
            });
        }
开发者ID:leloulight,项目名称:dnx,代码行数:59,代码来源:ListConsoleCommand.cs


示例20: Main

        static void Main(string[] args)
        {
            CommandLineApplication commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: false);
            CommandArgument directory = commandLineApplication.Argument("directory", "The directory to search for assemblies");
            CommandOption dgmlExport = commandLineApplication.Option("-dg|--dgml <filename>", "Export to a dgml file", CommandOptionType.SingleValue);
            CommandOption nonsystem = commandLineApplication.Option("-n|--nonsystem", "List system assemblies", CommandOptionType.NoValue);
            CommandOption all = commandLineApplication.Option("-a|--all", "List all assemblies and references.", CommandOptionType.NoValue);
            CommandOption noconsole = commandLineApplication.Option("-nc|--noconsole", "Do not show references on console.", CommandOptionType.NoValue);
            CommandOption silent = commandLineApplication.Option("-s|--silent", "Do not show any message, only warnings and errors will be shown.", CommandOptionType.NoValue);

            commandLineApplication.HelpOption("-? | -h | --help");
            commandLineApplication.OnExecute(() =>
            {
                var consoleLogger = new ConsoleLogger(!silent.HasValue());

                var directoryPath = directory.Value;
                if (!Directory.Exists(directoryPath))
                {
                    consoleLogger.LogMessage(string.Format("Directory: '{0}' does not exist.", directoryPath));
                    return -1;
                }

                var onlyConflicts = !all.HasValue();
                var skipSystem = nonsystem.HasValue();

                IDependencyAnalyzer analyzer = new DependencyAnalyzer() { DirectoryInfo = new DirectoryInfo(directoryPath) };

                consoleLogger.LogMessage(string.Format("Check assemblies in: {0}", analyzer.DirectoryInfo));

                var result = analyzer.Analyze(consoleLogger);

                if (!noconsole.HasValue())
                {
                    IDependencyVisualizer visualizer = new ConsoleVisualizer(result) { SkipSystem = skipSystem, OnlyConflicts = onlyConflicts };
                    visualizer.Visualize();
                }

                if (dgmlExport.HasValue())
                {
                    IDependencyVisualizer export = new DgmlExport(result, string.IsNullOrWhiteSpace(dgmlExport.Value()) ? Path.Combine(analyzer.DirectoryInfo.FullName, "references.dgml") : dgmlExport.Value(), consoleLogger);
                    export.Visualize();
                }

                return 0;
            });
            try
            {
                if (args == null || args.Length == 0)
                    commandLineApplication.ShowHelp();
                else
                    commandLineApplication.Execute(args);
            }
            catch (CommandParsingException cpe)
            {
                Console.WriteLine(cpe.Message);
                commandLineApplication.ShowHelp();
            }
        }
开发者ID:mikehadlow,项目名称:AsmSpy,代码行数:58,代码来源:Program.cs



注:本文中的CommandLineApplication类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# CommandLineArgumentParser类代码示例发布时间:2022-05-24
下一篇:
C# CommandLine.Parser类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap