Beispiel #1
0
 void contentForm_CommandClick(object sender, CommandArgument e)
 {
     cf.SetChanges();
     ContentFormResult cfr = cf.GetChanges();
     cfr.Argument = e.Argument;
     WebDialogueContext.SendResult(cfr);
 }
Beispiel #2
0
        public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult )
        {
            CommandResult = null;

            System.UriBuilder searchBinding = new System.UriBuilder();

            searchBinding.Scheme = "http";
            searchBinding.Host = searchServer;
            searchBinding.Path = searchRoot;

            string searchQuery = searchQueryPrefix;

            for ( int currentArgument = 1; currentArgument < Arguments.Length; currentArgument++ )
            {
                if ( currentArgument > 1 )
                {
                    searchQuery += "%20";
                }

                searchQuery += Arguments[currentArgument].GetArgument();
            }

            searchBinding.Query = searchQuery;

            _Terminal.WriteTo(
                new StringBuilder( searchBinding.ToString() + "\n\n" ),
                ConsoleProcessRedirection.OutputType.StandardOutput );

            PageCommand pageRetriever = new PageCommand(
                _CommandProcessor,
                new NullTerminal() );

            ICommandArgument[] showArguments = new ICommandArgument[2];

            showArguments[0] = Arguments[0];
            showArguments[1] = new CommandArgument( searchBinding.ToString() );

            pageRetriever.PerformCommand(
                showArguments,
                out CommandResult );

            string resultString = ( (StringBuilder) CommandResult.GetArgument() ).ToString();

            string[] links = FindLinks( resultString );

            foreach ( string link in links )
            {
                _Terminal.WriteTo(
                    new StringBuilder( link + "\n\n" ),
                    ConsoleProcessRedirection.OutputType.StandardOutput );
            }

            return 0;
        }
Beispiel #3
0
		public void SetArgs(CommandArgument[] args)
		{
			bool pastOptional = false;
			foreach (var arg in args)
			{
				if (arg.Optional) pastOptional = true;
				if (!arg.Optional && pastOptional) throw new Exception("Cannot define a non-optional argument after an optional argument has been defined.");
				if (string.IsNullOrEmpty(arg.Name)) throw new Exception("Empty or null name for command argument");
				if (arg.CommandType == null) throw new Exception("Invalid type for command argument");
			}
			this.Arguments.Value = args;
		}
Beispiel #4
0
        static int Main(string[] args)
        {
            var logger = new ConsoleLogger();
            var app    = new CommandLineApplication();

            app.Name     = "coverlet";
            app.FullName = "Cross platform .NET Core code coverage tool";
            app.HelpOption("-h|--help");
            app.VersionOption("-v|--version", GetAssemblyVersion());

            CommandArgument          module              = app.Argument("<ASSEMBLY>", "Path to the test assembly.");
            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            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);

            app.OnExecute(() =>
            {
                if (string.IsNullOrEmpty(module.Value) || string.IsNullOrWhiteSpace(module.Value))
                {
                    throw new CommandParsingException(app, "No test assembly 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;
                }

                // We add default exclusion filter if no specified
                if (excludeFilters.Values.Count == 0)
                {
                    excludeFilters.Values.Add("[xunit*]*");
                }

                Coverage coverage = new Coverage(module.Value,
                                                 includeFilters.Values.ToArray(),
                                                 includeDirectories.Values.ToArray(),
                                                 excludeFilters.Values.ToArray(),
                                                 excludedSourceFiles.Values.ToArray(),
                                                 excludeAttributes.Values.ToArray(),
                                                 includeTestAssembly.HasValue(),
                                                 singleHit.HasValue(),
                                                 mergeWith.Value(),
                                                 useSourceLink.HasValue(),
                                                 logger);
                coverage.PrepareModules();

                Process process                          = new Process();
                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();

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

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

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

                foreach (var format in (formats.HasValue() ? formats.Values : new List <string>(new string[] { "json" })))
                {
                    var 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), important: true);
                    }
                    else
                    {
                        // Output to file
                        var filename = Path.GetFileName(dOutput);
                        filename     = (filename == string.Empty) ? $"coverage.{reporter.Extension}" : filename;
                        filename     = Path.HasExtension(filename) ? filename : $"{filename}.{reporter.Extension}";

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

                var thresholdTypeFlags = ThresholdTypeFlags.None;

                foreach (var thresholdType in dThresholdTypes)
                {
                    if (thresholdType.Equals("line", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlags |= ThresholdTypeFlags.Line;
                    }
                    else if (thresholdType.Equals("branch", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlags |= ThresholdTypeFlags.Branch;
                    }
                    else if (thresholdType.Equals("method", StringComparison.OrdinalIgnoreCase))
                    {
                        thresholdTypeFlags |= ThresholdTypeFlags.Method;
                    }
                }

                var coverageTable = new ConsoleTable("Module", "Line", "Branch", "Method");
                var summary       = new CoverageSummary();
                int numModules    = result.Modules.Count;

                var totalLinePercent   = summary.CalculateLineCoverage(result.Modules).Percent;
                var totalBranchPercent = summary.CalculateBranchCoverage(result.Modules).Percent;
                var totalMethodPercent = summary.CalculateMethodCoverage(result.Modules).Percent;

                foreach (var _module in result.Modules)
                {
                    var linePercent   = summary.CalculateLineCoverage(_module.Value).Percent;
                    var branchPercent = summary.CalculateBranchCoverage(_module.Value).Percent;
                    var methodPercent = summary.CalculateMethodCoverage(_module.Value).Percent;

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

                logger.LogInformation(coverageTable.ToStringAlternative());

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

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

                logger.LogInformation(coverageTable.ToStringAlternative());

                thresholdTypeFlags = result.GetThresholdTypesBelowThreshold(summary, dThreshold, thresholdTypeFlags, dThresholdStat);
                if (thresholdTypeFlags != ThresholdTypeFlags.None)
                {
                    var exceptionMessageBuilder = new StringBuilder();
                    if ((thresholdTypeFlags & ThresholdTypeFlags.Line) != ThresholdTypeFlags.None)
                    {
                        exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} line coverage is below the specified {dThreshold}");
                    }

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

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

                    throw new Exception(exceptionMessageBuilder.ToString());
                }

                return(process.ExitCode == 0 ? 0 : process.ExitCode);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (CommandParsingException ex)
            {
                logger.LogError(ex.Message);
                app.ShowHelp();
                return(1);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(1);
            }
        }
        internal static void Register(CommandLineApplication app,
                                      Func <ILogger> getLogger,
                                      Action <LogLevel> setLogLevel)
        {
            app.Command("trust", trustedSignersCmd =>
            {
                CommandArgument command = trustedSignersCmd.Argument(
                    "<command>",
                    Strings.TrustCommandActionDescription,
                    multipleValues: true);

                CommandOption algorithm = trustedSignersCmd.Option(
                    "--algorithm",
                    Strings.TrustCommandAlgorithm,
                    CommandOptionType.SingleValue);

                CommandOption allowUntrustedRootOption = trustedSignersCmd.Option(
                    "--allow-untrusted-root",
                    Strings.TrustCommandAllowUntrustedRoot,
                    CommandOptionType.NoValue);

                CommandOption owners = trustedSignersCmd.Option(
                    "--owners",
                    Strings.TrustCommandOwners,
                    CommandOptionType.MultipleValue);

                CommandOption verbosity = trustedSignersCmd.Option(
                    "-v|--verbosity",
                    Strings.Verbosity_Description,
                    CommandOptionType.SingleValue);

                CommandOption configFile = trustedSignersCmd.Option(
                    "--configfile",
                    Strings.Option_ConfigFile,
                    CommandOptionType.SingleValue);

                trustedSignersCmd.HelpOption(XPlatUtility.HelpOption);
                trustedSignersCmd.Description = Strings.TrustCommandDescription;

                trustedSignersCmd.OnExecute(async() =>
                {
                    TrustCommand action;

                    if (!command.Values.Any() || string.IsNullOrEmpty(command.Values[0]))
                    {
                        action = TrustCommand.List;
                    }
                    else if (!Enum.TryParse(command.Values[0], ignoreCase: true, result: out action))
                    {
                        throw new CommandLineArgumentCombinationException(string.Format(CultureInfo.CurrentCulture, Strings.Error_UnknownAction, command.Values[0]));
                    }

                    string name = null;

                    if (command.Values.Count > 1)
                    {
                        name = command.Values[1];
                    }

                    string packagePath = null;
                    string sourceUrl   = null;
                    string fingerprint = null;
                    if (command.Values.Count() > 2)
                    {
                        if (action == TrustCommand.Author || action == TrustCommand.Repository)
                        {
                            packagePath = command.Values[2];
                        }
                        else if (action == TrustCommand.Source)
                        {
                            sourceUrl = command.Values[2];
                        }
                        else if (action == TrustCommand.Certificate)
                        {
                            fingerprint = command.Values[2];
                        }
                    }

                    ISettings settings = ProcessConfigFile(configFile.Value());

                    var trustedSignersArgs = new TrustedSignersArgs()
                    {
                        Action                 = MapTrustEnumAction(action),
                        PackagePath            = packagePath,
                        Name                   = name,
                        ServiceIndex           = sourceUrl,
                        CertificateFingerprint = fingerprint,
                        FingerprintAlgorithm   = algorithm.Value(),
                        AllowUntrustedRoot     = allowUntrustedRootOption.HasValue(),
                        Author                 = action == TrustCommand.Author,
                        Repository             = action == TrustCommand.Repository,
                        Owners                 = CommandLineUtility.SplitAndJoinAcrossMultipleValues(owners.Values),
                        Logger                 = getLogger()
                    };

                    setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value()));

#pragma warning disable CS0618 // Type or member is obsolete
                    var sourceProvider = new PackageSourceProvider(settings, enablePackageSourcesChangedEvent: false);
#pragma warning restore CS0618 // Type or member is obsolete
                    var trustedSignersProvider = new TrustedSignersProvider(settings);

                    var runner = new TrustedSignersCommandRunner(trustedSignersProvider, sourceProvider);
                    Task <int> trustedSignTask = runner.ExecuteCommandAsync(trustedSignersArgs);
                    return(await trustedSignTask);
                });
            });
        }
 public FilterTablesCommand(CommandArgument connectionIdArg, CommandArgument tablesArg, GlobalOptions globalOptions)
 {
     _tablesArg       = tablesArg;
     _options         = globalOptions;
     _connectionIdArg = connectionIdArg;
 }
 public static Task Delete(ManagementClient client, CommandArgument name)
 {
     return(client.DeleteQueueAsync(name.Value));
 }
 internal static CommandConfigurationException RequiredArgumentsCannotHaveDefaultValue(CommandArgument option)
 {
     return(new CommandConfigurationException($"The required argument '{option.Value}' cannot have a default value."));
 }
        public void NoMatchingPropertyWithInferredShouldThrow()
        {
            var args = new[] { "/NoMatch" };

            CommandLine.CommandEnvironment = new TestCommandEnvironment(args);

            var commandArg = new CommandArgument("/NoMatch", 0);
            commandArg.Command = "NoMatch";
            Assert.Equal(
                new CommandLineArgumentInvalidException(typeof(string), commandArg).Message,
                Assert.Throws<CommandLineArgumentInvalidException>(() => CommandLine.Parse<InferredTestArgs>()).Message);
        }
Beispiel #10
0
        public static CommandLineApplication BuildDocSampleCLA()
        {
            // Define the root command configuration
            var cla = new CommandLineApplication(throwOnUnexpectedArg: false);

            // Add various single-value or multi-value options or no-value options (flags)
            CommandOption greeting = cla.Option("-$|-g|--greeting <greeting>",
                                                "The greeting to display.",
                                                CommandOptionType.SingleValue);
            CommandOption uppercase = cla.Option("-u|--uppercase",
                                                 "Display the name in uppercase.",
                                                 CommandOptionType.NoValue);

            // Add some named arguments and/or child commands (here we combine both)
            CommandArgument names = null;

            cla.Command("name", (childCla) =>
            {
                childCla.HelpOption("--help-me");
                names = childCla.Argument(
                    "names",
                    "Enter the names of the people to be greeted.",
                    multipleValues: true);

                // Define a handler for *resolving* the result of parsing the CLI args
                // which usually entails interpretting all the possible values and
                // combinations and invoking some action
                childCla.OnExecute(() =>
                {
                    cla.Out.WriteLine("Executing...");
                    if (greeting.HasValue())
                    {
                        cla.Out.WriteLine("Greetings to the following:");
                        foreach (var n in names.Values)
                        {
                            cla.Out.WriteLine(greeting.Value() + " "
                                              + (uppercase.HasValue() ? n.ToUpper() : n));
                        }
                    }

                    return(0);
                });
            });

            // Enable built-in support for nicely-formatted help
            cla.HelpOption("-?|-h|--help");

            cla.OnExecute(() =>
            {
                cla.Out.WriteLine("Executing...");
                if (greeting.HasValue())
                {
                    cla.Out.WriteLine($"{greeting.Value()} to the {(uppercase.HasValue() ? "WORLD" : "World")}");
                }

                return(0);
            });

            // Apply the configuration to interpret the CLI args
            //cla.Execute(args);

            return(cla);
        }
 // setactivekey btcissuer
 public SetActiveKeyCommand() : base("setactivekey")
 {
     aliasArgument = RegisterArgument(new CommandArgument("alias"));
 }
        public static bool TryPackageOnlyTagHelperResolution(
            CommandArgument assemblyNamesArgument,
            CommandOption protocolOption,
            CommandOption buildBasePathOption,
            CommandOption configurationOption,
            Project project,
            NuGetFramework framework,
            out int exitCode)
        {
            exitCode = 0;

            if (framework.IsDesktop())
            {
                return(false);
            }

            var runtimeIdentifiers = RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers();
            var projectContext     = new ProjectContextBuilder()
                                     .WithProject(project)
                                     .WithTargetFramework(framework)
                                     .WithRuntimeIdentifiers(runtimeIdentifiers)
                                     .Build();
            var configuration = configurationOption.Value() ?? Constants.DefaultConfiguration;

            var projectRuntimeOutputPath = projectContext.GetOutputPaths(configuration, buildBasePathOption.Value())?.RuntimeOutputPath;
            var projectAssemblyName      = project.GetCompilerOptions(framework, configuration).OutputName;
            var projectOutputAssembly    = Path.Combine(projectRuntimeOutputPath, projectAssemblyName + ".dll");

            if (File.Exists(projectOutputAssembly))
            {
                // There's already build output. Dispatch to build output; this ensures dependencies have been resolved.
                return(false);
            }

            var projectLibraries = projectContext.LibraryManager.GetLibraries();
            var libraryLookup    = projectLibraries.ToDictionary(
                library => library.Identity.Name,
                library => library,
                StringComparer.Ordinal);

            foreach (var assemblyName in assemblyNamesArgument.Values)
            {
                if (!IsPackageOnly(assemblyName, libraryLookup))
                {
                    return(false);
                }
            }

            var loadContext = projectContext.CreateLoadContext(
                projectContext.RuntimeIdentifier,
                configuration: "Debug",
                outputPath: null);
            var runner = new PackageOnlyResolveTagHelpersRunCommand(loadContext)
            {
                AssemblyNamesArgument = assemblyNamesArgument,
                ProtocolOption        = protocolOption
            };

            exitCode = runner.OnExecute();

            return(true);
        }
 public string PrettyFormat(CommandArgument command)
 {
     return string.Format("{0}\t\t{1}", command.CommandRegex, command.Description);
 }
Beispiel #14
0
        public static bool Exists(string path, bool isLiteral)
        {
            // need to check if we should resolve wildcards
            var pathArg = new CommandArgument
                              {
                                  Name = (isLiteral) ? "LiteralPath" : "Path",
                                  Value = path
                              };

            // best way to check paths in a static context
            return PipelineHelper.ExecuteScalar<bool>(
                new Command(@"Microsoft.PowerShell.Management\Test-Path"), pathArg);
        }
Beispiel #15
0
 protected abstract int PrivateSend(CommandArgument argument);
Beispiel #16
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication(throwOnUnexpectedArg: false);

            app.Name                   = "dotnet build3";
            app.FullName               = ".NET Builder";
            app.Description            = "Builder for the .NET Platform. Delegates to the MSBuild 'Build' target in the project file.";
            app.AllowArgumentSeparator = true;
            app.HelpOption("-h|--help");

            CommandArgument projectArgument = app.Argument("<PROJECT>",
                                                           "The MSBuild project file to build. If a project file is not specified," +
                                                           " MSBuild searches the current working directory for a file that has a file extension that ends in `proj` and uses that file.");

            CommandOption outputOption        = app.Option("-o|--output <OUTPUT_DIR>", "Directory in which to place outputs", CommandOptionType.SingleValue);
            CommandOption frameworkOption     = app.Option("-f|--framework <FRAMEWORK>", "Compile a specific framework", CommandOptionType.SingleValue);
            CommandOption configurationOption = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue);
            CommandOption versionSuffixOption = app.Option("--version-suffix <VERSION_SUFFIX>", "Defines the value for the $(VersionSuffix) property in the project", CommandOptionType.SingleValue);

            CommandOption noIncrementalOption  = app.Option("--no-incremental", "Set this flag to turn off incremental build", CommandOptionType.NoValue);
            CommandOption noDependenciesOption = app.Option("--no-dependencies", "Set this flag to ignore project to project references and only build the root project", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                List <string> 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 (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");
                }

                msbuildArgs.AddRange(app.RemainingArguments);

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

            return(app.Execute(args));
        }
Beispiel #17
0
        public static int Main(string[] args)
        {
            CommandLineApplication app = new CommandLineApplication();

            CommandOption   includes  = app.Option("-i|--include", "Include items matching the pattern", CommandOptionType.MultipleValue);
            CommandOption   excludes  = app.Option("-x|--exclude", "Exclude items matching the pattern", CommandOptionType.MultipleValue);
            CommandOption   rateLimit = app.Option("-r|--rate-limit", "The minimum number of milliseconds that must pass between processing dirty or include events", CommandOptionType.SingleValue);
            CommandOption   help      = app.Option("-h|--help", "Shows help", CommandOptionType.NoValue);
            CommandArgument run       = app.Argument("run", "The task to run when an included file changes");
            CommandArgument arguments = app.Argument("arguments", "The task to run when an included file changes");

            app.OnExecute(async() =>
            {
                if (help.HasValue())
                {
                    app.ShowHelp();
                    return(0);
                }

                int limit         = int.Parse(rateLimit.Value() ?? "250");
                string currentDir = Directory.GetCurrentDirectory();
                Watcher <GlobbingPattern> watcher = await Watcher <GlobbingPattern> .For(currentDir).ConfigureAwait(false);
                Task currentTask = null;

                using (watcher)
                {
                    foreach (string value in includes.Values)
                    {
                        watcher.AddPattern(EntryKind.Include, new GlobbingPattern(value));
                    }

                    foreach (string value in excludes.Values)
                    {
                        watcher.AddPattern(EntryKind.Exclude, new GlobbingPattern(value));
                    }

                    while (!watcher.Ready.IsCompleted)
                    {
                        await watcher.Ready;
                    }

                    watcher.Dirty += (sender, e) =>
                    {
                        Task t = null;

                        t = Task.Run(async() =>
                        {
                            await Task.Delay(limit);

                            if (currentTask == t)
                            {
                                CommandResult execResult = Command.Create(new CommandSpec(run.Value, arguments.Value, CommandResolutionStrategy.Path)).ForwardStdErr().ForwardStdOut().Execute();
                                if (execResult.ExitCode != 0)
                                {
                                    Console.WriteLine($"{run.Value} {arguments.Value} exited with code {execResult.ExitCode}".Red().Bold());
                                }
                                watcher.Clean();
                            }
                        });

                        currentTask = t;
                    };

                    watcher.FilteredEntriesChanged += (sender, e) =>
                    {
                        Task t = null;

                        t = Task.Run(async() =>
                        {
                            await Task.Delay(limit);

                            if (currentTask == t)
                            {
                                CommandResult execResult = Command.Create(new CommandSpec(run.Value, arguments.Value, CommandResolutionStrategy.Path)).ForwardStdErr().ForwardStdOut().Execute();
                                if (execResult.ExitCode != 0)
                                {
                                    Console.WriteLine($"{run.Value} {arguments.Value} exited with code {execResult.ExitCode}".Red().Bold());
                                }
                                watcher.Clean();
                            }
                        });

                        currentTask = t;
                    };

                    Console.WriteLine($"Now watching for changes in {currentDir}");
                    Console.WriteLine("Press [Enter] to stop...");
                    Console.ReadLine();
                }
                return(0);
            });

            int result;

            try
            {
                result = app.Execute(args);
            }
            catch (Exception ex)
            {
                AggregateException ax = ex as AggregateException;

                while (ax != null && ax.InnerExceptions.Count == 1)
                {
                    ex = ax.InnerException;
                    ax = ex as AggregateException;
                }

                Reporter.Error.WriteLine(ex.Message.Bold().Red());

                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    ax = ex as AggregateException;

                    while (ax != null && ax.InnerExceptions.Count == 1)
                    {
                        ex = ax.InnerException;
                        ax = ex as AggregateException;
                    }

                    Reporter.Error.WriteLine(ex.Message.Bold().Red());
                }

                Reporter.Error.WriteLine(ex.StackTrace.Bold().Red());
                result = 1;
            }

            return(result);
        }
Beispiel #18
0
 void cntFrm_CommandClick(object sender, CommandArgument e)
 {
     updateCodeEditors(((Template)cntFrm.Content).Filepath);
 }
Beispiel #19
0
        public static int Run(string[] args)
        {
            // IMPORTANT:
            // When updating the command line args for dotnet-migrate, we need to update the in-VS caller of dotnet migrate as well.
            // It is located at dotnet/roslyn-project-system:
            //     src/Microsoft.VisualStudio.ProjectSystem.CSharp.VS/ProjectSystem/VS/Xproj/MigrateXprojFactory.cs

            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication();

            app.Name                = "dotnet migrate";
            app.FullName            = LocalizableStrings.AppFullName;
            app.Description         = LocalizableStrings.AppDescription;
            app.HandleResponseFiles = true;
            app.HelpOption("-h|--help");

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

            CommandOption template = app.Option(
                "-t|--template-file",
                LocalizableStrings.CmdTemplateDescription,
                CommandOptionType.SingleValue);
            CommandOption sdkVersion = app.Option(
                "-v|--sdk-package-version",
                LocalizableStrings.CmdVersionDescription,
                CommandOptionType.SingleValue);
            CommandOption xprojFile = app.Option(
                "-x|--xproj-file",
                LocalizableStrings.CmdXprojFileDescription,
                CommandOptionType.SingleValue);
            CommandOption skipProjectReferences = app.Option(
                "-s|--skip-project-references",
                LocalizableStrings.CmdSkipProjectReferencesDescription,
                CommandOptionType.BoolValue);

            CommandOption reportFile = app.Option(
                "-r|--report-file",
                LocalizableStrings.CmdReportFileDescription,
                CommandOptionType.SingleValue);
            CommandOption structuredReportOutput = app.Option(
                "--format-report-file-json",
                LocalizableStrings.CmdReportOutputDescription,
                CommandOptionType.BoolValue);
            CommandOption skipBackup = app.Option("--skip-backup",
                                                  LocalizableStrings.CmdSkipBackupDescription,
                                                  CommandOptionType.BoolValue);

            app.OnExecute(() =>
            {
                MigrateCommand migrateCommand = new MigrateCommand(
                    template.Value(),
                    projectArgument.Value,
                    sdkVersion.Value(),
                    xprojFile.Value(),
                    reportFile.Value(),
                    skipProjectReferences.BoolValue.HasValue ? skipProjectReferences.BoolValue.Value : false,
                    structuredReportOutput.BoolValue.HasValue ? structuredReportOutput.BoolValue.Value : false,
                    skipBackup.BoolValue.HasValue ? skipBackup.BoolValue.Value : false);

                return(migrateCommand.Execute());
            });

            try
            {
                return(app.Execute(args));
            }
            catch (GracefulException e)
            {
                Reporter.Error.WriteLine(e.Message);
                Reporter.Error.WriteLine(LocalizableStrings.MigrationFailedError);
                return(1);
            }
            catch (Exception)
            {
                Reporter.Error.WriteLine(LocalizableStrings.MigrationFailedError);
                throw;
            }
        }
		public CollectGameModule()
		{
         AddOptions(new Dictionary<string, object> {
            { "rankup", 50 },
            { "exchange", 500 },
            { "maxWithdraw", 100 },
            { "maxLovers", 20 },
            { "journalStyle", "style=\"font-family:'Courier New', Courier, monospace; line-height: 100%;\"" },
            { "jealousyHours", 24 },
            { "jealousyCoins", 1000 },
            { "hugSayings", "How nice!, You smile a bit!, You wonder why., How eccentric!, How lovely!, " +
               "You're pretty happy about it!, Your HP was restored by 10 points!, You became confused!, " +
               "Your defense fell!, Your spirits rose!, Maybe the world isn't so bad after all., " +
               "You cry a little., You cry a little inside., You burst into tears on their shoulder!, " +
               "You're a little uncomfortable., You want to return the favor., Your stress ebbs away., " +
               "You feel like you understand each other a bit better!, You feel warm inside., " + 
               "*doki doki desu!*, This isn't so bad., You get a little nostalgic., " +
               "You want another one!, You value their friendship a bit more!, You're overcome with a tidal wave of emotions!, " +
               "You wish more people were like this!, The world isn't such a dark place anymore., " +
               "You feel a bit better!" }
         });

         GeneralHelp = "In cgame, you collect items by using your hourly coins to draw random items. " +
         "Your goal is to collect all 100 items, which allows you to rank up and move through the leaderboards. " +
         "You can also trade items with other people, or simply be a nice person and give out free items.";

         CommandArgument price = new CommandArgument("price", ArgumentType.Integer);
         CommandArgument count = new CommandArgument("count", ArgumentType.Integer);
         CommandArgument multiplier = new CommandArgument("multiplier", ArgumentType.Custom, RepeatType.One, @"[xX]?[0-9]+");
         CommandArgument item = new CommandArgument("item", ArgumentType.Custom, RepeatType.One, @"[a-zA-Z][0-9]");
         CommandArgument itemList = new CommandArgument("itemList", ArgumentType.Custom, RepeatType.One, @"(?:[a-zA-Z][0-9]\s*)+");
         CommandArgument player = new CommandArgument("player", ArgumentType.User);

         Commands.AddRange(new List<ModuleCommand> {
            new ModuleCommand("cgamedraw", new List<CommandArgument> {
               count
            }, "Get item(s) (Max: " + MaxWithdraw + ")"),
            new ModuleCommand("cgamedraw", new List<CommandArgument> {
               count,
               multiplier
            }, "Get item(s) with increased luck (Max multiplier: " + CollectionManager.MaxMultiplier + ")"),
            new ModuleCommand("cgamechance", new List<CommandArgument> {
               multiplier
            }, "Chance of new item with given multiplier"),
            new ModuleCommand("cgamerestock", new List<CommandArgument>(), "Get your cgame coins for the hour"),
            new ModuleCommand("cgamestock", new List<CommandArgument>(), "See your current collection"),
            new ModuleCommand("cgamestockm", new List<CommandArgument>(), "Mobile friendly cgamestock"),
            new ModuleCommand("cgametopitems", new List<CommandArgument>(), "Top items by number"),
            new ModuleCommand("cgameamount", new List<CommandArgument> {
               item
            }, "Show amount of item"),
            new ModuleCommand("cgamecompare", new List<CommandArgument> {
               player
            }, "Compare your inventory against another's for possible trades."),
            new ModuleCommand("cgamequery", new List<CommandArgument> {
               itemList
            }, "See who has the given items"),
            new ModuleCommand("cgamequeryall", new List<CommandArgument>(), "See who has any item you need"),
            new ModuleCommand("cgamesell", new List<CommandArgument> {
               itemList,
               player,
               price
            }, "Sell item(s) to player for price."),
            new ModuleCommand("cgamebuy", new List<CommandArgument> {
               itemList,
               player,
               price
            }, "Buy item(s) from player for price."),
            new ModuleCommand("cgameshopsell", new List<CommandArgument> {
               itemList
            }, "Sell item(s) to shop (low trade price). All of the item is sold."),
            new ModuleCommand("cgameshopsellall", new List<CommandArgument>(), "Sell all items to shop (low trade price)"),
            new ModuleCommand("cgamegive", new List<CommandArgument> {
               itemList,
               player
            }, "Give item(s) to player (how nice!).", true),
            new ModuleCommand("cgametrade", new List<CommandArgument> {
               itemList,
               player,
               itemList
            }, "Trade your item(s) for player's item(s)"),
            new ModuleCommand("cgamequicktrade", new List<CommandArgument> {
               player
            }, "Automatic maximum even trade with player"),
            new ModuleCommand("cgamelove", new List<CommandArgument> {
               player
            }, "Give all items you can to player"),
            new ModuleCommand("cgameaddlove", new List<CommandArgument> {
               player
            }, "Add a player to your love list"),
            new ModuleCommand("cgameremovelove", new List<CommandArgument> {
               player
            }, "Remove a player from your love list"),
            new ModuleCommand("cgameloveall", new List<CommandArgument>(), "Love everyone on your list"),
            new ModuleCommand("cgamelovelist", new List<CommandArgument>(), "Players on your love list"),
            new ModuleCommand("cgamejealousy", new List<CommandArgument>(), "Take items from other players (careful!)"),
            new ModuleCommand("cgamecheckjealousy", new List<CommandArgument>(), "Check what you'll get from jealousy"),
            new ModuleCommand("cgamehug", new List<CommandArgument> {
               player
            }, "Give a hug to reduce jealousy", true),
            new ModuleCommand("cgameaccept", new List<CommandArgument>(), "Accept trade/sell/buy offer"),
            new ModuleCommand("cgamedecline", new List<CommandArgument>(), "Decline trade/sell/buy offer"),
            new ModuleCommand("cgamerankup", new List<CommandArgument>(), "Reset journal and go to next rank"),
            new ModuleCommand("cgametop", new List<CommandArgument>(), "See top players"),
            new ModuleCommand("cgameclose", new List<CommandArgument>(), "See your competitors"),
            new ModuleCommand("cgamestats", new List<CommandArgument>(), "See your lifetime stats (ranked only)")
         });

			chanceSimulator.DoWork += new DoWorkEventHandler(chanceSimulator_DoWork);
			chanceSimulator.RunWorkerCompleted += new RunWorkerCompletedEventHandler(chanceSimulator_RunWorkerCompleted);
		}
Beispiel #21
0
 ValidationResult IArgumentValidator.GetValidationResult(CommandArgument argument, ValidationContext context)
 => _validator(context);
Beispiel #22
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication();

            app.Name                = "dotnet compile-fsc";
            app.FullName            = ".NET F# Compiler";
            app.Description         = "F# Compiler for the .NET Platform";
            app.HandleResponseFiles = true;
            app.HelpOption("-h|--help");

            CommonCompilerOptionsCommandLine commonCompilerCommandLine = CommonCompilerOptionsCommandLine.AddOptions(app);
            AssemblyInfoOptionsCommandLine   assemblyInfoCommandLine   = AssemblyInfoOptionsCommandLine.AddOptions(app);

            CommandOption   tempOutputOption = app.Option("--temp-output <arg>", "Compilation temporary directory", CommandOptionType.SingleValue);
            CommandOption   outputNameOption = app.Option("--out <arg>", "Name of the output assembly", CommandOptionType.SingleValue);
            CommandOption   referencesOption = app.Option("--reference <arg>...", "Path to a compiler metadata reference", CommandOptionType.MultipleValue);
            CommandOption   resourcesOption  = app.Option("--resource <arg>...", "Resources to embed", CommandOptionType.MultipleValue);
            CommandArgument sourcesArgument  = app.Argument("<source-files>...", "Compilation sources", multipleValues: true);

            app.OnExecute(() =>
            {
                if (!tempOutputOption.HasValue())
                {
                    Reporter.Error.WriteLine("Option '--temp-output' is required");
                    return(ExitFailed);
                }

                CommonCompilerOptions commonOptions = commonCompilerCommandLine.GetOptionValues();

                AssemblyInfoOptions assemblyInfoOptions = assemblyInfoCommandLine.GetOptionValues();

                // TODO less hacky
                bool targetNetCore =
                    commonOptions.Defines.Contains("DNXCORE50") ||
                    commonOptions.Defines.Where(d => d.StartsWith("NETSTANDARDAPP1_")).Any() ||
                    commonOptions.Defines.Where(d => d.StartsWith("NETCOREAPP1_")).Any() ||
                    commonOptions.Defines.Where(d => d.StartsWith("NETSTANDARD1_")).Any();

                // Get FSC Path upfront to use it for win32manifest path
                string tempOutDir  = tempOutputOption.Value();
                var fscCommandSpec = ResolveFsc(null, tempOutDir);
                var fscExeFile     = fscCommandSpec.FscExeFile;
                var fscExeDir      = fscCommandSpec.FscExeDir;

                // FSC arguments
                var allArgs = new List <string>();

                //HACK fsc raise error FS0208 if target exe doesnt have extension .exe
                bool hackFS0208 = targetNetCore && commonOptions.EmitEntryPoint == true;

                string outputName      = outputNameOption.Value();
                var originalOutputName = outputName;

                if (outputName != null)
                {
                    if (hackFS0208)
                    {
                        outputName = Path.ChangeExtension(outputName, ".exe");
                    }

                    allArgs.Add($"--out:{outputName}");
                }

                //let's pass debugging type only if options.DebugType is specified, until
                //portablepdb are confirmed to work.
                //so it's possibile to test portable pdb without breaking existing build
                if (string.IsNullOrEmpty(commonOptions.DebugType))
                {
                    //debug info (only windows pdb supported, not portablepdb)
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        allArgs.Add("--debug");
                        //TODO check if full or pdbonly
                        allArgs.Add("--debug:pdbonly");
                    }
                    else
                    {
                        allArgs.Add("--debug-");
                    }
                }
                else
                {
                    allArgs.Add("--debug");
                    allArgs.Add($"--debug:{commonOptions.DebugType}");
                }

                // Default options
                allArgs.Add("--noframework");
                allArgs.Add("--nologo");
                allArgs.Add("--simpleresolution");
                allArgs.Add("--nocopyfsharpcore");

                // project.json compilationOptions
                if (commonOptions.Defines != null)
                {
                    allArgs.AddRange(commonOptions.Defines.Select(def => $"--define:{def}"));
                }

                if (commonOptions.GenerateXmlDocumentation == true)
                {
                    allArgs.Add($"--doc:{Path.ChangeExtension(outputName, "xml")}");
                }

                if (commonOptions.KeyFile != null)
                {
                    allArgs.Add($"--keyfile:{commonOptions.KeyFile}");
                }

                if (commonOptions.Optimize == true)
                {
                    allArgs.Add("--optimize+");
                }

                //--resource doesnt expect "
                //bad: --resource:"path/to/file",name
                //ok:  --resource:path/to/file,name
                allArgs.AddRange(resourcesOption.Values.Select(resource => $"--resource:{resource.Replace("\"", "")}"));

                allArgs.AddRange(referencesOption.Values.Select(r => $"-r:{r}"));

                if (commonOptions.EmitEntryPoint != true)
                {
                    allArgs.Add("--target:library");
                }
                else
                {
                    allArgs.Add("--target:exe");

                    //HACK we need default.win32manifest for exe
                    var win32manifestPath = Path.Combine(fscExeDir, "..", "..", "runtimes", "any", "native", "default.win32manifest");
                    allArgs.Add($"--win32manifest:{win32manifestPath}");
                }

                if (commonOptions.SuppressWarnings != null && commonOptions.SuppressWarnings.Any())
                {
                    allArgs.Add("--nowarn:" + string.Join(",", commonOptions.SuppressWarnings.ToArray()));
                }

                if (commonOptions.LanguageVersion != null)
                {
                    // Not used in fsc
                }

                if (commonOptions.Platform != null)
                {
                    allArgs.Add($"--platform:{commonOptions.Platform}");
                }

                if (commonOptions.AllowUnsafe == true)
                {
                }

                if (commonOptions.WarningsAsErrors == true)
                {
                    allArgs.Add("--warnaserror");
                }

                //set target framework
                if (targetNetCore)
                {
                    allArgs.Add("--targetprofile:netcore");
                }

                if (commonOptions.DelaySign == true)
                {
                    allArgs.Add("--delaysign+");
                }

                if (commonOptions.PublicSign == true)
                {
                }

                if (commonOptions.AdditionalArguments != null)
                {
                    // Additional arguments are added verbatim
                    allArgs.AddRange(commonOptions.AdditionalArguments);
                }

                // Generate assembly info
                var assemblyInfo = Path.Combine(tempOutDir, $"dotnet-compile.assemblyinfo.fs");
                File.WriteAllText(assemblyInfo, AssemblyInfoFileGenerator.GenerateFSharp(assemblyInfoOptions));

                //source files + assemblyInfo
                allArgs.AddRange(GetSourceFiles(sourcesArgument.Values, assemblyInfo).ToArray());

                //TODO check the switch enabled in fsproj in RELEASE and DEBUG configuration

                var rsp = Path.Combine(tempOutDir, "dotnet-compile-fsc.rsp");
                File.WriteAllLines(rsp, allArgs, Encoding.UTF8);

                // Execute FSC!
                var result = RunFsc(new List <string> {
                    $"@{rsp}"
                }, tempOutDir)
                             .ForwardStdErr()
                             .ForwardStdOut()
                             .Execute();

                bool successFsc = result.ExitCode == 0;

                if (hackFS0208 && File.Exists(outputName))
                {
                    if (File.Exists(originalOutputName))
                    {
                        File.Delete(originalOutputName);
                    }
                    File.Move(outputName, originalOutputName);
                }

                //HACK dotnet build require a pdb (crash without), fsc atm cant generate a portable pdb, so an empty pdb is created
                string pdbPath = Path.ChangeExtension(outputName, ".pdb");
                if (successFsc && !File.Exists(pdbPath))
                {
                    File.WriteAllBytes(pdbPath, Array.Empty <byte>());
                }

                return(result.ExitCode);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
#if DEBUG
                Reporter.Error.WriteLine(ex.ToString());
#else
                Reporter.Error.WriteLine(ex.Message);
#endif
                return(ExitFailed);
            }
        }
Beispiel #23
0
        public static CleanCommand FromArgs(string[] args, string msbuildPath = null)
        {
            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 = AddVerbosityOption(app);

            List <string> msbuildArgs = null;

            app.OnExecute(() =>
            {
                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(0);
            });

            int exitCode = app.Execute(args);

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

            return(new CleanCommand(msbuildArgs, msbuildPath));
        }
Beispiel #24
0
 public static Task Delete(ServiceBusAdministrationClient client, CommandArgument name)
 {
     return(client.DeleteQueueAsync(name.Value));
 }
Beispiel #25
0
 public SignHashCommand() : base("signhash")
 {
     privatekeyArgument = RegisterArgument(new CommandArgument("private key"));
     hashArgument       = RegisterArgument(new CommandArgument("hash"));
 }
        static void Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.Name = "xmldoc2md";

            app.VersionOption("-v|--version", () =>
            {
                return(string.Format(
                           "Version {0}",
                           Assembly.GetEntryAssembly()
                           .GetCustomAttribute <AssemblyInformationalVersionAttribute>()
                           .InformationalVersion
                           .ToString()));
            });
            app.HelpOption("-?|-h|--help");

            CommandArgument srcArg = app.Argument("src", "DLL source path");
            CommandArgument outArg = app.Argument("out", "Output directory");

            CommandOption namespaceMatchOption = app.Option(
                "--namespace-match <regex>",
                "Regex pattern to select namespaces",
                CommandOptionType.SingleValue);

            CommandOption indexPageNameOption = app.Option(
                "--index-page-name <regex>",
                "Name of the index page (default: \"index\")",
                CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                string src            = srcArg.Value;
                string @out           = outArg.Value;
                string namespaceMatch = namespaceMatchOption.Value();
                string indexPageName  = indexPageNameOption.HasValue() ? indexPageNameOption.Value() : "index";

                var xmlDocumentation = new XmlDocumentation(src, namespaceMatch);

                if (!Directory.Exists(@out))
                {
                    Directory.CreateDirectory(@out);
                }

                var indexBuilder = new MarkdownBuilder();
                indexBuilder.Header(1, xmlDocumentation.AssemblyName);

                foreach (var g in xmlDocumentation.Types.GroupBy(x => x.Namespace).OrderBy(x => x.Key))
                {
                    string subDir = Path.Combine(@out, g.Key);
                    if (!Directory.Exists(subDir))
                    {
                        Directory.CreateDirectory(subDir);
                    }

                    indexBuilder.AppendLine();
                    indexBuilder.HeaderWithCode(2, g.Key);
                    indexBuilder.AppendLine();
                    foreach (var item in g.OrderBy(x => x.Name))
                    {
                        string typeName = item.BeautifyName.Replace("<", "{").Replace(">", "}").Replace(",", "").Replace(" ", "-");
                        var sb          = new StringBuilder();

                        indexBuilder.ListLink(MarkdownBuilder.MarkdownCodeQuote(item.BeautifyName), g.Key + "/" + typeName);

                        sb.Append(item.ToString());

                        File.WriteAllText(Path.Combine(@out, g.Key, $"{typeName}.md"), sb.ToString());
                    }
                }

                File.WriteAllText(Path.Combine(@out, $"{indexPageName}.md"), indexBuilder.ToString());

                return(0);
            });

            try
            {
                app.Execute(args);
            }
            catch (CommandParsingException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to execute application: {0}", ex.Message);
            }
        }
 // getaccount qyl68tygnjx6qqwrsmynmejmc9wxlw7almv3397j
 public GetAccountCommand() : base("getaccount")
 {
     addressArgument = RegisterArgument(new CommandArgument("address"));
 }
Beispiel #28
0
        public static int Run(string[] args)
        {
            // IMPORTANT:
            // When updating the command line args for dotnet-migrate, we need to update the in-VS caller of dotnet migrate as well.
            // It is located at dotnet/roslyn-project-system:
            //     src/Microsoft.VisualStudio.ProjectSystem.CSharp.VS/ProjectSystem/VS/Xproj/MigrateXprojFactory.cs

            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication();

            app.Name                = "dotnet migrate";
            app.FullName            = ".NET Migrate Command";
            app.Description         = "Command used to migrate project.json projects to msbuild";
            app.HandleResponseFiles = true;
            app.HelpOption("-h|--help");

            CommandArgument projectArgument = app.Argument("<PROJECT_JSON/GLOBAL_JSON/PROJECT_DIR>",
                                                           string.Join(Environment.NewLine,
                                                                       "The path to ",
                                                                       " - a project.json file to migrate.",
                                                                       "or",
                                                                       " - a global.json file, it will migrate the folders specified in global.json.",
                                                                       "or",
                                                                       " - a directory to migrate, it will recursively search for project.json files to migrate.",
                                                                       "Defaults to current directory if nothing is specified."));

            CommandOption template              = app.Option("-t|--template-file", "Base MSBuild template to use for migrated app. The default is the project included in dotnet new", CommandOptionType.SingleValue);
            CommandOption sdkVersion            = app.Option("-v|--sdk-package-version", "The version of the sdk package that will be referenced in the migrated app. The default is the version of the sdk in dotnet new", CommandOptionType.SingleValue);
            CommandOption xprojFile             = app.Option("-x|--xproj-file", "The path to the xproj file to use. Required when there is more than one xproj in a project directory.", CommandOptionType.SingleValue);
            CommandOption skipProjectReferences = app.Option("-s|--skip-project-references", "Skip migrating project references. By default project references are migrated recursively", CommandOptionType.BoolValue);

            CommandOption reportFile             = app.Option("-r|--report-file", "Output migration report to a file in addition to the console.", CommandOptionType.SingleValue);
            CommandOption structuredReportOutput = app.Option("--format-report-file-json", "Output migration report file as json rather than user messages", CommandOptionType.BoolValue);

            app.OnExecute(() =>
            {
                MigrateCommand migrateCommand = new MigrateCommand(
                    template.Value(),
                    projectArgument.Value,
                    sdkVersion.Value(),
                    xprojFile.Value(),
                    reportFile.Value(),
                    skipProjectReferences.BoolValue.HasValue ? skipProjectReferences.BoolValue.Value : false,
                    structuredReportOutput.BoolValue.HasValue ? structuredReportOutput.BoolValue.Value : false);

                return(migrateCommand.Execute());
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
#if DEBUG
                Reporter.Error.WriteLine(ex.ToString());
#else
                Reporter.Error.WriteLine(ex.Message);
#endif
                Reporter.Error.WriteLine("Migration failed.");
                return(1);
            }
        }
 /// <summary>
 /// Gets the validation result for a command line argument.
 /// </summary>
 /// <param name="argument"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public ValidationResult?GetValidationResult(CommandArgument argument, ValidationContext context)
 => GetValidationResult(argument.Values, context);
Beispiel #30
0
 protected override int PrivateSend(CommandArgument commandArgument)
 {
     throw new NotImplementedException();
 }
Beispiel #31
0
        public static int Main(string[] args)
        {
            try
            {
                Logger.SystemLogger = LogUtils.GetLogger(Console.Error);
                Console.Error.WriteLine("CANAPE.Cli (c) 2017 James Forshaw, 2014 Context Information Security.");
                CommandLineApplication app = new CommandLineApplication(false);

                CommandArgument script  = app.Argument("script", "Specify a script file to run.");
                CommandOption   compile = app.Option(
                    "-c | --compile", "Compile script file only.",
                    CommandOptionType.NoValue);
                CommandOption verbose = app.Option(
                    "-v | --verbose", "Enable verbose logging output.",
                    CommandOptionType.NoValue);
                CommandOption include = app.Option(
                    "-i | --include", "Specify additional include directories to be accessed via the #load directive.",
                    CommandOptionType.MultipleValue);
                CommandOption libs = app.Option(
                    "-l | --libs", "Specify additional library directories to be accessed via the #r directive.",
                    CommandOptionType.MultipleValue);
                CommandOption color = app.Option(
                    "--color", "Enable ANSI 24 bit color output (if supported).",
                    CommandOptionType.NoValue);
                app.ShowInHelpText = true;
                app.HelpOption("-? | -h | --help");
                app.OnExecute(() =>
                {
                    IEnumerable <string> include_dirs  = include.HasValue() ? include.Values.Select(p => Path.GetFullPath(p)) : new string[0];
                    IEnumerable <string> metadata_dirs = libs.HasValue() ? libs.Values.Select(p => Path.GetFullPath(p)) : new string[0];

                    ConsoleUtils.EnableColor = color.HasValue();
                    if (verbose.HasValue())
                    {
                        Logger.SystemLogger.LogLevel = Logger.LogEntryType.All;
                    }
                    if (script.Value == null)
                    {
                        RunConsole(include_dirs, metadata_dirs).Wait();
                    }
                    else
                    {
                        string filename = Path.GetFullPath(script.Value);
                        if (compile.HasValue())
                        {
                            if (CompileScript(filename, include_dirs, metadata_dirs) != null)
                            {
                                Console.Error.WriteLine("SUCCESS: Script compiled with no errors");
                            }
                        }
                        else
                        {
                            RunScript(filename, include_dirs, metadata_dirs, app.RemainingArguments).Wait();
                        }
                    }

                    return(0);
                });
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
                PrintException(ex, false);
                return(1);
            }
        }
        private static bool Match(PropertyInfo property, CommandArgument argument)
        {
            var propertyName = PascalCase(argument.Name);

            return(string.Equals(property.Name, propertyName, StringComparison.Ordinal));
        }
Beispiel #33
0
        public static int Main(string[] args)
        {
            CommandLineApplication app = new CommandLineApplication(false)
            {
                Name     = "dotnet new3",
                FullName = "Template Instantiation Commands for .NET Core CLI."
            };

            CommandArgument template        = app.Argument("template", "The template to instantiate.");
            CommandOption   listOnly        = app.Option("-l|--list", "Lists templates with containing the specified name.", CommandOptionType.NoValue);
            CommandOption   name            = app.Option("-n|--name", "The name for the output. If no name is specified, the name of the current directory is used.", CommandOptionType.SingleValue);
            CommandOption   dir             = app.Option("-d|--dir", "Indicates whether to display create a directory for the generated content.", CommandOptionType.NoValue);
            CommandOption   alias           = app.Option("-a|--alias", "Creates an alias for the specified template", CommandOptionType.SingleValue);
            CommandOption   parametersFiles = app.Option("-x|--extra-args", "Adds a parameters file.", CommandOptionType.MultipleValue);
            CommandOption   install         = app.Option("-i|--install", "Installs a source or a template pack.", CommandOptionType.MultipleValue);
            CommandOption   help            = app.Option("-h|--help", "Indicates whether to display the help for the template's parameters instead of creating it.", CommandOptionType.NoValue);

            CommandOption quiet           = app.Option("--quiet", "Doesn't output any status information.", CommandOptionType.NoValue);
            CommandOption skipUpdateCheck = app.Option("--skip-update-check", "Don't check for updates.", CommandOptionType.NoValue);
            CommandOption update          = app.Option("--update", "Update matching templates.", CommandOptionType.NoValue);

            app.OnExecute(async() =>
            {
                bool reinitFlag = app.RemainingArguments.Any(x => x == "--debug:reinit");

                if (reinitFlag)
                {
                    Paths.User.FirstRunCookie.Delete();
                }

                if (reinitFlag || app.RemainingArguments.Any(x => x == "--debug:reset-config"))
                {
                    Paths.User.AliasesFile.Delete();
                    Paths.User.SettingsFile.Delete();
                    Paths.User.TemplateCacheFile.Delete();
                    return(0);
                }

                if (!Paths.User.BaseDir.Exists() || !Paths.User.FirstRunCookie.Exists())
                {
                    if (!quiet.HasValue())
                    {
                        Reporter.Output.WriteLine("Getting things ready for first use...");
                    }

                    ConfigureEnvironment();
                    Paths.User.FirstRunCookie.WriteAllText("");
                }

                if (app.RemainingArguments.Any(x => x == "--debug:showconfig"))
                {
                    ShowConfig();
                    return(0);
                }

                if (install.HasValue())
                {
                    InstallPackage(install.Values, quiet.HasValue());
                    return(0);
                }

                if (update.HasValue())
                {
                    //return PerformUpdateAsync(template.Value, quiet.HasValue(), source);
                }

                if (listOnly.HasValue())
                {
                    ListTemplates(template);
                    return(0);
                }

                IReadOnlyDictionary <string, string> parameters;

                try
                {
                    parameters = app.ParseExtraArgs(parametersFiles);
                }
                catch (Exception ex)
                {
                    Reporter.Error.WriteLine(ex.Message.Red().Bold());
                    app.ShowHelp();
                    return(-1);
                }

                if (string.IsNullOrWhiteSpace(template.Value) && help.HasValue())
                {
                    app.ShowHelp();
                    return(0);
                }

                string aliasName         = alias.HasValue() ? alias.Value() : null;
                ITemplateEngineHost host = new DotNetNew3TemplateEngineHost();

                string fallbackName = new DirectoryInfo(Directory.GetCurrentDirectory()).Name;

                if (await TemplateCreator.Instantiate(host, template.Value ?? "", name.Value(), fallbackName, dir.HasValue(), aliasName, parameters, skipUpdateCheck.HasValue()) == -1)
                {
                    ListTemplates(template);
                    return(-1);
                }

                return(0);
            });

            int result;

            try
            {
                using (Timing.Over("Execute"))
                {
                    result = app.Execute(args);
                }
            }
            catch (Exception ex)
            {
                AggregateException ax = ex as AggregateException;

                while (ax != null && ax.InnerExceptions.Count == 1)
                {
                    ex = ax.InnerException;
                    ax = ex as AggregateException;
                }

                Reporter.Error.WriteLine(ex.Message.Bold().Red());

                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    ax = ex as AggregateException;

                    while (ax != null && ax.InnerExceptions.Count == 1)
                    {
                        ex = ax.InnerException;
                        ax = ex as AggregateException;
                    }

                    Reporter.Error.WriteLine(ex.Message.Bold().Red());
                }

                Reporter.Error.WriteLine(ex.StackTrace.Bold().Red());
                result = 1;
            }

            return(result);
        }
Beispiel #34
0
        private static int Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name                 = "GenAPI",
                FullName             = "A command line tool to generate code for the API surface of an assembly.",
                ResponseFileHandling = ResponseFileHandling.ParseArgsAsSpaceSeparated
            };

            app.HelpOption("-?|-h|--help");
            app.VersionOption("-v|--version", GetAssemblyVersion());

            CommandArgument assemblyArg = app.Argument("assembly", "Path for an specific assembly or a directory to get all assemblies.");

            assemblyArg.IsRequired();
            CommandOption libPath     = app.Option("-l|--lib-path", "Delimited (',' or ';') set of paths to use for resolving assembly references", CommandOptionType.SingleValue);
            CommandOption apiList     = app.Option("-a|--api-list", "Specify a api list in the DocId format of which APIs to include.", CommandOptionType.SingleValue);
            CommandOption outFilePath = app.Option("-o|--out", "Output path. Default is the console. Can specify an existing directory as well and then a file will be created for each assembly with the matching name of the assembly.", CommandOptionType.SingleValue);
            CommandOption headerFile  = app.Option("-h|--header-file", "Specify a file with header content to prepend to output.", CommandOptionType.SingleValue);
            CommandOption <WriterType>       writerType       = app.Option <WriterType>("-w|--writer", "Specify the writer type to use. Legal values: CSDecl, DocIds, TypeForwards, TypeList. Default is CSDecl.", CommandOptionType.SingleValue);
            CommandOption <SyntaxWriterType> syntaxWriterType = app.Option <SyntaxWriterType>("-s|--syntax", "Specific the syntax writer type. Only used if the writer is CSDecl. Legal values: Text, Html, Xml. Default is Text.", CommandOptionType.SingleValue);
            CommandOption <DocIdKinds>       docIdKinds       = app.Option <DocIdKinds>("-d|--doc-id-kinds", "Only include API of the specified kinds. Legal values: A, Assembly, Namespace, N, T, Type, Field, F, P, Property, Method, M, Event, E, All. Default is All.", CommandOptionType.SingleValue);
            CommandOption exceptionMessage      = app.Option("-t|--throw", "Method bodies should throw PlatformNotSupportedException.", CommandOptionType.SingleValue);
            CommandOption globalPrefix          = app.Option("-g|--global", "Include global prefix for compilation.", CommandOptionType.NoValue);
            CommandOption excludeApiList        = app.Option("--exclude-api-list", "Specify a api list in the DocId format of which APIs to exclude.", CommandOptionType.SingleValue);
            CommandOption excludeAttributesList = app.Option("--exclude-attributes-list", "Specify a list in the DocId format of which attributes should be excluded from being applied on apis.", CommandOptionType.SingleValue);
            CommandOption apiOnly                    = app.Option("--api-only", "[CSDecl] Include only API's not CS code that compiles.", CommandOptionType.NoValue);
            CommandOption all                        = app.Option("--all", "Include all API's not just public APIs. Default is public only.", CommandOptionType.NoValue);
            CommandOption memberHeadings             = app.Option("--member-headings", "[CSDecl] Include member headings for each type of member.", CommandOptionType.NoValue);
            CommandOption hightlightBaseMembers      = app.Option("--hightlight-base-members", "[CSDecl] Highlight overridden base members.", CommandOptionType.NoValue);
            CommandOption hightlightInterfaceMembers = app.Option("--hightlight-interface-members", "[CSDecl] Highlight interface implementation members.", CommandOptionType.NoValue);
            CommandOption alwaysIncludeBase          = app.Option("--always-include-base", "[CSDecl] Include base types, interfaces, and attributes, even when those types are filtered.", CommandOptionType.NoValue);
            CommandOption excludeMembers             = app.Option("--exclude-members", "Exclude members when return value or parameter types are excluded.", CommandOptionType.NoValue);
            CommandOption langVersion                = app.Option("--lang-version", "Language Version to target", CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                HostEnvironment host  = new HostEnvironment();
                host.UnableToResolve += (sender, e) =>
                                        Console.WriteLine("Unable to resolve assembly '{0}' referenced by '{1}'.", e.Unresolved.ToString(), e.Referrer.ToString());;

                host.UnifyToLibPath = true;
                if (!string.IsNullOrWhiteSpace(libPath.Value()))
                {
                    host.AddLibPaths(HostEnvironment.SplitPaths(libPath.Value()));
                }

                IEnumerable <IAssembly> assemblies = host.LoadAssemblies(HostEnvironment.SplitPaths(assemblyArg.Value));

                if (!assemblies.Any())
                {
                    Console.WriteLine("ERROR: Failed to load any assemblies from '{0}'", assemblyArg.Value);
                    return(1);
                }

                string headerText    = GetHeaderText(headerFile.Value());
                bool loopPerAssembly = Directory.Exists(outFilePath.Value());

                if (loopPerAssembly)
                {
                    foreach (var assembly in assemblies)
                    {
                        using (TextWriter output = GetOutput(GetFilename(assembly, writerType.ParsedValue, syntaxWriterType.ParsedValue)))
                            using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output, writerType.ParsedValue, syntaxWriterType.ParsedValue))
                            {
                                if (headerText != null)
                                {
                                    output.Write(headerText);
                                }
                                ICciWriter writer = GetWriter(output, syntaxWriter);
                                writer.WriteAssemblies(new IAssembly[] { assembly });
                            }
                    }
                }
                else
                {
                    using (TextWriter output = GetOutput(outFilePath.Value()))
                        using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output, writerType.ParsedValue, syntaxWriterType.ParsedValue))
                        {
                            if (headerText != null)
                            {
                                output.Write(headerText);
                            }
                            ICciWriter writer = GetWriter(output, syntaxWriter);
                            writer.WriteAssemblies(assemblies);
                        }
                }

                return(0);
            });

            ICciWriter GetWriter(TextWriter output, ISyntaxWriter syntaxWriter)
            {
                ICciFilter filter = GetFilter(apiList.Value(), all.HasValue(), apiOnly.HasValue(),
                                              excludeApiList.Value(), excludeMembers.HasValue(), excludeAttributesList.Value());

                switch (writerType.ParsedValue)
                {
                case WriterType.DocIds:
                    DocIdKinds docIdKind = docIdKinds.HasValue() ? docIdKinds.ParsedValue : DocIdKinds.All;
                    return(new DocumentIdWriter(output, filter, docIdKind));

                case WriterType.TypeForwards:
                    return(new TypeForwardWriter(output, filter)
                    {
                        IncludeForwardedTypes = true
                    });

                case WriterType.TypeList:
                    return(new TypeListWriter(syntaxWriter, filter));

                default:
                case WriterType.CSDecl:
                {
                    CSharpWriter writer = new CSharpWriter(syntaxWriter, filter, apiOnly.HasValue());
                    writer.IncludeSpaceBetweenMemberGroups = writer.IncludeMemberGroupHeadings = memberHeadings.HasValue();
                    writer.HighlightBaseMembers            = hightlightBaseMembers.HasValue();
                    writer.HighlightInterfaceMembers       = hightlightInterfaceMembers.HasValue();
                    writer.PutBraceOnNewLine = true;
                    writer.PlatformNotSupportedExceptionMessage = exceptionMessage.Value();
                    writer.IncludeGlobalPrefixForCompilation    = globalPrefix.HasValue();
                    writer.AlwaysIncludeBase = alwaysIncludeBase.HasValue();
                    writer.LangVersion       = GetLangVersion();
                    return(writer);
                }
                }
            }

            Version GetLangVersion()
            {
                if (langVersion.HasValue())
                {
                    var langVersionValue = langVersion.Value();

                    if (langVersionValue.Equals("default", StringComparison.OrdinalIgnoreCase))
                    {
                        return(CSDeclarationWriter.LangVersionDefault);
                    }
                    else if (langVersionValue.Equals("latest", StringComparison.OrdinalIgnoreCase))
                    {
                        return(CSDeclarationWriter.LangVersionLatest);
                    }
                    else if (langVersionValue.Equals("preview", StringComparison.OrdinalIgnoreCase))
                    {
                        return(CSDeclarationWriter.LangVersionPreview);
                    }
                    else if (Version.TryParse(langVersionValue, out var parsedVersion))
                    {
                        return(parsedVersion);
                    }
                }

                return(CSDeclarationWriter.LangVersionDefault);
            }

            return(app.Execute(args));
        }
Beispiel #35
0
        private static void FlipDataset(CommandArgument fileArgs, CommandOption jpgOption, bool basic)
        {
            //var flip = parser.GetOptions().FirstOrDefault(option => option.ShortName == "flip");
            //var flipBasic = parser.GetOptions().FirstOrDefault(option => option.ShortName == "flip-basic");
            var dataSource = fileArgs.Value;

            using (var metadata = Dlib.ImageDatasetMetadata.LoadImageDatasetMetadata(dataSource))
                using (var origMetadata = Dlib.ImageDatasetMetadata.LoadImageDatasetMetadata(dataSource))
                {
                    // Set the current directory to be the one that contains the
                    // metadata file. We do this because the file might contain
                    // file paths which are relative to this folder.
                    var parentDir = Path.GetDirectoryName(Path.GetFullPath(dataSource));
                    Environment.CurrentDirectory = parentDir;

                    var metadataFilename = Path.Combine(parentDir, $"flipped_{Path.GetFileName(dataSource)}");

                    var images = metadata.Images;
                    for (int i = 0, iCount = images.Count; i < iCount; ++i)
                    {
                        var f        = new FileInfo(images[i].FileName);
                        var parent   = Path.GetDirectoryName(f.FullName);
                        var filename = Path.Combine(parent, $"flipped_{ToPngName(f.Name)}");

                        using (var img = Dlib.LoadImage <RgbPixel>(images[i].FileName))
                            using (var temp = new Array2D <RgbPixel>())
                            {
                                Dlib.FlipImageLeftRight(img, temp);

                                if (jpgOption.HasValue())
                                {
                                    filename = ToJpgName(filename);
                                    Dlib.SaveJpeg(temp, filename, JpegQuality);
                                }
                                else
                                {
                                    Dlib.SavePng(temp, filename);
                                }

                                var boxes = images[i].Boxes;
                                for (int j = 0, bCount = boxes.Count; j < bCount; ++j)
                                {
                                    boxes[j].Rect = Dlib.FlipRectLeftRight(boxes[j].Rect, img.Rect);

                                    // flip all the object parts
                                    foreach (var kvp in boxes[j].Parts.ToArray())
                                    {
                                        var rect     = new Rectangle(kvp.Value, kvp.Value);
                                        var flipRect = Dlib.FlipRectLeftRight(rect, img.Rect);
                                        boxes[j].Parts[kvp.Key] = flipRect.TopLeft;
                                    }
                                }

                                images[i].FileName = filename;
                            }
                    }

                    //if (flipBasic == null || !flipBasic.HasValue())
                    if (!basic)
                    {
                        MakePartLabelingMatchTargetDataset(origMetadata, metadata);
                    }

                    Dlib.ImageDatasetMetadata.SaveImageDatasetMetadata(metadata, metadataFilename);
                }
        }
      public VoteModule()
      {
         CommandArgument title = new CommandArgument("title", ArgumentType.Custom, RepeatType.One, @"""[^""]+""");
         CommandArgument choiceList = new CommandArgument("choices", ArgumentType.Custom, RepeatType.OneOrMore, @"\S+"); 
         CommandArgument poll = new CommandArgument("poll#", ArgumentType.Integer);
         CommandArgument choice = new CommandArgument("choice", ArgumentType.Word);
         //CommandArgument pageNumber = new CommandArgument("page", ArgumentType.Integer, RepeatType.ZeroOrOne);
         CommandArgument search = new CommandArgument("search", ArgumentType.FullString);

         Commands.Add(new ModuleCommand("polls", new List<CommandArgument>(), "See the top open polls"));
         Commands.Add(new ModuleCommand("poll", new List<CommandArgument> {
            poll
         }, "See data for poll#"));
         Commands.Add(new ModuleCommand("pollcreate", new List<CommandArgument>{
            title, choiceList
         }, "Create a poll with given options.", true));
         Commands.Add(new ModuleCommand("vote", new List<CommandArgument> {
            choice, poll
         }, "Vote on poll#."));
         Commands.Add(new ModuleCommand("pollclose", new List<CommandArgument> {
            poll
         }, "Close the given poll", true));
         Commands.Add(new ModuleCommand("pollsearch", new List<CommandArgument> {
            search
         }, "Search for poll with given title"));
         Commands.Add(new ModuleCommand("pollsopen", new List<CommandArgument>(), "See your open polls"));

         AddOptions(new Dictionary<string, object> {
            { "maxUserPolls", 1 },
            { "maxPollChoices", 10 },
            { "archivesPerPage", 20 },
            { "searchResults", 5 }
         });

         GeneralHelp = "Quickstart: Do /polls to see the list of polls you can vote on. " +
            "Do /poll 1 to see the voting options for poll #1." +
            "Do /vote yes 1 to vote \"yes\" on poll #1. " +
            "Do /pollsearch Blah blah blah to search for a poll by title. " +
            "To create a poll, do /pollcreate \"This is my poll\" option1 option2 etc... " +
            "Options do not have to be yes or no, they can be anything. Options cannot have spaces.";
      }
Beispiel #37
0
        public static void Main(string[] args)
        {
            App     app     = new App();
            Program program = new Program();

            app.SetCurrentCulture();

            program.SetExtractValues();

            CommandLineApplication commandLineApplication = new CommandLineApplication(true)
            {
                Description = "Extract Heroes of the Storm game data into XML and JSON format",
            };

            commandLineApplication.HelpOption("-?|-h|--help");
            commandLineApplication.VersionOption("-v|--version", $"Heroes Data Parser ({App.Version})");

            ListCommand.Add(commandLineApplication).SetCommand();
            ReadCommand.Add(commandLineApplication).SetCommand();
            ExtractCommand.Add(commandLineApplication).SetCommand();
            ImageCommand.Add(commandLineApplication).SetCommand();
            QuickCompareCommand.Add(commandLineApplication).SetCommand();
            V4ConvertCommand.Add(commandLineApplication).SetCommand();

            CommandArgument storagePathArgument = commandLineApplication.Argument("storage-path", "The 'Heroes of the Storm' directory or an already extracted 'mods' directory.");

            CommandOption setOutputDirectoryOption    = commandLineApplication.Option("-o|--output-directory <FILEPATH>", "Sets the output directory.", CommandOptionType.SingleValue);
            CommandOption setDescriptionOption        = commandLineApplication.Option("-d|--description <VALUE>", "Sets the description output type (0 - 6) - Default: 0.", CommandOptionType.SingleValue);
            CommandOption extractDataFilesOption      = commandLineApplication.Option("-e|--extract-data <VALUE>", $"Extracts data files - Default: herodata.", CommandOptionType.MultipleValue);
            CommandOption extractImageFilesOption     = commandLineApplication.Option("-i|--extract-images <VALUE>", $"Extracts image files, only available using the Heroes of the Storm game directory.", CommandOptionType.MultipleValue);
            CommandOption setGameStringLocalizations  = commandLineApplication.Option("-l|--localization <LOCALE>", "Sets the gamestring localization(s) - Default: enUS.", CommandOptionType.MultipleValue);
            CommandOption setBuildOption              = commandLineApplication.Option("-b|--build <NUMBER>", "Sets the override build file(s).", CommandOptionType.SingleValue);
            CommandOption setMaxDegreeParallismOption = commandLineApplication.Option("-t|--threads <NUMBER>", "Limits the maximum amount of threads to use.", CommandOptionType.SingleValue);

            CommandOption xmlOutputOption          = commandLineApplication.Option("--xml", "Creates xml output.", CommandOptionType.NoValue);
            CommandOption jsonOutputOption         = commandLineApplication.Option("--json", "Creates json output.", CommandOptionType.NoValue);
            CommandOption setFileSplitOption       = commandLineApplication.Option("--file-split", "Splits the XML and JSON file(s) into multiple files.", CommandOptionType.NoValue);
            CommandOption localizedTextOption      = commandLineApplication.Option("--localized-text", "Extracts localized gamestrings from the XML and JSON file(s) into a text file.", CommandOptionType.NoValue);
            CommandOption minifyOption             = commandLineApplication.Option("--minify", "Creates .min file(s) along with current output file(s).", CommandOptionType.NoValue);
            CommandOption validationWarningsOption = commandLineApplication.Option("--warnings", "Displays all validation warnings.", CommandOptionType.NoValue);

            commandLineApplication.OnExecute(() =>
            {
                App.Defaults = false;

                if (extractImageFilesOption.HasValue() && !extractDataFilesOption.HasValue())
                {
                    return(InvalidCommand("You need to set the -e|--extract-data option"));
                }

                if (!string.IsNullOrWhiteSpace(storagePathArgument.Value))
                {
                    App.StoragePath = storagePathArgument.Value;
                }

                if (setMaxDegreeParallismOption.HasValue() && int.TryParse(setMaxDegreeParallismOption.Value(), out int result))
                {
                    App.MaxParallelism = result;
                }

                if (setDescriptionOption.HasValue() && Enum.TryParse(setDescriptionOption.Value(), out DescriptionType resultType))
                {
                    App.DescriptionType = resultType;
                }

                if (setBuildOption.HasValue() && int.TryParse(setBuildOption.Value(), out result))
                {
                    App.OverrideBuild = result;
                }

                if (setOutputDirectoryOption.HasValue())
                {
                    App.OutputDirectory = setOutputDirectoryOption.Value();
                }
                else
                {
                    App.OutputDirectory = Path.Combine(program.AssemblyPath, "output");
                }

                // data file extraction
                if (extractDataFilesOption.HasValue())
                {
                    if (extractDataFilesOption.Values.Exists(x => x.Equals("ALL", StringComparison.OrdinalIgnoreCase)))
                    {
                        App.ExtractDataOption = ExtractDataOption.All;
                    }
                    else
                    {
                        foreach (ExtractDataOption extractDataOption in Enum.GetValues(typeof(ExtractDataOption)))
                        {
                            if (extractDataOption == ExtractDataOption.None || extractDataOption == ExtractDataOption.All)
                            {
                                continue;
                            }

                            if (program.ExtractDataValues.TryGetValue(extractDataOption, out List <string> values))
                            {
                                if (extractDataFilesOption.Values.Intersect(values, StringComparer.OrdinalIgnoreCase).Any())
                                {
                                    App.ExtractDataOption |= extractDataOption;
                                }
                            }
                        }
                    }

                    // none is default as defined in App
                    if (App.ExtractDataOption != ExtractDataOption.None)
                    {
                        App.ExtractDataOption &= ~ExtractDataOption.None;
                    }
                }
                else
                {
                    App.ExtractDataOption = ExtractDataOption.HeroData;
                }

                // image file extraction
                if (extractImageFilesOption.HasValue() && !string.IsNullOrEmpty(storagePathArgument.Value))
                {
                    if (extractImageFilesOption.Values.Exists(x => x.Equals("ALL", StringComparison.OrdinalIgnoreCase)))
                    {
                        App.ExtractFileOption = ExtractImageOption.All;
                    }
                    else if (extractImageFilesOption.Values.Exists(x => x.Equals("ALL-SPLIT", StringComparison.OrdinalIgnoreCase) || x.Equals("ALLSPLIT", StringComparison.OrdinalIgnoreCase)))
                    {
                        App.ExtractFileOption = ExtractImageOption.AllSplit;
                    }
                    else
                    {
                        foreach (ExtractImageOption extractFileOption in Enum.GetValues(typeof(ExtractImageOption)))
                        {
                            if (extractFileOption == ExtractImageOption.None || extractFileOption == ExtractImageOption.All)
                            {
                                continue;
                            }

                            if (program.ExtractImageValues.TryGetValue(extractFileOption, out List <string> values))
                            {
                                if (extractImageFilesOption.Values.Intersect(values, StringComparer.OrdinalIgnoreCase).Any())
                                {
                                    App.ExtractFileOption |= extractFileOption;
                                }
                            }
                        }
                    }

                    // none is default as defined in App
                    if (App.ExtractFileOption != ExtractImageOption.None)
                    {
                        App.ExtractFileOption &= ~ExtractImageOption.None;
                    }
                }

                if (setGameStringLocalizations.HasValue())
                {
                    IEnumerable <string> localizations = new List <string>();

                    if (setGameStringLocalizations.Values.Exists(x => x.Equals("ALL", StringComparison.OrdinalIgnoreCase)))
                    {
                        localizations = Enum.GetNames(typeof(Localization));
                    }
                    else
                    {
                        localizations = setGameStringLocalizations.Values;
                    }

                    foreach (string locale in localizations)
                    {
                        if (Enum.TryParse(locale, true, out Localization localization))
                        {
                            app.Localizations.Add(localization);
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine($"Unknown localization - {locale}");
                        }
                    }

                    Console.ResetColor();
                    Console.WriteLine();
                }
                else
                {
                    app.Localizations.Add(Localization.ENUS);
                }

                App.CreateXml  = xmlOutputOption.HasValue();
                App.CreateJson = jsonOutputOption.HasValue();

                // if both not set, default to both true
                if (!xmlOutputOption.HasValue() && !jsonOutputOption.HasValue())
                {
                    App.CreateXml  = true;
                    App.CreateJson = true;
                }

                App.ShowValidationWarnings = validationWarningsOption.HasValue();
                App.IsFileSplit            = setFileSplitOption.HasValue();
                App.IsLocalizedText        = localizedTextOption.HasValue();
                App.CreateMinFiles         = minifyOption.HasValue();
                app.Run();
                Console.ResetColor();

                return(0);
            });

            if (args != null && args.Length > 0)
            {
                try
                {
                    commandLineApplication.Execute(args);
                }
                catch (CommandParsingException)
                {
                    return;
                }
            }
            else // defaults
            {
                App.Defaults = true;
                app.Run();
            }

            Console.ResetColor();
        }
        private CommandArgument[] GenerateArguments(
            string[] arguments)
        {
            CommandArgument[] resultArguments = new CommandArgument[ arguments.Length ];

            int currentArgument = 0;

            foreach ( string argument in arguments )
            {
                resultArguments[ currentArgument++ ] = new CommandArgument( argument );
            }

            return resultArguments;
        }
Beispiel #39
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>();
            var 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();

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

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

                var result = coverage.GetCoverageResult();

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

                foreach (var format in formats.HasValue() ? formats.Values : new List <string>(new string[] { "json" }))
                {
                    var 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
                        var filename = Path.GetFileName(dOutput);
                        filename     = (filename == string.Empty) ? $"coverage.{reporter.Extension}" : filename;
                        filename     = Path.HasExtension(filename) ? filename : $"{filename}.{reporter.Extension}";

                        var 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 (var 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);
                    }
                }

                Dictionary <ThresholdTypeFlags, double> thresholdTypeFlagValues = new Dictionary <ThresholdTypeFlags, double>();
                if (threshold.HasValue() && threshold.Value().Contains(','))
                {
                    var 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 (var thresholdValue in thresholdValues)
                    {
                        if (double.TryParse(thresholdValue, out var 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();

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

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

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

                foreach (var _module in result.Modules)
                {
                    var linePercent   = summary.CalculateLineCoverage(_module.Value).Percent;
                    var branchPercent = summary.CalculateBranchCoverage(_module.Value).Percent;
                    var methodPercent = summary.CalculateMethodCoverage(_module.Value).Percent;

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

                logger.LogInformation(coverageTable.ToStringAlternative());

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

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

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

                var 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);
            }
        }
        public void DuplicateArgsShouldThrow()
        {
            CommandLine.CommandEnvironment = new TestCommandEnvironment("/N:123 /N:345");

            var commandArg = new CommandArgument("/N:345", 7);
            commandArg.Command = "N";
            Assert.Equal(
                new CommandLineArgumentInvalidException(typeof(string), commandArg).Message,
                Assert.Throws<CommandLineArgumentInvalidException>(() => CommandLine.Parse<TestArgs>()).Message);
        }
Beispiel #41
0
        static int Main(string[] args)
        {
            Logger logger = new Logger();
            var    app    = new CommandLineApplication();

            app.Name        = "dotnet get";
            app.FullName    = ".NET Core Tools Global Installer";
            app.Description = "Install and use command line tools built on .NET Core";
            app.HelpOption("-h|--help");
            app.VersionOption("-v|--version", GetAssemblyVersion());

            CommandOption verboseOption = app.Option("--verbose", "Enable verbose output", CommandOptionType.NoValue);

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

            app.Command("install", c =>
            {
                c.Description = "Installs a .NET Core tool";
                c.HelpOption("-h|--help");

                CommandArgument source = c.Argument("<SOURCE>", "The tool to install. Can be a NuGet package");

                c.OnExecute(() =>
                {
                    logger = new Logger(verboseOption.HasValue());
                    if (string.IsNullOrWhiteSpace(source.Value))
                    {
                        logger.LogError("<SOURCE> argument is required. Use -h|--help to see help");
                        return(1);
                    }

                    InstallCommand installCommand = new InstallCommand(source.Value, logger);
                    return(installCommand.Execute() ? 0 : 1);
                });
            });

            app.Command("update", c =>
            {
                c.Description = "Updates a .NET Core tool";
                c.HelpOption("-h|--help");

                CommandArgument source = c.Argument("<SOURCE>", "The tool to update.");

                c.OnExecute(() =>
                {
                    logger = new Logger(verboseOption.HasValue());
                    if (string.IsNullOrWhiteSpace(source.Value))
                    {
                        return(Update(logger) ? 0 : 1);
                    }

                    UpdateCommand updateCommand = new UpdateCommand(source.Value, logger);
                    return(updateCommand.Execute() ? 0 : 1);
                });
            });

            app.Command("list", c =>
            {
                c.Description = "Lists all installed .NET Core tools";
                c.HelpOption("-h|--help");

                c.OnExecute(() =>
                {
                    logger = new Logger(verboseOption.HasValue());
                    ListCommand listCommand = new ListCommand(logger);
                    return(listCommand.Execute() ? 0 : 1);
                });
            });

            app.Command("uninstall", c =>
            {
                c.Description = "Uninstalls a .NET Core tool";
                c.HelpOption("-h|--help");

                CommandArgument source = c.Argument("<SOURCE>", "The tool to uninstall.");

                c.OnExecute(() =>
                {
                    logger = new Logger(verboseOption.HasValue());
                    if (string.IsNullOrWhiteSpace(source.Value))
                    {
                        logger.LogError("<SOURCE> argument is required. Use -h|--help to see help");
                        return(1);
                    }

                    UninstallCommand uninstallCommand = new UninstallCommand(source.Value, logger);
                    return(uninstallCommand.Execute() ? 0 : 1);
                });
            });

            try
            {
                return(app.Execute(args));
            }
            catch (CommandParsingException ex)
            {
                logger.LogWarning(ex.Message);
                app.ShowHelp();
                return(1);
            }
        }