Example #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 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;
            });
              });
        }
Example #3
0
        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);
        }
        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;
        }
    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;
        });
      });
    }
Example #6
0
        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;
            }
        }
Example #7
0
        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;
            }
        }
Example #8
0
        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;
            }
        }
    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;
        }));
      }));
    }
Example #10
0
        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;
            }
        }
Example #11
0
        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);
        }
Example #12
0
        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;
        }
        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);
        }
        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);
        }
Example #15
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;
                });
            });
        }
Example #16
0
        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;
            });
        }
Example #17
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 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();
                });
            });
        }
Example #18
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;
            }
        }
Example #19
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;
                });
            });
        }
Example #20
0
        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();
            }
        }
Example #21
0
        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"
            };

            // Parse --quiet, because we have to handle that specially since NuGet3 has a different
            // "--verbosity" switch that goes BEFORE the command
            var quiet = args.Any(s => s.Equals("--quiet", StringComparison.OrdinalIgnoreCase));
            args = args.Where(s => !s.Equals("--quiet", StringComparison.OrdinalIgnoreCase)).ToArray();

            // Until NuGet/Home#1941 is fixed, if no RIDs are specified, add our own.
            if (!args.Any(s => s.Equals("--runtime", StringComparison.OrdinalIgnoreCase)))
            {
                args = Enumerable.Concat(
                    args,
                    PlatformServices.Default.Runtime.GetOverrideRestoreRuntimeIdentifiers().SelectMany(r => new [] { "--runtime", r })
                    ).ToArray();
            }

            app.OnExecute(() =>
            {
                try
                {
                    var projectRestoreResult = NuGet3.Restore(args, quiet);

                    var restoreTasks = GetRestoreTasks(args);

                    foreach (var restoreTask in restoreTasks)
                    {
                        var project = ProjectReader.GetProject(restoreTask.ProjectPath);

                        RestoreTools(project, restoreTask, quiet);
                    }

                    return projectRestoreResult;
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);

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

                    return -2;
                }
            });

            return app.Execute(args);
        }
Example #22
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name = "dnx Azure",
                FullName = "Azure Message Queue Utils"
            };

            app.HelpOption(HELP_TEMPLATE);

            app.OnExecute(() => ShowHelp(app));

            app.Command("send", send =>
            {
                send.Description = "Send a message";
                send.HelpOption(HELP_TEMPLATE);

                var queueName = send.Argument("[queueName]", "The name of the queue");
                var message = send.Argument("[message]", "The message to send");
                var connectionString = send.Argument("[connectionString]", "The connection string");

                send.OnExecute(() =>
                {
                    var factory = MessagingFactory.CreateFromConnectionString(connectionString.Value);
                    var queue = factory.CreateQueueClient(queueName.Value);
                    var packet = new BrokeredMessage(message.Value);

                    queue.Send(packet);

                    return 0;
                });
            });

            app.Command("receive", receive =>
            {
                receive.Description = "Receive a message";
                receive.HelpOption(HELP_TEMPLATE);

                var queueName = receive.Argument("[queueName]", "The name of the queue");
                var connectionString = receive.Argument("[connectionString]", "The connection string");

                receive.OnExecute(() =>
                {
                    var factory = MessagingFactory.CreateFromConnectionString(connectionString.Value);
                    var queue = factory.CreateQueueClient(queueName.Value);
                    var message = queue.Receive();

                    Console.WriteLine(message.GetBody<string>());

                    message.Complete(); // must signal to queue that the message has been handled

                    return 0;
                });
            });

            return app.Execute(args);
        }
Example #23
0
 static void Main(string[] args)
 {
     var app = new CommandLineApplication();
     app.UseServices(services =>
         services
             .AddServices()
             .ConfigureArguments(args));
     app.ListReferences();
     app.Execute();
 }
        public static void Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name = "Project.Json.Patcher",
                Description = "Patch project.json files with new version and release notes",
                FullName = "Project.Json Patcher"
            };

            app.HelpOption("-h|--help");

            app.Command("Patch", commandAppConfing =>
            {
                commandAppConfing.Description = "Patches the project.json file";

                CommandOption fileOption = commandAppConfing.Option("-f|--File <FilePath>",
                    "OPTIONAL. Path to project.json", CommandOptionType.SingleValue);

                CommandOption versionOption = commandAppConfing.Option("-v|--Version <Version>",
                    "Target version of project.json", CommandOptionType.SingleValue);

                CommandOption releaseNotesOption = commandAppConfing.Option("-r|--RealeaseNotes <ReleaseNotes>",
                    "OPTIONAL. Release notes of this version", CommandOptionType.SingleValue);

                commandAppConfing.HelpOption("-h|--help");

                commandAppConfing.OnExecute(() =>
                {

                    string filePath = GetFilePath(fileOption);

                    string version = GetVersion(versionOption);

                    string releaseNotes = releaseNotesOption.Value();

                    Console.WriteLine($"FilePath: {filePath}, " +
                                      $"Version: {version}, " +
                                      $"ReleaseNotes: {releaseNotes}");

                    Patch(filePath, version, releaseNotes);

                    Console.WriteLine("Patching Complete");
                    return 0;
                });

            });

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

            app.Execute(args);
        }
Example #25
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

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

            var output = app.Option("-o|--output <OUTPUT_DIR>", "Directory in which to place outputs", CommandOptionType.SingleValue);
            var intermediateOutput = app.Option("-t|--temp-output <OUTPUT_DIR>", "Directory in which to place temporary outputs", CommandOptionType.SingleValue);
            var configuration = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue);
            var project = app.Argument("<PROJECT>", "The project to compile, defaults to the current directory. Can be a path to a project.json or a project directory");

            app.OnExecute(() =>
            {
                // Locate the project and get the name and full path
                var path = project.Value;
                if (string.IsNullOrEmpty(path))
                {
                    path = Directory.GetCurrentDirectory();
                }

                if(!path.EndsWith(Project.FileName))
                {
                    path = Path.Combine(path, Project.FileName);
                }

                if(!File.Exists(path))
                {
                    Reporter.Error.WriteLine($"Unable to find a project.json in {path}");
                    return 1;
                }

                var configValue = configuration.Value() ?? Cli.Utils.Constants.DefaultConfiguration;
                var outputValue = output.Value();

                return BuildPackage(path, configValue, outputValue, intermediateOutput.Value()) ? 1 : 0;
            });

            try
            {
                return app.Execute(args);
            }
            catch (Exception ex)
            {
            #if DEBUG
                Console.Error.WriteLine(ex);
            #else
                Console.Error.WriteLine(ex.Message);
            #endif
                return 1;
            }
        }
        public DotnetBaseParams(string name, string fullName, string description)
        {
            _app = new CommandLineApplication(false)
            {
                Name = name,
                FullName = fullName,
                Description = description
            };

            AddDotnetBaseParameters();
        }
Example #27
0
        public int Main(params string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 1000;
            ServicePointManager.MaxServicePoints = 1000;
            var proxies = CreateClients().ToList();
            if (!proxies.Any())
            {
                Console.WriteLine("No Bolt servers running ...".Red());
                return 1;
            }

            var app = new CommandLineApplication();
            app.Name = "bolt";
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 2;
            });

            app.Command("test", c =>
            {
                c.Description = "Tests the Bolt performance.";

                var output = c.Option("--output <PATH>", "Directory or configuration file path. If no path is specified then the 'bolt.configuration.json' configuration file will be generated in current directory.", CommandOptionType.SingleValue);

                var argRepeats = c.Option("-r <NUMBER>", "Number of repeats for each action.", CommandOptionType.SingleValue);
                var argConcurrency = c.Option("-c <NUMBER>", "Concurrency of each action.", CommandOptionType.SingleValue);

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

                int cnt = 100;
                int degree = 1;

                c.OnExecute(() =>
                {
                    if ( argRepeats.HasValue())
                    {
                        cnt = int.Parse(argRepeats.Value());
                    }

                    if (argConcurrency.HasValue())
                    {
                        degree = int.Parse(argConcurrency.Value());
                    }

                    ExecuteActions(proxies, cnt, degree);
                    Console.WriteLine("Test finished. Press any key to exit program ... ");
                    System.Console.ReadLine();
                    return 0;
                });
            });

            return app.Execute(args);
        }
        public static void Register(CommandLineApplication app, IAssemblyLoadContext assemblyLoadContext)
        {
            app.Command("resolve-taghelpers", config =>
            {
                config.Description = "Resolves TagHelperDescriptors in the specified assembly(s).";
                config.HelpOption("-?|-h|--help");
                var clientProtocol = config.Option(
                    "-p|--protocol",
                    "Provide client protocol version.",
                    CommandOptionType.SingleValue);
                var assemblyNames = config.Argument(
                    "[name]",
                    "Assembly name to resolve TagHelperDescriptors in.",
                    multipleValues: true);

                config.OnExecute(() =>
                {
                    var messageBroker = new CommandMessageBroker();
                    var plugin = new RazorPlugin(messageBroker);
                    var resolvedProtocol = ResolveProtocolCommand.ResolveProtocol(clientProtocol, plugin.Protocol);

                    plugin.Protocol = resolvedProtocol;

                    var success = true;
                    foreach (var assemblyName in assemblyNames.Values)
                    {
                        var messageData = new ResolveTagHelperDescriptorsRequestData
                        {
                            AssemblyName = assemblyName,
                            SourceLocation = SourceLocation.Zero
                        };
                        var message = new RazorPluginRequestMessage(
                            RazorPluginMessageTypes.ResolveTagHelperDescriptors,
                            JObject.FromObject(messageData));

                        success &= plugin.ProcessMessage(JObject.FromObject(message), assemblyLoadContext);
                    }

                    var resolvedDescriptors = messageBroker.Results.SelectMany(result => result.Data.Descriptors);
                    var resolvedErrors = messageBroker.Results.SelectMany(result => result.Data.Errors);
                    var resolvedResult = new ResolvedTagHelperDescriptorsResult
                    {
                        Descriptors = resolvedDescriptors,
                        Errors = resolvedErrors
                    };
                    var serializedResult = JsonConvert.SerializeObject(resolvedResult, Formatting.Indented);

                    Console.WriteLine(serializedResult);

                    return success ? 0 : 1;
                });
            });
        }
Example #29
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);
        }
Example #30
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;
            };
        }
 public static void Register(CommandLineApplication cmdApp, ILogger log)
 {
     cmdApp.Command("emptygroup", (cmd) => Run(cmd, log), throwOnUnexpectedArg: true);
 }
Example #32
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication cmd = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name                      = "restore3",
                FullName                  = "restore3",
                Description               = "restore for msbuild",
                AllowArgumentSeparator    = true,
                ArgumentSeparatorHelpText = HelpMessageStrings.MSBuildAdditionalArgsHelpText
            };

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

            var argRoot = cmd.Argument(
                "[root]",
                "Optional path to a project file or MSBuild arguments.",
                multipleValues: true);

            var sourceOption = cmd.Option(
                "-s|--source <source>",
                "Specifies a NuGet package source to use during the restore.",
                CommandOptionType.MultipleValue);

            var packagesOption = cmd.Option(
                "--packages <packagesDirectory>",
                "Directory to install packages in.",
                CommandOptionType.SingleValue);

            var disableParallelOption = cmd.Option(
                "--disable-parallel",
                "Disables restoring multiple projects in parallel.",
                CommandOptionType.NoValue);

            var configFileOption = cmd.Option(
                "--configfile <file>",
                "The NuGet configuration file to use.",
                CommandOptionType.SingleValue);

            var noCacheOption = cmd.Option(
                "--no-cache",
                "Do not cache packages and http requests.",
                CommandOptionType.NoValue);

            var ignoreFailedSourcesOption = cmd.Option(
                "--ignore-failed-sources",
                "Treat package source failures as warnings.",
                CommandOptionType.NoValue);

            var noDependenciesOption = cmd.Option(
                "--no-dependencies",
                "Set this flag to ignore project to project references and only restore the root project",
                CommandOptionType.NoValue);

            cmd.OnExecute(() =>
            {
                var msbuildArgs = new List <string>()
                {
                    "/t:Restore"
                };

                if (sourceOption.HasValue())
                {
                    msbuildArgs.Add($"/p:RestoreSources={string.Join("%3B", sourceOption.Values)}");
                }

                if (packagesOption.HasValue())
                {
                    msbuildArgs.Add($"/p:RestorePackagesPath={packagesOption.Value()}");
                }

                if (disableParallelOption.HasValue())
                {
                    msbuildArgs.Add($"/p:RestoreDisableParallel=true");
                }

                if (configFileOption.HasValue())
                {
                    msbuildArgs.Add($"/p:RestoreConfigFile={configFileOption.Value()}");
                }

                if (noCacheOption.HasValue())
                {
                    msbuildArgs.Add($"/p:RestoreNoCache=true");
                }

                if (ignoreFailedSourcesOption.HasValue())
                {
                    msbuildArgs.Add($"/p:RestoreIgnoreFailedSources=true");
                }

                if (noDependenciesOption.HasValue())
                {
                    msbuildArgs.Add($"/p:RestoreRecursive=false");
                }

                // Add in arguments
                msbuildArgs.AddRange(argRoot.Values);

                // Add remaining arguments that the parser did not understand
                msbuildArgs.AddRange(cmd.RemainingArguments);

                return(new MSBuildForwardingApp(msbuildArgs).Execute());
            });

            return(cmd.Execute(args));
        }
        static void Main(string[] args)
        {
            Message($"{typeof(Program)} : Main()", true);
            CommandLineApplication app = new CommandLineApplication();

            try
            {
                app.Description = ".NET Core console app to validate a Contentstack stack.";
                app.Name        = typeof(Program).Namespace;
                CommandOption help = app.HelpOption("-?|-h|--help");
                CommandOption dir  = app.Option("-d|--d<value>",
                                                "Path to directory containing appconfig.json",
                                                CommandOptionType.SingleValue);
                app.OnExecute(() =>
                {
                    if (help.HasValue())
                    {
                        ExitMessage(app, null, false, true, ExitCode.HelpRequested);
                    }

                    string directory = Directory.GetCurrentDirectory();

                    if (dir.HasValue())
                    {
                        directory = dir.Value();
                    }

                    if (!Directory.Exists(directory))
                    {
                        ExitMessage(app,
                                    $"{directory} does not exist or is not a subdirectory.",
                                    true,
                                    true,
                                    ExitCode.DirectoryDoesNotExist);
                    }

                    IConfiguration configuration = new ConfigurationBuilder().AddJsonFile(
                        $"{directory}\\appsettings.json",
                        optional: false,
                        reloadOnChange: true).Build();
                    Startup startup = new Startup();
                    ServiceCollection serviceCollection = new ServiceCollection();        // dependency injection configuration
                    startup.ConfigureServices(serviceCollection, configuration);          // configuration
                    IServiceProvider provider = serviceCollection.BuildServiceProvider(); // caution: may be disposable
                    ContentstackClient client = provider.GetService <ContentstackClient>();
                    //                    client.SerializerSettings.Converters.Add(new MBFlexibleblocksFlexibleblocksConverter());
                    Console.WriteLine(Environment.NewLine);
                    Message(typeof(EntryLister) + ".List()", true);
                    new EntryLister().List(client);
                    Message(typeof(EntryLister) + ".List() complete.");
                    Console.WriteLine(Environment.NewLine);
                    // Message(typeof(SimpleEntryLister) + ".List()", true);
                    // new SimpleEntryLister(client).List();
                    // Message(typeof(SimpleEntryLister) + ".List() complete.");
                    Console.WriteLine(Environment.NewLine);
                    //                    Message(typeof(BlockLister) + ".List()", true);
                    //                    new BlockLister().List(
                    //                        client.ContentType("flexibleblockspage").Entry("blt36bfa917ffedd575").Fetch<Flexibleblockspage>().Result);
                    //                    Message(typeof(BlockLister) + ".List() complete.");
                });

                app.Execute(args);
            }
            catch (Exception ex)
            {
                ExitMessage(app, $"{ex} : {ex.Message}", false, true, ExitCode.Exception);
            }
        }
Example #34
0
 protected override int OnExecute(CommandLineApplication app)
 {
     base.OnExecute(app);
     app.ShowHelp();
     return(0);
 }
Example #35
0
 public int OnExecute(CommandLineApplication app)
 {
     app.ShowHelp();
     return(0);
 }
Example #36
0
 static Task <int> Main(string[] args) => CommandLineApplication.ExecuteAsync <Program>(args);
        static void Main(string[] args)
        {
            var logger  = new Logger();
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            var configuration = builder.Build();

            var app = new CommandLineApplication
            {
                Name = Constants.UserAgent
            };

            app.OnExecute(async() =>
            {
                logger.LogInformation("Pikapika-dotnet start mining...");

                try
                {
                    var dbAccess = new PikapikaRepositoryAccess(
                        configuration.GetConnectionString("PikapikaDatabase"),
                        logger);
                    var dotnetAppsMiner = new DotnetAppsMiner(
                        configuration.GetSection("AuthorizationUsername").Value,
                        configuration.GetSection("AuthorizationToken").Value,
                        configuration.GetSection("GithubBaseUri").Value,
                        configuration.GetSection("MedidataRepositories").GetChildren().Select(x => x.Value),
                        logger);
                    var nugetRepositoryAccess = new NugetRepositoryAccess(
                        new Uri(configuration.GetSection("PublicNugetServerUri").Value),
                        new Uri(configuration.GetSection("MedidataNugetServerBaseUri").Value),
                        configuration.GetSection("MedidataNugetAccessUserName").Value,
                        configuration.GetSection("MedidataNugetAccessPassword").Value,
                        logger);
                    var dotnetNugetsMiner = new DotnetNugetsMiner(nugetRepositoryAccess, logger);

                    var timer = new Stopwatch();
                    timer.Start();

                    // mine dotnet projects
                    var dotnetAppsFromDb = await dbAccess.GetDotnetApps();
                    var dotnetRepos      = await dotnetAppsMiner.Mine(dotnetAppsFromDb);
                    //mine dotnet nugets
                    var dotnetNugetsToMine = (await dbAccess.GetDotnetNugets())
                                             .Select(x => x.Name).ToList();
                    dotnetNugetsToMine.AddRange(dotnetRepos
                                                .SelectMany(x => x.Projects
                                                            .SelectMany(y => y.DotnetAppProject.ProjectNugets
                                                                        .Select(z => z.Name))));
                    var dotnetNugets = await dotnetNugetsMiner.Mine(dotnetNugetsToMine
                                                                    .Distinct()
                                                                    .OrderBy(x => x).ToList());
                    var dotnetFrameworks = dotnetRepos
                                           .SelectMany(x => x.Projects
                                                       .SelectMany(y => y.DotnetAppProject.Frameworks))
                                           .Distinct()
                                           .OrderBy(x => x).ToList();
                    //save dotnet projects to db
                    var newdDotnetApps  = dotnetRepos.SelectMany(x => x.ConvertToDotnetApps()).ToList();
                    var savedDotnetApps = await dbAccess.SaveDotnetApps(newdDotnetApps);
                    // save dotnet nugets to db
                    var newDotnetNugets   = dotnetNugets.Values.Select(x => x.ConvertToDotnetNugets()).ToList();
                    var savedDotnetNugets = await dbAccess.SaveDotnetNugets(newDotnetNugets);
                    // save dotnet projects and nugets relationship to db
                    var dotnetAppNugetRelationship = dotnetRepos.SelectMany(x => x.ConvertToDotnetAppDotnetNugetList(savedDotnetApps, savedDotnetNugets, logger)).ToList();
                    await dbAccess.SaveDotnetAppDotnetNugetRelationships(dotnetAppNugetRelationship);

                    timer.Stop();
                    logger.LogInformation($"Operation elapsed time: {timer.Elapsed}");
                }
                catch (Exception ex)
                {
                    logger.LogError($"Exception occured:{ex.Message}");
                }

                logger.LogInformation("Pikapika-dotnet mining stopped");

                //Console.ReadLine();
                return(0);
            });

            app.Execute(args);

            //Console.ReadLine();
        }
 public void AddOptionToCommandLineApplication(CommandLineApplication commandLineApplication)
 {
     AccountFileOption = commandLineApplication.AddOptionAccoutKeyStoreFile();
     PasswordOption    = commandLineApplication.AddOptionAccoutFilePassword();
 }
Example #39
0
        public static PublishCommand FromArgs(string[] args, string msbuildPath = null)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication(throwOnUnexpectedArg: false);

            app.Name        = "dotnet publish";
            app.FullName    = LocalizableStrings.AppFullName;
            app.Description = LocalizableStrings.AppDescription;
            app.HandleRemainingArguments  = true;
            app.ArgumentSeparatorHelpText = HelpMessageStrings.MSBuildAdditionalArgsHelpText;
            app.HelpOption("-h|--help");

            CommandArgument projectArgument = app.Argument($"<{LocalizableStrings.ProjectArgument}>",
                                                           LocalizableStrings.ProjectArgDescription);

            CommandOption frameworkOption = app.Option(
                $"-f|--framework <{LocalizableStrings.FrameworkOption}>", LocalizableStrings.FrameworkOptionDescription,
                CommandOptionType.SingleValue);

            CommandOption runtimeOption = app.Option(
                $"-r|--runtime <{LocalizableStrings.RuntimeOption}>", LocalizableStrings.RuntimeOptionDescription,
                CommandOptionType.SingleValue);

            CommandOption outputOption = app.Option(
                $"-o|--output <{LocalizableStrings.OutputOption}>", LocalizableStrings.OutputOptionDescription,
                CommandOptionType.SingleValue);

            CommandOption configurationOption = app.Option(
                $"-c|--configuration <{LocalizableStrings.ConfigurationOption}>", LocalizableStrings.ConfigurationOptionDescription,
                CommandOptionType.SingleValue);

            CommandOption versionSuffixOption = app.Option(
                $"--version-suffix <{LocalizableStrings.VersionSuffixOption}>", LocalizableStrings.VersionSuffixOptionDescription,
                CommandOptionType.SingleValue);

            CommandOption filterProjOption = app.Option(
                $"--filter <{LocalizableStrings.FilterProjOption}>", LocalizableStrings.FilterProjOptionDescription,
                CommandOptionType.SingleValue);

            CommandOption verbosityOption = AddVerbosityOption(app);

            List <string> msbuildArgs = null;

            app.OnExecute(() =>
            {
                msbuildArgs = new List <string>();

                msbuildArgs.Add("/t:Publish");

                if (!string.IsNullOrEmpty(projectArgument.Value))
                {
                    msbuildArgs.Add(projectArgument.Value);
                }

                if (!string.IsNullOrEmpty(frameworkOption.Value()))
                {
                    msbuildArgs.Add($"/p:TargetFramework={frameworkOption.Value()}");
                }

                if (!string.IsNullOrEmpty(runtimeOption.Value()))
                {
                    msbuildArgs.Add($"/p:RuntimeIdentifier={runtimeOption.Value()}");
                }

                if (!string.IsNullOrEmpty(outputOption.Value()))
                {
                    msbuildArgs.Add($"/p:PublishDir={outputOption.Value()}");
                }

                if (!string.IsNullOrEmpty(configurationOption.Value()))
                {
                    msbuildArgs.Add($"/p:Configuration={configurationOption.Value()}");
                }

                if (!string.IsNullOrEmpty(versionSuffixOption.Value()))
                {
                    msbuildArgs.Add($"/p:VersionSuffix={versionSuffixOption.Value()}");
                }

                if (!string.IsNullOrEmpty(filterProjOption.Value()))
                {
                    msbuildArgs.Add($"/p:FilterProjFile={filterProjOption.Value()}");
                }

                if (!string.IsNullOrEmpty(verbosityOption.Value()))
                {
                    msbuildArgs.Add($"/verbosity:{verbosityOption.Value()}");
                }

                msbuildArgs.AddRange(app.RemainingArguments);

                return(0);
            });

            int exitCode = app.Execute(args);

            if (msbuildArgs == null)
            {
                throw new CommandCreationException(exitCode);
            }

            return(new PublishCommand(msbuildArgs, msbuildPath));
        }
Example #40
0
 public static int Main(string[] args) =>
 CommandLineApplication.Execute <Server>(args);
Example #41
0
        public virtual async Task <int> OnExecuteAsync(CommandLineApplication app, IConsole console)
        {
            await ProcessAsync();

            return(1);
        }
Example #42
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name        = "dotnet clean",
                FullName    = LocalizableStrings.AppFullName,
                Description = LocalizableStrings.AppDescription,
                HandleRemainingArguments  = true,
                ArgumentSeparatorHelpText = HelpMessageStrings.MSBuildAdditionalArgsHelpText
            };

            app.HelpOption("-h|--help");

            CommandArgument projectArgument = app.Argument(
                $"<{LocalizableStrings.CmdArgProject}>",
                LocalizableStrings.CmdArgProjDescription);

            CommandOption outputOption = app.Option(
                $"-o|--output <{LocalizableStrings.CmdOutputDir}>",
                LocalizableStrings.CmdOutputDirDescription,
                CommandOptionType.SingleValue);
            CommandOption frameworkOption = app.Option(
                $"-f|--framework <{LocalizableStrings.CmdFramework}>",
                LocalizableStrings.CmdFrameworkDescription,
                CommandOptionType.SingleValue);
            CommandOption configurationOption = app.Option(
                $"-c|--configuration <{LocalizableStrings.CmdConfiguration}>",
                LocalizableStrings.CmdConfigurationDescription,
                CommandOptionType.SingleValue);
            CommandOption verbosityOption = MSBuildForwardingApp.AddVerbosityOption(app);

            app.OnExecute(() =>
            {
                List <string> msbuildArgs = new List <string>();

                if (!string.IsNullOrEmpty(projectArgument.Value))
                {
                    msbuildArgs.Add(projectArgument.Value);
                }

                msbuildArgs.Add("/t:Clean");

                if (outputOption.HasValue())
                {
                    msbuildArgs.Add($"/p:OutputPath={outputOption.Value()}");
                }

                if (frameworkOption.HasValue())
                {
                    msbuildArgs.Add($"/p:TargetFramework={frameworkOption.Value()}");
                }

                if (configurationOption.HasValue())
                {
                    msbuildArgs.Add($"/p:Configuration={configurationOption.Value()}");
                }

                if (verbosityOption.HasValue())
                {
                    msbuildArgs.Add($"/verbosity:{verbosityOption.Value()}");
                }

                msbuildArgs.AddRange(app.RemainingArguments);

                return(new MSBuildForwardingApp(msbuildArgs).Execute());
            });

            return(app.Execute(args));
        }
Example #43
0
 public override Task <int> Execute(CommandLineApplication app)
 {
     SPT.Execute(this);
     return(this.Ok());
 }
Example #44
0
        static void Main(string[] args)
        {
            Console.WriteLine("FreeMote PSB Converter");
            Console.WriteLine("by Ulysses, [email protected]");
            FreeMount.Init();
            Console.WriteLine($"{FreeMount.PluginsCount} Plugins Loaded.");
            Console.WriteLine();

            var app = new CommandLineApplication();

            app.OptionsComparison = StringComparison.OrdinalIgnoreCase;

            //help
            app.HelpOption();
            app.ExtendedHelpText = PrintHelp();

            //options
            var optKey    = app.Option <uint>("-k|--key <KEY>", "PSB key (uint, dec)", CommandOptionType.SingleValue);
            var optNewKey = app.Option <uint>("-nk|--new-key <KEY>", "New PSB key for transfer (uint, dec)",
                                              CommandOptionType.SingleValue);
            //args
            var argPath =
                app.Argument("Files", "File paths", multipleValues: true);

            //command: pack
            app.Command("pack", packCmd =>
            {
                //help
                packCmd.Description = "Pack/Unpack PSBs to/from shell (FreeMote.Plugins required)";
                packCmd.HelpOption();
                packCmd.ExtendedHelpText = @"
Example:
  EmtConvert pack -s LZ4 sample.psb 
";
                //options
                var optType = packCmd.Option("-s|--shell <SHELL>",
                                             "Set shell type. No need to specify if unpack",
                                             CommandOptionType.SingleValue);
                //args
                var argPsbPaths = packCmd.Argument("PSB", "MDF/PSB Paths", true);

                packCmd.OnExecute(() =>
                {
                    string type = optType.HasValue() ? optType.Value() : null;
                    foreach (var s in argPsbPaths.Values)
                    {
                        if (File.Exists(s))
                        {
                            ShellConvert(s, type);
                        }
                    }
                });
            });

            //command: print
            app.Command("print", printCmd =>
            {
                //help
                printCmd.Description = "Print an EMT PSB (for its initial state, don't expect it working)";
                printCmd.HelpOption();
                printCmd.ExtendedHelpText = @"
Example:
  EmtConvert print -w 4096 -h 4096 sample.psb 
";
                //options
                var optWidth = printCmd.Option <int>("-w|--width <INT>",
                                                     "Set width. Default=-1 (auto)",
                                                     CommandOptionType.SingleValue);
                var optHeight = printCmd.Option <int>("-h|--height <INT>",
                                                      "Set height. Default=-1 (auto)",
                                                      CommandOptionType.SingleValue);
                //args
                var argPsbPaths = printCmd.Argument("PSB", "MDF/PSB Paths", true);

                printCmd.OnExecute(() =>
                {
                    int width  = optWidth.HasValue() ? optWidth.ParsedValue : -1;
                    int height = optHeight.HasValue() ? optHeight.ParsedValue : -1;
                    foreach (var s in argPsbPaths.Values)
                    {
                        if (File.Exists(s))
                        {
                            Draw(s, width, height);
                        }
                    }
                });
            });

            //mdf
            app.Command("mdf", mdfCmd =>
            {
                //help
                mdfCmd.Description = "Pack/Unpack MT19937 encrypted MDF (FreeMote.Plugins required)";
                mdfCmd.HelpOption();
                mdfCmd.ExtendedHelpText = @"
Example:
  EmtConvert mdf -k 1234567890ab -l 131 sample.psb 
  EmtConvert mdf -s 1234567890absample.psb -l 131 sample.psb 
  Hint: To pack a normal MDF, use `EmtConvert pack -s MDF <MDF file>`
";
                //options
                //var optMdfPack = mdfCmd.Option("-p|--pack",
                //    "Pack (Encrypt) a PSB to MT19937 MDF",
                //    CommandOptionType.NoValue);
                var optMdfSeed = mdfCmd.Option("-s|--seed <SEED>",
                                               "Set complete seed (Key+FileName)",
                                               CommandOptionType.SingleValue);
                var optMdfKey = mdfCmd.Option("-k|--key <KEY>",
                                              "Set key (Infer file name from path)",
                                              CommandOptionType.SingleValue);
                var optMdfKeyLen = mdfCmd.Option <uint>("-l|--length <LEN>",
                                                        "Set key length (not required if decrypt all bytes)",
                                                        CommandOptionType.SingleValue);
                //args
                var argPsbPaths = mdfCmd.Argument("PSB", "PSB Paths", true);

                mdfCmd.OnExecute(() =>
                {
                    string key  = optMdfKey.HasValue() ? optMdfKey.Value() : null;
                    string seed = optMdfSeed.HasValue() ? optMdfSeed.Value() : null;
                    if (string.IsNullOrEmpty(key) && string.IsNullOrEmpty(seed))
                    {
                        throw new ArgumentNullException("No key or seed specified.");
                    }

                    uint?len = optMdfKeyLen.HasValue() ? optMdfKeyLen.ParsedValue : (uint?)null;
                    Dictionary <string, object> context = new Dictionary <string, object>();
                    if (len.HasValue)
                    {
                        context["MdfKeyLength"] = len;
                    }

                    foreach (var s in argPsbPaths.Values)
                    {
                        if (File.Exists(s))
                        {
                            var fileName     = Path.GetFileName(s);
                            string finalSeed = seed;
                            if (key != null)
                            {
                                finalSeed = key + fileName;
                            }

                            context["MdfKey"] = finalSeed;
                            ShellConvert(s, "MDF", context);
                        }
                    }
                });
            });

            app.OnExecute(() =>
            {
                uint?key    = optKey.HasValue() ? optKey.ParsedValue : (uint?)null;
                uint?newKey = optNewKey.HasValue() ? optNewKey.ParsedValue : (uint?)null;

                foreach (var s in argPath.Values)
                {
                    if (File.Exists(s))
                    {
                        if (key != null && newKey != null) //Transfer
                        {
                            File.WriteAllBytes(Path.ChangeExtension(s, ".converted.psb"),
                                               PsbFile.Transfer(key.Value, newKey.Value, File.ReadAllBytes(s)));
                        }
                        else
                        {
                            Convert(key, s);
                        }
                    }
                }
            });

            if (args.Length == 0)
            {
                app.ShowHelp();
                Console.WriteLine("Convert all PSBs in current directory:");
                AskForKey();
                AskForNewKey();

                DirectoryInfo di    = new DirectoryInfo(Environment.CurrentDirectory);
                uint          count = 0;
                foreach (var file in di.EnumerateFiles("*.psb"))
                {
                    if (NewKey != null)
                    {
                        try
                        {
                            File.WriteAllBytes(Path.ChangeExtension(file.FullName, ".converted.psb"),
                                               PsbFile.Transfer(Key.Value, NewKey.Value, File.ReadAllBytes(file.FullName)));
                            count++;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Error: This file is not valid.");
                            Console.WriteLine(e);
                        }
                    }
                    else
                    {
                        if (Convert(Key, file.FullName))
                        {
                            count++;
                        }
                    }
                }

                Console.WriteLine($"Completed! {count} files processed in total.");
                Console.WriteLine("Press ENTER to exit...");
                Console.ReadLine();
                return;
            }

            app.Execute(args);

            Console.WriteLine("Done.");
        }
 /// <inheritdoc />
 public virtual void Generate(CommandLineApplication application, TextWriter output)
 {
     GenerateHeader(application, output);
     GenerateBody(application, output);
     GenerateFooter(application, output);
 }
Example #46
0
 public static int Main(string[] args) => CommandLineApplication.Execute<Program>(args);
Example #47
0
        static int Main(string[] args)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddTransient <IRetryHelper, RetryHelper>();
            serviceCollection.AddTransient <IProcessExitHandler, ProcessExitHandler>();
            serviceCollection.AddTransient <IFileSystem, FileSystem>();
            serviceCollection.AddTransient <ILogger, ConsoleLogger>();
            // We need to keep singleton/static semantics
            serviceCollection.AddSingleton <IInstrumentationHelper, InstrumentationHelper>();
            serviceCollection.AddSingleton <ISourceRootTranslator, SourceRootTranslator>(provider => new SourceRootTranslator(provider.GetRequiredService <ILogger>(), provider.GetRequiredService <IFileSystem>()));
            serviceCollection.AddSingleton <ICecilSymbolHelper, CecilSymbolHelper>();

            ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

            var         logger     = (ConsoleLogger)serviceProvider.GetService <ILogger>();
            IFileSystem fileSystem = serviceProvider.GetService <IFileSystem>();

            var app = new CommandLineApplication
            {
                Name     = "coverlet",
                FullName = "Cross platform .NET Core code coverage tool"
            };

            app.HelpOption("-h|--help");
            app.VersionOption("-v|--version", GetAssemblyVersion());
            int exitCode = (int)CommandExitCodes.Success;

            CommandArgument          moduleOrAppDirectory = app.Argument("<ASSEMBLY|DIRECTORY>", "Path to the test assembly or application directory.");
            CommandOption            target                  = app.Option("-t|--target", "Path to the test runner application.", CommandOptionType.SingleValue);
            CommandOption            targs                   = app.Option("-a|--targetargs", "Arguments to be passed to the test runner.", CommandOptionType.SingleValue);
            CommandOption            output                  = app.Option("-o|--output", "Output of the generated coverage report", CommandOptionType.SingleValue);
            CommandOption <LogLevel> verbosity               = app.Option <LogLevel>("-v|--verbosity", "Sets the verbosity level of the command. Allowed values are quiet, minimal, normal, detailed.", CommandOptionType.SingleValue);
            CommandOption            formats                 = app.Option("-f|--format", "Format of the generated coverage report.", CommandOptionType.MultipleValue);
            CommandOption            threshold               = app.Option("--threshold", "Exits with error if the coverage % is below value.", CommandOptionType.SingleValue);
            CommandOption            thresholdTypes          = app.Option("--threshold-type", "Coverage type to apply the threshold to.", CommandOptionType.MultipleValue);
            CommandOption            thresholdStat           = app.Option("--threshold-stat", "Coverage statistic used to enforce the threshold value.", CommandOptionType.SingleValue);
            CommandOption            excludeFilters          = app.Option("--exclude", "Filter expressions to exclude specific modules and types.", CommandOptionType.MultipleValue);
            CommandOption            includeFilters          = app.Option("--include", "Filter expressions to include only specific modules and types.", CommandOptionType.MultipleValue);
            CommandOption            excludedSourceFiles     = app.Option("--exclude-by-file", "Glob patterns specifying source files to exclude.", CommandOptionType.MultipleValue);
            CommandOption            includeDirectories      = app.Option("--include-directory", "Include directories containing additional assemblies to be instrumented.", CommandOptionType.MultipleValue);
            CommandOption            excludeAttributes       = app.Option("--exclude-by-attribute", "Attributes to exclude from code coverage.", CommandOptionType.MultipleValue);
            CommandOption            includeTestAssembly     = app.Option("--include-test-assembly", "Specifies whether to report code coverage of the test assembly.", CommandOptionType.NoValue);
            CommandOption            singleHit               = app.Option("--single-hit", "Specifies whether to limit code coverage hit reporting to a single hit for each location", CommandOptionType.NoValue);
            CommandOption            skipAutoProp            = app.Option("--skipautoprops", "Neither track nor record auto-implemented properties.", CommandOptionType.NoValue);
            CommandOption            mergeWith               = app.Option("--merge-with", "Path to existing coverage result to merge.", CommandOptionType.SingleValue);
            CommandOption            useSourceLink           = app.Option("--use-source-link", "Specifies whether to use SourceLink URIs in place of file system paths.", CommandOptionType.NoValue);
            CommandOption            doesNotReturnAttributes = app.Option("--does-not-return-attribute", "Attributes that mark methods that do not return.", CommandOptionType.MultipleValue);

            app.OnExecute(() =>
            {
                if (string.IsNullOrEmpty(moduleOrAppDirectory.Value) || string.IsNullOrWhiteSpace(moduleOrAppDirectory.Value))
                {
                    throw new CommandParsingException(app, "No test assembly or application directory specified.");
                }

                if (!target.HasValue())
                {
                    throw new CommandParsingException(app, "Target must be specified.");
                }

                if (verbosity.HasValue())
                {
                    // Adjust log level based on user input.
                    logger.Level = verbosity.ParsedValue;
                }

                CoverageParameters parameters = new()
                {
                    IncludeFilters          = includeFilters.Values.ToArray(),
                    IncludeDirectories      = includeDirectories.Values.ToArray(),
                    ExcludeFilters          = excludeFilters.Values.ToArray(),
                    ExcludedSourceFiles     = excludedSourceFiles.Values.ToArray(),
                    ExcludeAttributes       = excludeAttributes.Values.ToArray(),
                    IncludeTestAssembly     = includeTestAssembly.HasValue(),
                    SingleHit               = singleHit.HasValue(),
                    MergeWith               = mergeWith.Value(),
                    UseSourceLink           = useSourceLink.HasValue(),
                    SkipAutoProps           = skipAutoProp.HasValue(),
                    DoesNotReturnAttributes = doesNotReturnAttributes.Values.ToArray()
                };

                ISourceRootTranslator sourceRootTranslator = serviceProvider.GetRequiredService <ISourceRootTranslator>();

                Coverage coverage = new(moduleOrAppDirectory.Value,
                                        parameters,
                                        logger,
                                        serviceProvider.GetRequiredService <IInstrumentationHelper>(),
                                        fileSystem,
                                        sourceRootTranslator,
                                        serviceProvider.GetRequiredService <ICecilSymbolHelper>());
                coverage.PrepareModules();

                Process process                          = new();
                process.StartInfo.FileName               = target.Value();
                process.StartInfo.Arguments              = targs.HasValue() ? targs.Value() : string.Empty;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.OutputDataReceived              += (sender, eventArgs) =>
                {
                    if (!string.IsNullOrEmpty(eventArgs.Data))
                    {
                        logger.LogInformation(eventArgs.Data, important: true);
                    }
                };

                process.ErrorDataReceived += (sender, eventArgs) =>
                {
                    if (!string.IsNullOrEmpty(eventArgs.Data))
                    {
                        logger.LogError(eventArgs.Data);
                    }
                };

                process.Start();

                process.BeginErrorReadLine();
                process.BeginOutputReadLine();

                process.WaitForExit();

                string dOutput = output.HasValue() ? output.Value() : Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar.ToString();
                List <string> dThresholdTypes     = thresholdTypes.HasValue() ? thresholdTypes.Values : new List <string>(new string[] { "line", "branch", "method" });
                ThresholdStatistic dThresholdStat = thresholdStat.HasValue() ? Enum.Parse <ThresholdStatistic>(thresholdStat.Value(), true) : Enum.Parse <ThresholdStatistic>("minimum", true);

                logger.LogInformation("\nCalculating coverage result...");

                CoverageResult result = coverage.GetCoverageResult();

                string directory = Path.GetDirectoryName(dOutput);
                if (directory == string.Empty)
                {
                    directory = Directory.GetCurrentDirectory();
                }
                else if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                foreach (string format in formats.HasValue() ? formats.Values : new List <string>(new string[] { "json" }))
                {
                    Core.Abstractions.IReporter reporter = new ReporterFactory(format).CreateReporter();
                    if (reporter == null)
                    {
                        throw new Exception($"Specified output format '{format}' is not supported");
                    }

                    if (reporter.OutputType == ReporterOutputType.Console)
                    {
                        // Output to console
                        logger.LogInformation("  Outputting results to console", important: true);
                        logger.LogInformation(reporter.Report(result, sourceRootTranslator), important: true);
                    }
                    else
                    {
                        // Output to file
                        string filename = Path.GetFileName(dOutput);
                        filename        = (filename == string.Empty) ? $"coverage.{reporter.Extension}" : filename;
                        filename        = Path.HasExtension(filename) ? filename : $"{filename}.{reporter.Extension}";

                        string report = Path.Combine(directory, filename);
                        logger.LogInformation($"  Generating report '{report}'", important: true);
                        fileSystem.WriteAllText(report, reporter.Report(result, sourceRootTranslator));
                    }
                }

                var thresholdTypeFlagQueue = new Queue <ThresholdTypeFlags>();

                foreach (string thresholdType in dThresholdTypes)
                {
                    if (thresholdType.Equals("line", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Line);
                    }
                    else if (thresholdType.Equals("branch", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Branch);
                    }
                    else if (thresholdType.Equals("method", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Method);
                    }
                }

                var thresholdTypeFlagValues = new Dictionary <ThresholdTypeFlags, double>();
                if (threshold.HasValue() && threshold.Value().Contains(','))
                {
                    IEnumerable <string> thresholdValues = threshold.Value().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(t => t.Trim());
                    if (thresholdValues.Count() != thresholdTypeFlagQueue.Count)
                    {
                        throw new Exception($"Threshold type flag count ({thresholdTypeFlagQueue.Count}) and values count ({thresholdValues.Count()}) doesn't match");
                    }

                    foreach (string thresholdValue in thresholdValues)
                    {
                        if (double.TryParse(thresholdValue, out double value))
                        {
                            thresholdTypeFlagValues[thresholdTypeFlagQueue.Dequeue()] = value;
                        }
                        else
                        {
                            throw new Exception($"Invalid threshold value must be numeric");
                        }
                    }
                }
                else
                {
                    double thresholdValue = threshold.HasValue() ? double.Parse(threshold.Value()) : 0;

                    while (thresholdTypeFlagQueue.Any())
                    {
                        thresholdTypeFlagValues[thresholdTypeFlagQueue.Dequeue()] = thresholdValue;
                    }
                }

                var coverageTable = new ConsoleTable("Module", "Line", "Branch", "Method");
                var summary       = new CoverageSummary();

                CoverageDetails linePercentCalculation   = summary.CalculateLineCoverage(result.Modules);
                CoverageDetails branchPercentCalculation = summary.CalculateBranchCoverage(result.Modules);
                CoverageDetails methodPercentCalculation = summary.CalculateMethodCoverage(result.Modules);

                double totalLinePercent   = linePercentCalculation.Percent;
                double totalBranchPercent = branchPercentCalculation.Percent;
                double totalMethodPercent = methodPercentCalculation.Percent;

                double averageLinePercent   = linePercentCalculation.AverageModulePercent;
                double averageBranchPercent = branchPercentCalculation.AverageModulePercent;
                double averageMethodPercent = methodPercentCalculation.AverageModulePercent;

                foreach (KeyValuePair <string, Documents> _module in result.Modules)
                {
                    double linePercent   = summary.CalculateLineCoverage(_module.Value).Percent;
                    double branchPercent = summary.CalculateBranchCoverage(_module.Value).Percent;
                    double methodPercent = summary.CalculateMethodCoverage(_module.Value).Percent;

                    coverageTable.AddRow(Path.GetFileNameWithoutExtension(_module.Key), $"{InvariantFormat(linePercent)}%", $"{InvariantFormat(branchPercent)}%", $"{InvariantFormat(methodPercent)}%");
                }

                logger.LogInformation(coverageTable.ToStringAlternative());

                coverageTable.Columns.Clear();
                coverageTable.Rows.Clear();

                coverageTable.AddColumn(new[] { "", "Line", "Branch", "Method" });
                coverageTable.AddRow("Total", $"{InvariantFormat(totalLinePercent)}%", $"{InvariantFormat(totalBranchPercent)}%", $"{InvariantFormat(totalMethodPercent)}%");
                coverageTable.AddRow("Average", $"{InvariantFormat(averageLinePercent)}%", $"{InvariantFormat(averageBranchPercent)}%", $"{InvariantFormat(averageMethodPercent)}%");

                logger.LogInformation(coverageTable.ToStringAlternative());
                if (process.ExitCode > 0)
                {
                    exitCode += (int)CommandExitCodes.TestFailed;
                }

                ThresholdTypeFlags thresholdTypeFlags = result.GetThresholdTypesBelowThreshold(summary, thresholdTypeFlagValues, dThresholdStat);
                if (thresholdTypeFlags != ThresholdTypeFlags.None)
                {
                    exitCode += (int)CommandExitCodes.CoverageBelowThreshold;
                    var exceptionMessageBuilder = new StringBuilder();
                    if ((thresholdTypeFlags & ThresholdTypeFlags.Line) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} line coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Line]}");
                    }

                    if ((thresholdTypeFlags & ThresholdTypeFlags.Branch) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} branch coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Branch]}");
                    }

                    if ((thresholdTypeFlags & ThresholdTypeFlags.Method) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} method coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Method]}");
                    }
                    throw new Exception(exceptionMessageBuilder.ToString());
                }

                return(exitCode);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (CommandParsingException ex)
            {
                logger.LogError(ex.Message);
                app.ShowHelp();
                return((int)CommandExitCodes.CommandParsingException);
            }
            catch (Win32Exception we) when(we.Source == "System.Diagnostics.Process")
            {
                logger.LogError($"Start process '{target.Value()}' failed with '{we.Message}'");
                return(exitCode > 0 ? exitCode : (int)CommandExitCodes.Exception);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(exitCode > 0 ? exitCode : (int)CommandExitCodes.Exception);
            }
        }
Example #48
0
 public void OnExecuteIsNotInvokedWhenHelpOptionSpecified(string arg)
 {
     Assert.Equal(0, CommandLineApplication.Execute <SimpleHelpApp>(new TestConsole(_output), arg));
 }
Example #49
0
        static void Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name        = "AppFx-LocalizationExporter",
                Description = "Exporter for AppFx-Localizations supporting Mssql, Pgsql, Mysql, LiteDb, Assembly",
            };

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

            // add option for selecting the correct source type
            var sourceTypeOption = app
                                   .AddCliOption("-t | --type <type>", "ExportSourceType (Mssql, Pgsql, Mysql, LiteDb, Assembly")
                                   .IsRequired <string>()
                                   .ValidatedWith(EnumHelper.IsEnum <ExportSourceType>, "Invalid ExportSourceType")
                                   .TransformWith(EnumHelper.ParseEnum <ExportSourceType>);

            // add option to specify fileName / connectionString
            var sourceOption = app.AddCliOption("-s | --source <source>", "ExportSource (FileName, ConnectionString")
                               .IsRequired <string>();

            // add option to filter outpout by resourceKey
            var filterOption = app.AddCliOption("-f | --filter <filter>", "ResourceKeyFilter (case sensitive)")
                               .WithDefaultValue(string.Empty);

            // add option to specify exportFileName
            var exportFileNameOption = app.AddCliOption("-e | --exportFile <exportFile>",
                                                        "ExportFileName (example: \"./json/export\", default is common basePath of exported resources")
                                       .WithDefaultValue(string.Empty);

            app.OnExecute(() =>
            {
                Console.WriteLine(app.Name);

                var type = sourceTypeOption.Value();
                Console.WriteLine($"--> Using ExportSourceType {type}");

                var source = sourceOption.Value();
                Console.WriteLine($"--> Using Source {source}");

                var filter = filterOption.Value();
                if (!string.IsNullOrWhiteSpace(filter))
                {
                    Console.WriteLine($"--> Using Filter {filter}");
                }

                var reader  = ExportSourceReaderFactory.Create(type, source);
                var entries = string.IsNullOrWhiteSpace(filter)
                    ? reader.ReadAll()
                    : reader.ReadAll().Where(e => e.ResourceKey.StartsWith(filter));

                var optionValue  = exportFileNameOption.Value();
                var baseFileName = string.IsNullOrWhiteSpace(optionValue)
                    ? "./json/" + FindCommonBasePath(entries)
                    : optionValue;
                var fileName = $"{baseFileName}.json";
                Console.WriteLine($"--> Exporting to file {fileName}");

                var json = JsonConvert.SerializeObject(entries);

                // ensure old files are deleted
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                // ensure target directory exists
                var directoryName = new FileInfo(fileName).DirectoryName;
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                File.WriteAllText(fileName, json, Encoding.UTF8);

                return(0);
            });

            try
            {
                // parse and call OnExecute handler specified above
                app.Execute(args);
            }
            catch (CommandParsingException ex)
            {
                Console.WriteLine(app.Name);
                Console.WriteLine(app.Description);
                Console.WriteLine(ex.Message);
            }
        }
 public override void Configure(CommandLineApplication command)
 {
     _asUser = AsUserOption.ConfigureOption(command);
     base.Configure(command);
 }
Example #51
0
 static void Main(string[] args)
 {
     CommandLineApplication.Execute <Command>(args);
 }
Example #52
0
 public static int Main(string[] args)
 {
     return(CommandLineApplication.Execute <Program>(args));
 }
        /*
         * Example Usage - schemadump -sc "Server=NSWIN10VM.local;Database=WideWorldImportersDW;user id=sa;password=sa" -sf "/Users/rvegajr/Downloads/Schema/WideWorldImportersDW.db.json" -sn "WideWorldImportersDWEntities"
         */
        public static void Enable(CommandLineApplication app)
        {
            app.Command(CommandOperator, (command) =>
            {
                command.ExtendedHelpText = "Use the '" + CommandOperator + "' command to read the Connection String frorm the App Settings file or use the command line to dump the schema file";
                command.Description      = "Perform actions on the schema .";
                command.HelpOption("-?|-h|--help");

                var verboseOption = command.Option("-verbose|--verbose",
                                                   "Will display more detailed message about what is going on with the processing",
                                                   CommandOptionType.NoValue);

                var configFile = command.Option("-cf|--configfile",
                                                "the configuration file this template render will use.  the default will be in the same path as this assembly of this applicaiton.  This parm is optional and will override the value in appsettings.json.   ",
                                                CommandOptionType.SingleValue);

                var schemaOutput = command.Option("-sf|--schema-filename <value>",
                                                  "The file name or path to dump the schema to.  This is required field.",
                                                  CommandOptionType.SingleValue);

                var entityName = command.Option("-sn|--schema-name <value>",
                                                "The Name that will be given to the schema object.  This value will override the value in appsettings.json.   This is an optional field.",
                                                CommandOptionType.SingleValue);

                var connectionString = command.Option("-sc|--connection-string <optionvalue>",
                                                      "Connection String pass via the commandline.  This value will override the value in appsettings.json.  This is an optional field.",
                                                      CommandOptionType.SingleValue);

                var databaseType = command.Option("-db|--database-type <optionvalue>",
                                                  "Optional switch to force the appication to process as a certain database type.  This is an optional field.  Default is auto, but can be set to 'mssql' or 'ora'.",
                                                  CommandOptionType.SingleValue);

                command.OnExecute(() =>
                {
                    try
                    {
                        if (verboseOption.HasValue())
                        {
                            AppSettings.Instance.VerboseMessages = verboseOption.HasValue();
                        }
                        if (configFile.HasValue())
                        {
                            AppSettings.Instance.ConfigurationFileName = configFile.Value();
                        }
                        if (entityName.HasValue())
                        {
                            AppSettings.Instance.SchemaName = entityName.Value();
                        }
                        if (connectionString.HasValue())
                        {
                            AppSettings.Instance.ConnectionString = connectionString.Value();
                        }
                        var dbtype = (databaseType.HasValue() ? databaseType.Value() : "auto");

                        Console.WriteLine("Performing " + CommandName + "....");
                        Console.WriteLine("Connection String: " + AppSettings.Instance.ConnectionString);
                        Console.WriteLine("Schema Name: " + AppSettings.Instance.SchemaName);
                        Console.WriteLine("Output File/Path: " + schemaOutput.Value());
                        Console.WriteLine("Database Type: " + dbtype);
                        IDatabase schemaObject = null;
                        if ((AppSettings.Instance.ConnectionString.ToLower().Contains("database=")) || (dbtype.Equals("mssql")))
                        {
                            Console.WriteLine("Processing a mssql database");
                        }
                        else
                        {
                            throw new Exception(string.Format("Cannot figure out how to handle the connection string!  '{0}'", AppSettings.Instance.ConnectionString));
                        }
                        schemaObject.ShowWarnings = AppSettings.Instance.VerboseMessages;
                        schemaObject = schemaObject.Render(
                            AppSettings.Instance.SchemaName,
                            AppSettings.Instance.ConnectionString);

                        var schemaAsJson = JsonConvert.SerializeObject(
                            schemaObject
                            , Formatting.Indented
                            , new JsonSerializerSettings {
                            PreserveReferencesHandling = PreserveReferencesHandling.All
                        });
                        File.WriteAllText(schemaOutput.Value(), schemaAsJson);
                        Console.WriteLine(string.Format("Schema has been written to {0}", schemaOutput.Value()));

                        Console.WriteLine(CommandName + " has completed.");
                        Environment.ExitCode = (int)ReturnCode.Ok;
                        Environment.Exit(Environment.ExitCode);
                        return(Environment.ExitCode);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("{0} failed. {1}", CommandName, ex.Message));
                        Console.WriteLine("Stack Trace:");
                        Console.WriteLine(ex.StackTrace);
                        Environment.ExitCode = (int)ReturnCode.Error;
                        Environment.Exit(Environment.ExitCode);
                        return(Environment.ExitCode);
                    }
                });
            });
        }
        private static void Run(CommandLineApplication cmd, ILogger log)
        {
            cmd.Description = "Add empty dependency groups or remove dependencies from existing groups.";

            var idFilter             = cmd.Option(Constants.IdFilterTemplate, Constants.IdFilterDesc, CommandOptionType.SingleValue);
            var versionFilter        = cmd.Option(Constants.VersionFilterTemplate, Constants.VersionFilterDesc, CommandOptionType.SingleValue);
            var excludeSymbolsFilter = cmd.Option(Constants.ExcludeSymbolsTemplate, Constants.ExcludeSymbolsDesc, CommandOptionType.NoValue);
            var highestVersionFilter = cmd.Option(Constants.HighestVersionFilterTemplate, Constants.HighestVersionFilterDesc, CommandOptionType.NoValue);

            var frameworkOption = cmd.Option(Constants.FrameworkOptionTemplate, Constants.FrameworkOptionDesc, CommandOptionType.MultipleValue);

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

            cmd.HelpOption(Constants.HelpOption);

            var required = new List <CommandOption>()
            {
                frameworkOption
            };

            cmd.OnExecute(() =>
            {
                try
                {
                    var inputs = argRoot.Values;

                    if (inputs.Count < 1)
                    {
                        inputs.Add(Directory.GetCurrentDirectory());
                    }

                    // Validate parameters
                    foreach (var requiredOption in required)
                    {
                        if (!requiredOption.HasValue())
                        {
                            throw new ArgumentException($"Missing required parameter --{requiredOption.LongName}.");
                        }
                    }

                    var frameworks = new HashSet <NuGetFramework>();

                    if (frameworkOption.HasValue())
                    {
                        foreach (var option in frameworkOption.Values)
                        {
                            var fw = NuGetFramework.Parse(option);

                            log.LogInformation($"adding empty dependency groups for {fw.GetShortFolderName()}");

                            frameworks.Add(fw);
                        }
                    }

                    var packages = Util.GetPackagesWithFilter(idFilter, versionFilter, excludeSymbolsFilter, highestVersionFilter, inputs.ToArray());

                    foreach (var package in packages)
                    {
                        log.LogMinimal($"processing {package}");

                        // Get nuspec file path
                        string nuspecPath   = null;
                        XDocument nuspecXml = null;
                        using (var packageReader = new PackageArchiveReader(package))
                        {
                            nuspecPath = packageReader.GetNuspecFile();
                            nuspecXml  = XDocument.Load(packageReader.GetNuspec());
                        }

                        var metadata         = Util.GetMetadataElement(nuspecXml);
                        var ns               = metadata.GetDefaultNamespace().NamespaceName;
                        var dependenciesNode = metadata.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("dependencies", StringComparison.OrdinalIgnoreCase));

                        if (dependenciesNode == null)
                        {
                            dependenciesNode = new XElement(XName.Get("dependencies", ns));
                            metadata.Add(dependenciesNode);
                        }

                        // Convert non-grouped to group
                        var rootDeps = dependenciesNode.Elements()
                                       .Where(e => e.Name.LocalName.Equals("dependency", StringComparison.OrdinalIgnoreCase))
                                       .ToArray();

                        if (rootDeps.Length > 1)
                        {
                            var anyGroup = new XElement(XName.Get("group", ns));
                            dependenciesNode.AddFirst(anyGroup);

                            foreach (var rootDep in rootDeps)
                            {
                                rootDep.Remove();
                                anyGroup.Add(rootDep);
                            }
                        }

                        // Remove existing groups
                        foreach (var node in dependenciesNode.Elements()
                                 .Where(e => e.Name.LocalName.Equals("group", StringComparison.OrdinalIgnoreCase))
                                 .ToArray())
                        {
                            var groupFramework = NuGetFramework.AnyFramework;

                            var tfm = node.Attribute(XName.Get("targetFramework"))?.Value;

                            if (!string.IsNullOrEmpty(tfm))
                            {
                                groupFramework = NuGetFramework.Parse(tfm);
                            }

                            if (frameworks.Remove(groupFramework))
                            {
                                foreach (var child in node.Elements().ToArray())
                                {
                                    child.Remove();
                                }
                            }
                        }

                        // Add empty groups for those remaining
                        foreach (var fw in frameworks)
                        {
                            var groupNode = DependenciesUtil.CreateGroupNode(ns, fw);

                            dependenciesNode.Add(groupNode);
                        }

                        // Update zip
                        Util.AddOrReplaceZipEntry(package, nuspecPath, nuspecXml, log);
                    }

                    return(0);
                }
                catch (Exception ex)
                {
                    log.LogError(ex.Message);
                    log.LogDebug(ex.ToString());
                }

                return(1);
            });
        }
Example #55
0
 private void OnExecute(CommandLineApplication <CaptureRemainingArgsCommand> app)
 {
 }
Example #56
0
 private void OnExecute(CommandLineApplication <Write42Command> app)
 {
     app.Out.WriteLine("42");
 }
Example #57
0
        //--- Methods --
        public void Register(CommandLineApplication app)
        {
            app.Command("util", cmd => {
                cmd.HelpOption();
                cmd.Description = "Miscellaneous AWS utilities";

                // delete orphaned logs sub-command
                cmd.Command("delete-orphan-lambda-logs", subCmd => {
                    subCmd.HelpOption();
                    subCmd.Description = "Delete orphaned Lambda CloudWatch logs";
                    var dryRunOption   = subCmd.Option("--dryrun", "(optional) Check which logs to delete without deleting them", CommandOptionType.NoValue);

                    // run command
                    subCmd.OnExecute(async() => {
                        Console.WriteLine($"{app.FullName} - {subCmd.Description}");
                        await DeleteOrphanLambdaLogsAsync(dryRunOption.HasValue());
                    });
                });

                // download cloudformation specification sub-command
                cmd.Command("download-cloudformation-spec", subCmd => {
                    subCmd.HelpOption();
                    subCmd.Description = "Download CloudFormation JSON specification to LAMBDASHARP development folder";
                    subCmd.OnExecute(async() => {
                        Console.WriteLine($"{app.FullName} - {subCmd.Description}");

                        // determine destination folder
                        var lambdaSharpFolder = System.Environment.GetEnvironmentVariable("LAMBDASHARP");
                        if (lambdaSharpFolder == null)
                        {
                            LogError("LAMBDASHARP environment variable is not defined");
                            return;
                        }
                        var destinationZipLocation  = Path.Combine(lambdaSharpFolder, "src", "LambdaSharp.Tool", "Resources", "CloudFormationResourceSpecification.json.gz");
                        var destinationJsonLocation = Path.Combine(lambdaSharpFolder, "src", "CloudFormationResourceSpecification.json");

                        // run command
                        await RefreshCloudFormationSpecAsync(
                            "https://d1uauaxba7bl26.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
                            destinationZipLocation,
                            destinationJsonLocation
                            );
                    });
                });

                cmd.Command("create-invoke-methods-schema", subCmd => {
                    subCmd.HelpOption();
                    subCmd.Description         = "Create JSON schemas for API Gateway invoke methods";
                    var directoryOption        = subCmd.Option("--directory|-d", "Directory where .NET assemblies are located", CommandOptionType.SingleValue);
                    var methodOption           = subCmd.Option("--method|-m", "Name of a method to analyze", CommandOptionType.MultipleValue);
                    var defaultNamespaceOption = subCmd.Option("--default-namespace|-ns", "(optional) Default namespace for resolving class names", CommandOptionType.SingleValue);
                    var outputFileOption       = subCmd.Option("--out|-o", "(optional) Output schema file location (default: console out)", CommandOptionType.SingleValue);
                    var noBannerOption         = subCmd.Option("--quiet", "Don't show banner or execution time", CommandOptionType.NoValue);
                    subCmd.OnExecute(async() => {
                        Program.Quiet = noBannerOption.HasValue();
                        if (!Program.Quiet)
                        {
                            Console.WriteLine($"{app.FullName} - {subCmd.Description}");
                        }

                        // validate options
                        if (directoryOption.Value() == null)
                        {
                            LogError("missing --assembly option");
                            return;
                        }
                        if (!methodOption.Values.Any())
                        {
                            LogError("missing --method option(s)");
                            return;
                        }
                        await CreateInvocationTargetSchemasAsync(
                            directoryOption.Value(),
                            defaultNamespaceOption.Value(),
                            methodOption.Values,
                            outputFileOption.Value()
                            );
                    });
                });

                // show help text if no sub-command is provided
                cmd.OnExecute(() => {
                    Console.WriteLine(cmd.GetHelpText());
                });
            });
        }
Example #58
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            CommandLineApplication commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: false);
            CommandOption          seedArg = commandLineApplication.Option(
                "-s |--s <seed>",
                "The seed for the randomizer. "
                + " Same seed will produce the same map. Defaults to random value.",
                CommandOptionType.SingleValue);
            CommandOption pathArg = commandLineApplication.Option(
                "-p |--p <path>",
                "Path to Ultima 4 installation. "
                + " Leaving blank will assume it is the working directory.",
                CommandOptionType.SingleValue);
            CommandOption restoreArg = commandLineApplication.Option(
                "-r |--r",
                "Restore original Ultima 4 files. ",
                CommandOptionType.NoValue);
            CommandOption encodedArg = commandLineApplication.Option(
                "-e |--encoded",
                "Encoded flags. Overrides all other flags. ",
                CommandOptionType.SingleValue);
            CommandOption minimapArg = commandLineApplication.Option(
                "--miniMap",
                "Output a minimap of the overworld. ",
                CommandOptionType.NoValue);
            CommandOption overworldArg = commandLineApplication.Option(
                "-o |--overworld",
                "Sets randomization level for Overworld map. 1 for no change. 2 for shuffle overworld locations. 5 for randomize the entire map. Defaults to 5.",
                CommandOptionType.SingleValue);
            CommandOption spellRemoveArg = commandLineApplication.Option(
                "--spellRemove",
                "Put in the letters of the spells you want removed. e.g. \"--spellRemove zed\" would remove zdown, energy field and dispel. ",
                CommandOptionType.SingleValue);
            CommandOption startingWeapons = commandLineApplication.Option(
                "--startingWeaponsArmor",
                "Randomize the weapons and armor player and companions start with.",
                CommandOptionType.NoValue);
            CommandOption minQuantityArg = commandLineApplication.Option(
                "--mixQuantity",
                "Lets you input how much of a spell you want to mix. ",
                CommandOptionType.NoValue);
            CommandOption dngStoneArg = commandLineApplication.Option(
                "--dngStone",
                "Randomize the location of stones in the dungeons ",
                CommandOptionType.NoValue);
            CommandOption fixesArg = commandLineApplication.Option(
                "--fixes",
                "Collection of non-gameplay fixes.",
                CommandOptionType.NoValue);
            CommandOption hythlothFixArg = commandLineApplication.Option(
                "--hythlothFix",
                "Fixes an issue with Hythloth dungeon room.",
                CommandOptionType.NoValue);
            CommandOption sleepLockAssistArg = commandLineApplication.Option(
                "--sleepLockAssist",
                "Helps prevent sleeplock in battles.",
                CommandOptionType.NoValue);
            CommandOption activePlayerArg = commandLineApplication.Option(
                "--activePlayer",
                "Allow selecting which characters are active in combat.",
                CommandOptionType.NoValue);
            CommandOption appleHitChanceArg = commandLineApplication.Option(
                "--appleHitChance",
                "Change hit chance to behave like the original Apple II version.",
                CommandOptionType.NoValue);
            CommandOption diagonalAttackArg = commandLineApplication.Option(
                "--diagonalAttack",
                "Allow diagonal attacks in combat.",
                CommandOptionType.NoValue);
            CommandOption sacrificeFixArg = commandLineApplication.Option(
                "--sacrificeFix",
                "Adds a way to gain sacrifice which the shrine says should work.",
                CommandOptionType.NoValue);
            CommandOption runesArg = commandLineApplication.Option(
                "--runes",
                "Randomize the location of the runes.",
                CommandOptionType.NoValue);
            CommandOption mantrasArg = commandLineApplication.Option(
                "--mantras",
                "Randomize the mantras.",
                CommandOptionType.NoValue);
            CommandOption wordOfPassageArg = commandLineApplication.Option(
                "--wordOfPassage",
                "Randomize the Word of Passage.",
                CommandOptionType.NoValue);
            CommandOption questItemsArg = commandLineApplication.Option(
                "--questItems <0-100>",
                "Percentage chance to start with a quest item.",
                CommandOptionType.SingleValue);
            CommandOption karmaValueArg = commandLineApplication.Option(
                "--karmaValue <value>",
                "Value to override starting karma value for a virtue. Leave blank for random.",
                CommandOptionType.SingleValue);
            CommandOption karmaPercentageArg = commandLineApplication.Option(
                "--karmaPercentage <0-100>",
                "Percentage chance to override a starting karma value for a virtue. Default 0 (no override).",
                CommandOptionType.SingleValue);
            CommandOption monsterDamageArg = commandLineApplication.Option(
                "--monsterDamage <0-3>",
                "Value to change how much damage monsters do. Allowed values 0-3. 0 is quad damage. 1 is more damge. 2 is default. 3 is less damage.",
                CommandOptionType.SingleValue);
            CommandOption weaponDamageArg = commandLineApplication.Option(
                "--weaponDamage <1-3>",
                "Value to change how much damage weapons do. Allowed values 1-3. 1 is more damge. 2 is default. 3 is less damage.",
                CommandOptionType.SingleValue);
            CommandOption earlierMonstersArg = commandLineApplication.Option(
                "--earlierMonsters",
                "Make more difficult monsters appear earlier.",
                CommandOptionType.NoValue);
            CommandOption monsterQtyArg = commandLineApplication.Option(
                "--monsterQty",
                "More monsters from the start.",
                CommandOptionType.NoValue);
            CommandOption noRequireFullPartyArg = commandLineApplication.Option(
                "--noRequireFullParty",
                "Don't require the full party.",
                CommandOptionType.NoValue);
            CommandOption randomizeSpellsArg = commandLineApplication.Option(
                "--randomizeSpells",
                "Randomizes the gate and resurrection spells that you learn in game.",
                CommandOptionType.NoValue);
            CommandOption sextantArg = commandLineApplication.Option(
                "--sextant",
                "Start with a sextant.",
                CommandOptionType.NoValue);
            CommandOption clothMapArg = commandLineApplication.Option(
                "--clothMap",
                "Cloth map of the world.",
                CommandOptionType.NoValue);
            CommandOption vgaPatchArg = commandLineApplication.Option(
                "--vgaPatch",
                "VGA patch compatibility.",
                CommandOptionType.NoValue);

            CommandOption spoilerLogArg = commandLineApplication.Option(
                "--spoilerLog",
                "Output a spoiler log.",
                CommandOptionType.NoValue);

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

            commandLineApplication.OnExecute(() =>
            {
                var seed = Environment.TickCount;
                if (seedArg.HasValue())
                {
                    if (!int.TryParse(seedArg.Value(), out seed))
                    {
                        throw new InvalidCastException("Seed must be a number");
                    }
                }

                var overworld = 5;
                if (overworldArg.HasValue())
                {
                    if (!int.TryParse(overworldArg.Value(), out overworld))
                    {
                        throw new InvalidCastException("Overworld argument must be a number");
                    }
                }

                var questItems = 0;
                if (questItemsArg.HasValue())
                {
                    if (!int.TryParse(questItemsArg.Value(), out questItems) && questItems >= 0 && questItems <= 100)
                    {
                        throw new InvalidCastException("QuestItems argument must be a number between 0 and 100 inclusive");
                    }
                }

                var karmaPercentage = 0;
                if (karmaPercentageArg.HasValue())
                {
                    if (!int.TryParse(karmaPercentageArg.Value(), out karmaPercentage) && karmaPercentage >= 0 && karmaPercentage <= 100)
                    {
                        throw new InvalidCastException("KarmaPercentage argument must be a number between 0 and 100 inclusive");
                    }
                }

                int?karmaValue    = null;
                var karmaValueTmp = 0;
                if (karmaValueArg.HasValue())
                {
                    if (!int.TryParse(karmaValueArg.Value(), out karmaValueTmp) && karmaValueTmp >= 1 && karmaValueTmp <= 100)
                    {
                        throw new InvalidCastException("KarmaValue argument must be a number between 1 and 100 inclusive");
                    }

                    karmaValue = karmaValueTmp;
                }

                int monsterDamage    = 2;
                var monsterDamageTmp = 2;
                if (monsterDamageArg.HasValue())
                {
                    if (!int.TryParse(monsterDamageArg.Value(), out monsterDamageTmp) && monsterDamageTmp >= 0 && monsterDamageTmp <= 3)
                    {
                        throw new InvalidCastException("MonsterDamage argument must be a number between 0 and 3 inclusive");
                    }

                    monsterDamage = monsterDamageTmp;
                }

                int weaponDamage    = 2;
                var weaponDamageTmp = 2;
                if (weaponDamageArg.HasValue())
                {
                    if (!int.TryParse(weaponDamageArg.Value(), out weaponDamageTmp) && weaponDamageTmp >= 1 && weaponDamageTmp <= 3)
                    {
                        throw new InvalidCastException("WeaponDamage argument must be a number between 1 and 3 inclusive");
                    }

                    weaponDamage = weaponDamageTmp;
                }

                var path = Directory.GetCurrentDirectory();
                if (pathArg.HasValue())
                {
                    if (!Directory.Exists(pathArg.Value()))
                    {
                        throw new ArgumentException("Path provided does not exist");
                    }
                    else
                    {
                        path = pathArg.Value();
                    }
                }
                if (!File.Exists(Path.Combine(path, "WORLD.MAP")))
                {
                    Console.Write("Could not find WORLD.MAP please provide path:  ");
                    path = Console.ReadLine().Trim();

                    if (!Directory.Exists(path))
                    {
                        throw new ArgumentException("Path provided does not exist");
                    }
                }

                if (restoreArg.HasValue())
                {
                    Restore(path);
                }
                else
                {
                    Flags flags               = new Flags(seed, 9);
                    flags.Overworld           = overworld;
                    flags.MiniMap             = minimapArg.HasValue();
                    flags.SpellRemove         = spellRemoveArg.Value();
                    flags.StartingWeapons     = startingWeapons.HasValue();
                    flags.DngStone            = dngStoneArg.HasValue();
                    flags.MixQuantity         = minQuantityArg.HasValue();
                    flags.Fixes               = fixesArg.HasValue();
                    flags.FixHythloth         = hythlothFixArg.HasValue();
                    flags.SleepLockAssist     = sleepLockAssistArg.HasValue();
                    flags.ActivePlayer        = activePlayerArg.HasValue();
                    flags.HitChance           = appleHitChanceArg.HasValue();
                    flags.DiagonalAttack      = diagonalAttackArg.HasValue();
                    flags.SacrificeFix        = sacrificeFixArg.HasValue();
                    flags.Runes               = runesArg.HasValue();
                    flags.Mantras             = mantrasArg.HasValue();
                    flags.WordOfPassage       = wordOfPassageArg.HasValue();
                    flags.QuestItemPercentage = questItems;
                    flags.KarmaSetPercentage  = karmaPercentage;
                    flags.KarmaValue          = karmaValue;
                    flags.MonsterDamage       = monsterDamage;
                    flags.WeaponDamage        = weaponDamage;
                    flags.EarlierMonsters     = earlierMonstersArg.HasValue();
                    flags.MonsterQty          = monsterQtyArg.HasValue();
                    flags.NoRequireFullParty  = noRequireFullPartyArg.HasValue();
                    flags.RandomizeSpells     = randomizeSpellsArg.HasValue();
                    flags.Sextant             = sextantArg.HasValue();
                    flags.ClothMap            = clothMapArg.HasValue();
                    flags.SpoilerLog          = spoilerLogArg.HasValue();
                    flags.VGAPatch            = vgaPatchArg.HasValue();
                    Randomize(seed, path, flags, encodedArg.Value());
                    //Console.WriteLine("Seed: " + seed);
                    //var random = new Random(seed);
                    //var worldMap = new WorldMap();
                    //worldMap.SwampTest(random);
                    //worldMap.Save(path);

                    //var image = worldMap.ToImage();
                    //image.SaveAsPng("worldMap.png");
                }

                return(0);
            });
            commandLineApplication.Execute(args);
        }
Example #59
0
        public static BuildCommand FromArgs(string[] args, string msbuildPath = null)
        {
            CommandLineApplication app = new CommandLineApplication(throwOnUnexpectedArg: false);

            app.Name        = "dotnet build";
            app.FullName    = LocalizableStrings.AppFullName;
            app.Description = LocalizableStrings.AppDescription;
            app.ArgumentSeparatorHelpText = HelpMessageStrings.MSBuildAdditionalArgsHelpText;
            app.HandleRemainingArguments  = true;
            app.HelpOption("-h|--help");

            CommandArgument projectArgument = app.Argument($"<{LocalizableStrings.ProjectArgumentValueName}>", LocalizableStrings.ProjectArgumentDescription);

            CommandOption outputOption    = app.Option($"-o|--output <{LocalizableStrings.OutputOptionName}>", LocalizableStrings.OutputOptionDescription, CommandOptionType.SingleValue);
            CommandOption frameworkOption = app.Option($"-f|--framework <{LocalizableStrings.FrameworkOptionName}>", LocalizableStrings.FrameworkOptionDescription, CommandOptionType.SingleValue);
            CommandOption runtimeOption   = app.Option(
                $"-r|--runtime <{LocalizableStrings.RuntimeOptionName}>", LocalizableStrings.RuntimeOptionDescription,
                CommandOptionType.SingleValue);
            CommandOption configurationOption = app.Option($"-c|--configuration <{LocalizableStrings.ConfigurationOptionName}>", LocalizableStrings.ConfigurationOptionDescription, CommandOptionType.SingleValue);
            CommandOption versionSuffixOption = app.Option($"--version-suffix <{LocalizableStrings.VersionSuffixOptionName}>", LocalizableStrings.VersionSuffixOptionDescription, CommandOptionType.SingleValue);

            CommandOption noIncrementalOption  = app.Option("--no-incremental", LocalizableStrings.NoIncrementialOptionDescription, CommandOptionType.NoValue);
            CommandOption noDependenciesOption = app.Option("--no-dependencies", LocalizableStrings.NoDependenciesOptionDescription, CommandOptionType.NoValue);
            CommandOption verbosityOption      = MSBuildForwardingApp.AddVerbosityOption(app);

            List <string> msbuildArgs = null;

            app.OnExecute(() =>
            {
                // this delayed initialization is here intentionally
                // this code will not get run in some cases (i.e. --help)
                msbuildArgs = new List <string>();

                if (!string.IsNullOrEmpty(projectArgument.Value))
                {
                    msbuildArgs.Add(projectArgument.Value);
                }

                if (noIncrementalOption.HasValue())
                {
                    msbuildArgs.Add("/t:Rebuild");
                }
                else
                {
                    msbuildArgs.Add("/t:Build");
                }

                if (outputOption.HasValue())
                {
                    msbuildArgs.Add($"/p:OutputPath={outputOption.Value()}");
                }

                if (frameworkOption.HasValue())
                {
                    msbuildArgs.Add($"/p:TargetFramework={frameworkOption.Value()}");
                }

                if (runtimeOption.HasValue())
                {
                    msbuildArgs.Add($"/p:RuntimeIdentifier={runtimeOption.Value()}");
                }

                if (configurationOption.HasValue())
                {
                    msbuildArgs.Add($"/p:Configuration={configurationOption.Value()}");
                }

                if (versionSuffixOption.HasValue())
                {
                    msbuildArgs.Add($"/p:VersionSuffix={versionSuffixOption.Value()}");
                }

                if (noDependenciesOption.HasValue())
                {
                    msbuildArgs.Add("/p:BuildProjectReferences=false");
                }

                if (verbosityOption.HasValue())
                {
                    msbuildArgs.Add($"/verbosity:{verbosityOption.Value()}");
                }

                msbuildArgs.Add($"/clp:Summary");

                msbuildArgs.AddRange(app.RemainingArguments);

                return(0);
            });

            int exitCode = app.Execute(args);

            if (msbuildArgs == null)
            {
                throw new CommandCreationException(exitCode);
            }

            return(new BuildCommand(msbuildArgs, msbuildPath));
        }
Example #60
0
        private static int Main(string[] args)
        {
            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json");

            Configuration = configurationBuilder.Build();

            var self     = typeof(Program).GetTypeInfo().Assembly;
            var client   = new MongoClient(new MongoUrl(Configuration["mongoDb:url"]));
            var database = client.GetDatabase(Configuration["mongoDb:database"]);

            BsonClassMapping.Register();

            var builder = new ContainerBuilder();

            builder.RegisterModule(new AutofacModule(database));
            builder.RegisterModule(new Server.Services.DependencyResolution.AutofacModule());

            builder.RegisterInstance(new TokenFactorySettings
            {
                SecretKey = Configuration["oAuth:secretKey"],
                Audience  = Configuration["oAuth:audience"],
                Issuer    = Configuration["oAuth:issuer"]
            });

            var commands = self.GetTypes()
                           .Where(a => typeof(ICommand).IsAssignableFrom(a) && !a.GetTypeInfo().IsAbstract);

            foreach (var type in commands)
            {
                builder.RegisterType(type).AsSelf();
            }

            var container = builder.Build();

            var app = new CommandLineApplication();


            app.Name = "toolbox";
            app.HelpOption("-?|-h|--help");

            if (args.Length == 0)
            {
                args = new[] { "-h" }
            }
            ;


            foreach (var type in commands)
            {
                var command = (ICommand)container.Resolve(type);
                app.Command(command.Name, command.Register);
            }

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(0);
        }
    }