private static async Task <int> ExecuteCommand(TrustCommand action,
                                                       CommandOption algorithm,
                                                       bool allowUntrustedRootOption,
                                                       CommandOption owners,
                                                       CommandOption verbosity,
                                                       CommandOption configFile,
                                                       Func <ILogger> getLogger,
                                                       Action <LogLevel> setLogLevel,
                                                       string name        = null,
                                                       string sourceUrl   = null,
                                                       string packagePath = null,
                                                       string fingerprint = null)
        {
            ILogger logger = getLogger();

            try
            {
                ISettings settings = XPlatUtility.ProcessConfigFile(configFile.Value());

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

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

                // Add is the only action which does certificate chain building.
                if (trustedSignersArgs.Action == TrustedSignersAction.Add)
                {
                    X509TrustStore.InitializeForDotNetSdk(logger);
                }

#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);
            }
            catch (InvalidOperationException e)
            {
                // nuget trust command handled exceptions.
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var error_TrustedSignerAlreadyExistsMessage = string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustedSignerAlreadyExists, name);

                    if (e.Message == error_TrustedSignerAlreadyExistsMessage)
                    {
                        logger.LogError(error_TrustedSignerAlreadyExistsMessage);
                        return(1);
                    }
                }

                if (!string.IsNullOrWhiteSpace(sourceUrl))
                {
                    var error_TrustedRepoAlreadyExists = string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustedRepoAlreadyExists, sourceUrl);

                    if (e.Message == error_TrustedRepoAlreadyExists)
                    {
                        logger.LogError(error_TrustedRepoAlreadyExists);
                        return(1);
                    }
                }

                throw;
            }
            catch (ArgumentException e)
            {
                if (e.Data is System.Collections.IDictionary)
                {
                    logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.Error_TrustFingerPrintAlreadyExist));
                    return(1);
                }

                throw;
            }
        }
        public static void Register(CommandLineApplication app, Func <ILogger> getLogger,
                                    Func <IPackageReferenceCommandRunner> getCommandRunner)
        {
            app.Command("add", addpkg =>
            {
                addpkg.Description = Strings.AddPkg_Description;
                addpkg.HelpOption(XPlatUtility.HelpOption);

                addpkg.Option(
                    CommandConstants.ForceEnglishOutputOption,
                    Strings.ForceEnglishOutput_Description,
                    CommandOptionType.NoValue);

                var id = addpkg.Option(
                    "--package",
                    Strings.AddPkg_PackageIdDescription,
                    CommandOptionType.SingleValue);

                var version = addpkg.Option(
                    "--version",
                    Strings.AddPkg_PackageVersionDescription,
                    CommandOptionType.SingleValue);

                var dgFilePath = addpkg.Option(
                    "-d|--dg-file",
                    Strings.AddPkg_DgFileDescription,
                    CommandOptionType.SingleValue);

                var projectPath = addpkg.Option(
                    "-p|--project",
                    Strings.AddPkg_ProjectPathDescription,
                    CommandOptionType.SingleValue);

                var frameworks = addpkg.Option(
                    "-f|--framework",
                    Strings.AddPkg_FrameworksDescription,
                    CommandOptionType.MultipleValue);

                var noRestore = addpkg.Option(
                    "-n|--no-restore",
                    Strings.AddPkg_NoRestoreDescription,
                    CommandOptionType.NoValue);

                var sources = addpkg.Option(
                    "-s|--source",
                    Strings.AddPkg_SourcesDescription,
                    CommandOptionType.MultipleValue);

                var packageDirectory = addpkg.Option(
                    "--package-directory",
                    Strings.AddPkg_PackageDirectoryDescription,
                    CommandOptionType.SingleValue);

                var interactive = addpkg.Option(
                    "--interactive",
                    Strings.AddPkg_InteractiveDescription,
                    CommandOptionType.NoValue);

                var prerelease = addpkg.Option(
                    "--prerelease",
                    Strings.AddPkg_PackagePrerelease,
                    CommandOptionType.NoValue);

                addpkg.OnExecute(() =>
                {
                    ValidateArgument(id, addpkg.Name);
                    ValidateArgument(projectPath, addpkg.Name);
                    ValidateProjectPath(projectPath, addpkg.Name);
                    if (!noRestore.HasValue())
                    {
                        ValidateArgument(dgFilePath, addpkg.Name);
                    }
                    var logger         = getLogger();
                    var noVersion      = !version.HasValue();
                    var packageVersion = version.HasValue() ? version.Value() : null;
                    ValidatePrerelease(prerelease.HasValue(), noVersion, addpkg.Name);
                    var packageRefArgs = new PackageReferenceArgs(projectPath.Value(), logger)
                    {
                        Frameworks       = CommandLineUtility.SplitAndJoinAcrossMultipleValues(frameworks.Values),
                        Sources          = CommandLineUtility.SplitAndJoinAcrossMultipleValues(sources.Values),
                        PackageDirectory = packageDirectory.Value(),
                        NoRestore        = noRestore.HasValue(),
                        NoVersion        = noVersion,
                        DgFilePath       = dgFilePath.Value(),
                        Interactive      = interactive.HasValue(),
                        Prerelease       = prerelease.HasValue(),
                        PackageVersion   = packageVersion,
                        PackageId        = id.Values[0]
                    };
                    var msBuild = new MSBuildAPIUtility(logger);
                    var addPackageRefCommandRunner = getCommandRunner();
                    return(addPackageRefCommandRunner.ExecuteCommand(packageRefArgs, msBuild));
                });
            });
        }
        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);
                });
            });
        }