public CommandParameterAttribute(string commandParameter, bool isOptional, 
            CommandOption.CommandOptionType optionType, bool useConfigurationDefaults, 
            string additionalHelpText)
        {
            _commandParameter = commandParameter;
            _isOptional = isOptional;
            _optionType = optionType;
            _additionalHelpText = additionalHelpText;
            _useConfigurationDefualts = useConfigurationDefaults;

        }
Ejemplo n.º 2
0
 public OptionItem(CommandOption option, string syntax, string description) : base(syntax, description)
 {
     Option = option;
 }
 public CommandParameterAttribute(string commandParameter, CommandOption.CommandOptionType optionType)
     : this(commandParameter, false, optionType, false, string.Empty)
 {
 }
Ejemplo n.º 4
0
        public Dictionary <string, string> GetKeyValuePairOrDefault(Dictionary <string, string> propertyValue, CommandOption option, bool required)
        {
            if (propertyValue != null)
            {
                return(propertyValue);
            }
            else if (!string.IsNullOrEmpty(DefaultConfig[option.Switch] as string))
            {
                var configDefault = DefaultConfig[option.Switch] as string;
                if (string.IsNullOrEmpty(configDefault))
                {
                    return(null);
                }

                return(Utilities.ParseKeyValueOption(configDefault));
            }
            else if (required && this.EnableInteractive)
            {
                var response = PromptForValue(option);
                if (string.IsNullOrEmpty(response))
                {
                    return(null);
                }

                return(Utilities.ParseKeyValueOption(response));
            }

            return(null);
        }
Ejemplo n.º 5
0
        public StrykerOptions Build(
            string basePath,
            CommandOption reporter,
            CommandOption dashboardApiKey,
            CommandOption dashboardUrl,
            CommandOption reportersProjectName,
            CommandOption reportersModuleName,
            CommandOption reportersProjectVersion,
            CommandOption fallbackVersion,
            CommandOption projectUnderTestNameFilter,
            CommandOption additionalTimeoutMS,
            CommandOption excludedMutations,
            CommandOption ignoreMethods,
            CommandOption logLevel,
            CommandOption logToFile,
            CommandOption devMode,
            CommandOption coverageAnalysis,
            CommandOption abortTestOnFail,
            CommandOption configFilePath,
            CommandOption disableSimultaneousTesting,
            CommandOption maxConcurrentTestRunners,
            CommandOption thresholdHigh,
            CommandOption thresholdLow,
            CommandOption thresholdBreak,
            CommandOption filesToExclude,
            CommandOption filePatterns,
            CommandOption testRunner,
            CommandOption solutionPath,
            CommandOption languageVersion,
            CommandOption diff,
            CommandOption diffCompareToDashboard,
            CommandOption gitSource,
            CommandOption testProjects)
        {
            var fileLocation = Path.Combine(basePath, GetOption(configFilePath.Value(), CLIOptions.ConfigFilePath));

            if (File.Exists(fileLocation))
            {
                try
                {
                    _config = new ConfigurationBuilder()
                              .SetBasePath(basePath)
                              .AddJsonFile(fileLocation)
                              .Build()
                              .GetSection("stryker-config");
                }
                catch (FormatException formatException)
                {
                    throw new StrykerInputException("The stryker config file was in an incorrect format.", formatException.InnerException.Message);
                }
            }

            return(new StrykerOptions(
                       logger: _logger,
                       basePath: basePath,
                       reporters: GetOption(reporter.Value(), CLIOptions.Reporters),
                       dashboardApiKey: GetOption(dashboardApiKey.Value(), CLIOptions.DashboardApiKeyOption),
                       dashboardUrl: GetOption(dashboardUrl.Value(), CLIOptions.DashboardUrlOption),
                       projectName: GetOption(reportersProjectName.Value(), CLIOptions.DashboardProjectNameOption),
                       moduleName: GetOption(reportersModuleName.Value(), CLIOptions.DashboardModuleNameOption),
                       projectVersion: GetOption(reportersProjectVersion.Value(), CLIOptions.DashboardProjectVersionOption),
                       fallbackVersion: GetOption(fallbackVersion.Value(), CLIOptions.DashboardFallbackVersionOption),
                       projectUnderTestNameFilter: GetOption(projectUnderTestNameFilter.Value(), CLIOptions.ProjectFileName),
                       additionalTimeoutMS: GetOption(additionalTimeoutMS.Value(), CLIOptions.AdditionalTimeoutMS),
                       excludedMutations: GetOption(excludedMutations.Value(), CLIOptions.ExcludedMutations),
                       ignoredMethods: GetOption(ignoreMethods.Value(), CLIOptions.IgnoreMethods),
                       logLevel: GetOption(logLevel.Value(), CLIOptions.LogLevel),
                       logToFile: GetOption(logToFile.HasValue(), CLIOptions.LogToFile),
                       devMode: GetOption(devMode.HasValue(), CLIOptions.DevMode),
                       maxConcurrentTestRunners: GetOption(maxConcurrentTestRunners.Value(), CLIOptions.MaxConcurrentTestRunners),
                       coverageAnalysis: GetOption(coverageAnalysis.Value(), CLIOptions.CoverageAnalysis),
                       abortTestOnFail: GetOption(abortTestOnFail.HasValue(), CLIOptions.AbortTestOnFail),
                       disableSimultaneousTesting: GetOption(disableSimultaneousTesting.HasValue(), CLIOptions.DisableTestingMix),
                       thresholdHigh: GetOption(thresholdHigh.Value(), CLIOptions.ThresholdHigh),
                       thresholdLow: GetOption(thresholdLow.Value(), CLIOptions.ThresholdLow),
                       thresholdBreak: GetOption(thresholdBreak.Value(), CLIOptions.ThresholdBreak),
                       filesToExclude: GetOption(filesToExclude.Value(), CLIOptions.FilesToExclude),
                       mutate: GetOption(filePatterns.Value(), CLIOptions.Mutate),
                       testRunner: GetOption(testRunner.Value(), CLIOptions.TestRunner),
                       solutionPath: GetOption(solutionPath.Value(), CLIOptions.SolutionPath),
                       languageVersion: GetOption(languageVersion.Value(), CLIOptions.LanguageVersionOption),
                       diff: (GetOption(diff.HasValue(), CLIOptions.Diff)) || GetOption(diffCompareToDashboard.HasValue(), CLIOptions.DashboardCompare),
                       compareToDashboard: GetOption(diffCompareToDashboard.HasValue(), CLIOptions.DashboardCompare),
                       gitSource: GetOption(gitSource.Value(), CLIOptions.GitSource),
                       testProjects: GetOption(testProjects.Value(), CLIOptions.TestProjects)));
        }
Ejemplo n.º 6
0
        static int Main(string[] args)
        {
            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 project = app.Argument("<PROJECT>", "The project to test. Defaults to the current directory.");
            CommandOption   config  = app.Option("-c|--configuration", "Configuration to use for building the project.", CommandOptionType.SingleValue);
            CommandOption   output  = app.Option("-o|--coverage-output", "The output path of the generated coverage report", CommandOptionType.SingleValue);
            CommandOption   format  = app.Option("-f|--coverage-format", "The format of the coverage report", CommandOptionType.SingleValue);

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

                dotnetTestArgs.Add("test");

                if (project.Value != string.Empty)
                {
                    dotnetTestArgs.Add(project.Value);
                }

                if (config.HasValue())
                {
                    dotnetTestArgs.Add($"-c {config.Value()}");
                }

                dotnetTestArgs.Add("/p:CollectCoverage=true");

                if (output.HasValue())
                {
                    dotnetTestArgs.Add($"/p:CoverletOutput={output.Value()}");
                }

                if (format.HasValue())
                {
                    dotnetTestArgs.Add($"/p:CoverletOutputFormat={format.Value()}");
                }

                Process process                  = new Process();
                process.StartInfo.FileName       = "dotnet";
                process.StartInfo.Arguments      = string.Join(" ", dotnetTestArgs);
                process.StartInfo.CreateNoWindow = true;

                process.Start();
                process.WaitForExit();

                return(process.ExitCode);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (CommandParsingException ex)
            {
                Console.WriteLine(ex.Message);
                app.ShowHelp();
                return(1);
            }
        }
Ejemplo n.º 7
0
        protected Func <Task <Settings> > CreateSettingsInitializer(
            CommandLineApplication cmd,
            bool requireAwsProfile = true
            )
        {
            CommandOption awsProfileOption = null;
            CommandOption awsRegionOption  = null;

            // add misc options
            var tierOption = cmd.Option("--tier|-T <NAME>", "(optional) Name of deployment tier (default: LAMBDASHARP_TIER environment variable)", CommandOptionType.SingleValue);

            if (requireAwsProfile)
            {
                awsProfileOption = cmd.Option("--aws-profile|-P <NAME>", "(optional) Use a specific AWS profile from the AWS credentials file", CommandOptionType.SingleValue);
                awsRegionOption  = cmd.Option("--aws-region <NAME>", "(optional) Use a specific AWS region (default: read from AWS profile)", CommandOptionType.SingleValue);
            }

            // add hidden testing options
            var awsAccountIdOption         = cmd.Option("--aws-account-id <VALUE>", "(test only) Override AWS account Id (default: read from AWS profile)", CommandOptionType.SingleValue);
            var awsUserArnOption           = cmd.Option("--aws-user-arn <ARN>", "(test only) Override AWS user ARN (default: read from AWS profile)", CommandOptionType.SingleValue);
            var toolVersionOption          = cmd.Option("--cli-version <VALUE>", "(test only) LambdaSharp CLI version for profile", CommandOptionType.SingleValue);
            var deploymentBucketNameOption = cmd.Option("--deployment-bucket-name <NAME>", "(test only) S3 Bucket name used to deploy modules (default: read from LambdaSharp CLI configuration)", CommandOptionType.SingleValue);
            var tierVersionOption          = cmd.Option("--tier-version <VERSION>", "(test only) LambdaSharp tier version (default: read from deployment tier)", CommandOptionType.SingleValue);
            var promptsAsErrorsOption      = cmd.Option("--prompts-as-errors", "(optional) Missing parameters cause an error instead of a prompts (use for CI/CD to avoid unattended prompts)", CommandOptionType.NoValue);

            awsAccountIdOption.ShowInHelpText         = false;
            awsUserArnOption.ShowInHelpText           = false;
            toolVersionOption.ShowInHelpText          = false;
            deploymentBucketNameOption.ShowInHelpText = false;
            tierVersionOption.ShowInHelpText          = false;
            return(async() => {
                // check if experimental caching feature is enabled
                Settings.AllowCaching = string.Equals((Environment.GetEnvironmentVariable("LAMBDASHARP_FEATURE_CACHING") ?? "false"), "true", StringComparison.OrdinalIgnoreCase);

                // initialize deployment tier
                string tier = tierOption.Value() ?? Environment.GetEnvironmentVariable("LAMBDASHARP_TIER") ?? "";

                // initialize AWS profile
                try {
                    AwsAccountInfo awsAccount = null;
                    IAmazonSimpleSystemsManagement ssmClient = null;
                    IAmazonCloudFormation cfnClient = null;
                    IAmazonKeyManagementService kmsClient = null;
                    IAmazonS3 s3Client = null;
                    IAmazonAPIGateway apiGatewayClient = null;
                    IAmazonIdentityManagementService iamClient = null;
                    IAmazonLambda lambdaClient = null;
                    if (requireAwsProfile)
                    {
                        awsAccount = await InitializeAwsProfile(
                            awsProfileOption.Value(),
                            awsAccountIdOption.Value(),
                            awsRegionOption.Value(),
                            awsUserArnOption.Value()
                            );

                        if (awsAccount == null)
                        {
                            return null;
                        }

                        // create AWS clients
                        ssmClient = new AmazonSimpleSystemsManagementClient(AWSConfigs.RegionEndpoint);
                        cfnClient = new AmazonCloudFormationClient(AWSConfigs.RegionEndpoint);
                        kmsClient = new AmazonKeyManagementServiceClient(AWSConfigs.RegionEndpoint);
                        s3Client = new AmazonS3Client(AWSConfigs.RegionEndpoint);
                        apiGatewayClient = new AmazonAPIGatewayClient(AWSConfigs.RegionEndpoint);
                        iamClient = new AmazonIdentityManagementServiceClient(AWSConfigs.RegionEndpoint);
                        lambdaClient = new AmazonLambdaClient(AWSConfigs.RegionEndpoint);
                    }
                    if (HasErrors)
                    {
                        return null;
                    }

                    // initialize LambdaSharp deployment values
                    var tierVersion = tierVersionOption.Value();
                    var deploymentBucketName = deploymentBucketNameOption.Value();

                    // initialize LambdaSharp testing values
                    VersionInfo toolVersion = null;
                    if (toolVersionOption.HasValue())
                    {
                        toolVersion = VersionInfo.Parse(toolVersionOption.Value());
                    }

                    // create a settings instance for each module filename
                    return new Settings(toolVersion ?? Version)
                    {
                        TierVersion = (tierVersion != null) ? VersionInfo.Parse(tierVersion) : null,
                        Tier = tier,
                        AwsRegion = awsAccount?.Region,
                        AwsAccountId = awsAccount?.AccountId,
                        AwsUserArn = awsAccount?.UserArn,
                        DeploymentBucketName = deploymentBucketName,
                        SsmClient = ssmClient,
                        CfnClient = cfnClient,
                        KmsClient = kmsClient,
                        S3Client = s3Client,
                        ApiGatewayClient = apiGatewayClient,
                        IamClient = iamClient,
                        LambdaClient = lambdaClient,
                        PromptsAsErrors = promptsAsErrorsOption.HasValue()
                    };
                } catch (AmazonClientException e) when(e.Message == "No RegionEndpoint or ServiceURL configured")
                {
                    LogError("AWS profile is missing a region specifier");
                    return null;
                }
            });
        }
Ejemplo n.º 8
0
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            CommandLineApplication app = new CommandLineApplication();

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

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

            CommandOption   tempOutput = app.Option("--temp-output <arg>", "Compilation temporary directory", CommandOptionType.SingleValue);
            CommandOption   outputName = app.Option("--out <arg>", "Name of the output assembly", CommandOptionType.SingleValue);
            CommandOption   references = app.Option("--reference <arg>...", "Path to a compiler metadata reference", CommandOptionType.MultipleValue);
            CommandOption   analyzers  = app.Option("--analyzer <arg>...", "Path to an analyzer assembly", CommandOptionType.MultipleValue);
            CommandOption   resources  = app.Option("--resource <arg>...", "Resources to embed", CommandOptionType.MultipleValue);
            CommandArgument sources    = app.Argument("<source-files>...", "Compilation sources", multipleValues: true);

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

                CommonCompilerOptions commonOptions = commonCompilerCommandLine.GetOptionValues();

                AssemblyInfoOptions assemblyInfoOptions = assemblyInfoCommandLine.GetOptionValues();

                var translated = TranslateCommonOptions(commonOptions, outputName.Value());

                var allArgs = new List <string>(translated);
                allArgs.AddRange(GetDefaultOptions());

                // Generate assembly info
                var assemblyInfo = Path.Combine(tempOutput.Value(), $"dotnet-compile.assemblyinfo.cs");

                File.WriteAllText(assemblyInfo, AssemblyInfoFileGenerator.GenerateCSharp(assemblyInfoOptions, sources.Values));

                allArgs.Add($"\"{assemblyInfo}\"");

                if (outputName.HasValue())
                {
                    allArgs.Add($"-out:\"{outputName.Value()}\"");
                }

                allArgs.AddRange(analyzers.Values.Select(a => $"-a:\"{a}\""));
                allArgs.AddRange(references.Values.Select(r => $"-r:\"{r}\""));

                // Resource has two parts separated by a comma
                // Only the first should be quoted. This is handled
                // in dotnet-compile where the information is present.
                allArgs.AddRange(resources.Values.Select(resource => $"-resource:{resource}"));

                allArgs.AddRange(sources.Values.Select(s => $"\"{s}\""));

                var rsp = Path.Combine(tempOutput.Value(), "dotnet-compile-csc.rsp");

                File.WriteAllLines(rsp, allArgs, Encoding.UTF8);

                // Execute CSC!
                var result = RunCsc(new string[] { $"-noconfig", "@" + $"{rsp}" })
                             .WorkingDirectory(Directory.GetCurrentDirectory())
                             .ForwardStdErr()
                             .ForwardStdOut()
                             .Execute();

                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);
            }
        }
Ejemplo n.º 9
0
        public static Task Create(ManagementClient client, CommandArgument endpointName, CommandOption topicName, CommandOption subscriptionName, CommandArgument eventType, CommandOption ruleName)
        {
            var topicNameToUse        = topicName.HasValue() ? topicName.Value() : Topic.DefaultTopicName;
            var subscriptionNameToUse = subscriptionName.HasValue() ? subscriptionName.Value() : endpointName.Value;
            var eventToSubscribeTo    = eventType.Value;
            var ruleNameToUse         = ruleName.HasValue() ? ruleName.Value() : eventToSubscribeTo;
            var description           = new RuleDescription(ruleNameToUse, new SqlFilter($"[NServiceBus.EnclosedMessageTypes] LIKE '%{eventToSubscribeTo}%'"));

            return(client.CreateRuleAsync(topicNameToUse, subscriptionNameToUse, description));
        }
Ejemplo n.º 10
0
        public static Task Delete(ManagementClient client, CommandArgument endpointName, CommandOption topicName, CommandOption subscriptionName, CommandArgument eventType, CommandOption ruleName)
        {
            var topicNameToUse        = topicName.HasValue() ? topicName.Value() : Topic.DefaultTopicName;
            var subscriptionNameToUse = subscriptionName.HasValue() ? subscriptionName.Value() : endpointName.Value;
            var eventToSubscribeTo    = eventType.Value;
            var ruleNameToUse         = ruleName.HasValue() ? ruleName.Value() : eventToSubscribeTo;

            return(client.DeleteRuleAsync(topicNameToUse, subscriptionNameToUse, ruleNameToUse));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Настройка команд для идентификации ввода в консоли cmd.exe.
        /// </summary>
        /// <param name="args"> аргументы сонсоли cmd.exe</param>
        /// <returns>Настроенный экземпляр реализации команд консоли cmd.exe</returns>
        public static CommandLineApplication InitCommandLine(string[] args)
        {
            CommandLineApplication commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: false);

            CommandOption createDictionary = commandLineApplication.Option(
                "--create | -c",
                "The command to create a dictionary, you must specify the name of the file with the text. A dictionary will be created from the text.",
                CommandOptionType.SingleValue);

            var updateDictionary = commandLineApplication.Option(
                "--update | -u",
                "The command to update the dictionary, you must specify the name of the file with the text." +
                " New words will be added from the text, and existing words in the dictionary will be updated.",
                CommandOptionType.SingleValue);

            var deleteDictionary = commandLineApplication.Option(
                "--delete | -d",
                "The command to delete the dictionary.",
                CommandOptionType.NoValue);

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


            commandLineApplication.OnExecute(() =>
            {
                //одновременно должна выполняться только одна команда
                int numberInsertCommand = 0; //счетчик команд

                foreach (var command in commandLineApplication.GetOptions())
                {
                    if (command.HasValue())
                    {
                        numberInsertCommand++;
                    }
                }

                if (numberInsertCommand > 1) //команд больше чем одна
                {
                    Console.WriteLine("You can specify only one command-line parameter at a time (commands)");
                    Environment.Exit(0);
                    return(0);
                }


                DBDictionaryWord dbContext;
                IGenericRepository <DictionaryWord> repo;
                ManagerDictionary manager;

                dbContext = new DBDictionaryWord();
                repo      = new GenericRepository <DictionaryWord>(dbContext);
                manager   = new ManagerDictionary(repo);

                //обработка команд
                //команда создания словаря
                if (createDictionary.HasValue())
                {
                    if (IsUTF8(createDictionary.Value()))
                    {
                        string text = "";
                        text        = File.ReadAllText(createDictionary.Value(), Encoding.Default);
                        manager.CreateDictionary(text);
                    }
                    else
                    {
                        Console.WriteLine("Error: The file format is not UTF8.");
                    }
                }

                //команда обновления словаря
                if (updateDictionary.HasValue())
                {
                    if (IsUTF8(updateDictionary.Value()))
                    {
                        string text = "";
                        text        = File.ReadAllText(updateDictionary.Value(), Encoding.Default);
                        manager.UpdateDictionary(text);
                    }
                    else
                    {
                        Console.WriteLine("Error: The file format is not UTF8.");
                    }
                }

                //команда удаления словаря
                if (deleteDictionary.HasValue())
                {
                    manager.DeleteDictionary();
                }
                Environment.Exit(0);
                return(0);
            });
            return(commandLineApplication);
        }
Ejemplo n.º 12
0
        private static string PrepareQueryForBatch(CommandOption mysqlTable, IList <KeyValuePair <string, string> > batch)
        {
            var values = string.Join(",", batch.Select(r => $"('{r.Key}','{r.Value}')"));

            return($"INSERT INTO {mysqlTable.Value()}(user, pass) VALUES {values};");
        }