public override bool Execute()
        {
            try
            {
#if DEBUG
                var debugPackTask = Environment.GetEnvironmentVariable("DEBUG_PACK_TASK");
                if (!string.IsNullOrEmpty(debugPackTask) && debugPackTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
                {
                    Debugger.Launch();
                }
#endif

                var            request        = GetRequest();
                var            logic          = PackTaskLogic;
                PackageBuilder packageBuilder = null;

                // If packing using a Nuspec file, we don't need to build a PackageBuilder here
                // as the package builder is built by reading the manifest file later in the code path.
                // Passing a null package builder for nuspec file code path is perfectly valid.
                if (string.IsNullOrEmpty(request.NuspecFile))
                {
                    packageBuilder = logic.GetPackageBuilder(request);
                }

                PackArgs packArgs   = logic.GetPackArgs(request);
                var      packRunner = logic.GetPackCommandRunner(request, packArgs, packageBuilder);

                return(logic.BuildPackage(packRunner));
            }
            catch (Exception ex)
            {
                ExceptionUtilities.LogException(ex, Logger);
                return(false);
            }
        }
示例#2
0
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // Log inputs
            log.LogDebug($"(in) RestoreGraphItems Count '{RestoreGraphItems?.Count() ?? 0}'");
            log.LogDebug($"(in) RestoreSources '{RestoreSources}'");
            log.LogDebug($"(in) RestorePackagesPath '{RestorePackagesPath}'");
            log.LogDebug($"(in) RestoreFallbackFolders '{RestoreFallbackFolders}'");
            log.LogDebug($"(in) RestoreDisableParallel '{RestoreDisableParallel}'");
            log.LogDebug($"(in) RestoreConfigFile '{RestoreConfigFile}'");
            log.LogDebug($"(in) RestoreNoCache '{RestoreNoCache}'");
            log.LogDebug($"(in) RestoreIgnoreFailedSources '{RestoreIgnoreFailedSources}'");
            log.LogDebug($"(in) RestoreRecursive '{RestoreRecursive}'");
            log.LogDebug($"(in) RestoreForce '{RestoreForce}'");
            log.LogDebug($"(in) HideWarningsAndErrors '{HideWarningsAndErrors}'");

            try
            {
                return(ExecuteAsync(log).Result);
            }
            catch (AggregateException ex) when(_cts.Token.IsCancellationRequested && ex.InnerException is TaskCanceledException)
            {
                // Canceled by user
                log.LogError(Strings.RestoreCanceled);
                return(false);
            }
            catch (Exception e)
            {
                ExceptionUtilities.LogException(e, log);
                return(false);
            }
        }
示例#3
0
        public override bool Execute()
        {
            try
            {
                var            request        = GetRequest();
                var            logic          = PackTaskLogic;
                PackageBuilder packageBuilder = null;
                var            packArgs       = logic.GetPackArgs(request);

                // If packing using a Nuspec file, we don't need to build a PackageBuilder here
                // as the package builder is built by reading the manifest file later in the code path.
                // Passing a null package builder for nuspec file code path is perfectly valid.
                if (string.IsNullOrEmpty(request.NuspecFile))
                {
                    packageBuilder = logic.GetPackageBuilder(request);
                }
                var packRunner = logic.GetPackCommandRunner(request, packArgs, packageBuilder);
                logic.BuildPackage(packRunner);

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionUtilities.LogException(ex, Logger);
                return(false);
            }
        }
示例#4
0
        public async Task <int> ExecuteCommandAsync(VerifyArgs verifyArgs)
        {
            if (verifyArgs.Verifications.Count == 0)
            {
                verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_VerificationTypeNotSupported));
                return(FailureCode);
            }

            var errorCount = 0;

            if (ShouldExecuteVerification(verifyArgs, Verification.Signatures))
            {
                var packagesToVerify = LocalFolderUtility.ResolvePackageFromPath(verifyArgs.PackagePath);
                LocalFolderUtility.EnsurePackageFileExists(verifyArgs.PackagePath, packagesToVerify);

                var verificationProviders = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
                var verifier = new PackageSignatureVerifier(verificationProviders, SignedPackageVerifierSettings.VerifyCommandDefaultPolicy);


                foreach (var package in packagesToVerify)
                {
                    try
                    {
                        errorCount += await VerifySignatureForPackageAsync(package, verifyArgs.Logger, verifier);
                    }
                    catch (InvalidDataException e)
                    {
                        verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_PackageIsNotValid, package));
                        ExceptionUtilities.LogException(e, verifyArgs.Logger);
                    }
                }
            }

            return(errorCount == 0 ? SuccessCode : FailureCode);
        }
示例#5
0
        public async Task <int> ExecuteCommandAsync(VerifyArgs verifyArgs)
        {
            if (verifyArgs.Verifications.Count == 0)
            {
                verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_VerificationTypeNotSupported));
                return(FailureCode);
            }

            var errorCount = 0;

            if (ShouldExecuteVerification(verifyArgs, Verification.Signatures))
            {
                var packagesToVerify = verifyArgs.PackagePaths.SelectMany(packagePath =>
                {
                    var packages = LocalFolderUtility.ResolvePackageFromPath(packagePath);
                    LocalFolderUtility.EnsurePackageFileExists(packagePath, packages);
                    return(packages);
                });

                var allowListEntries = verifyArgs.CertificateFingerprint.Select(fingerprint =>
                                                                                new CertificateHashAllowListEntry(
                                                                                    VerificationTarget.Author | VerificationTarget.Repository,
                                                                                    SignaturePlacement.PrimarySignature,
                                                                                    fingerprint,
                                                                                    _defaultFingerprintAlgorithm)).ToList();

                var verifierSettings      = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy();
                var verificationProviders = new List <ISignatureVerificationProvider>()
                {
                    new IntegrityVerificationProvider(),
                    new SignatureTrustAndValidityVerificationProvider()
                };

                verificationProviders.Add(
                    new AllowListVerificationProvider(
                        allowListEntries,
                        requireNonEmptyAllowList: false,
                        noMatchErrorMessage: Strings.Error_NoMatchingCertificate));

                var verifier = new PackageSignatureVerifier(verificationProviders);

                foreach (var package in packagesToVerify)
                {
                    try
                    {
                        errorCount += await VerifySignatureForPackageAsync(package, verifyArgs.Logger, verifier, verifierSettings);
                    }
                    catch (InvalidDataException e)
                    {
                        verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_PackageIsNotValid, package));
                        ExceptionUtilities.LogException(e, verifyArgs.Logger);
                    }
                }
            }

            return(errorCount == 0 ? SuccessCode : FailureCode);
        }
示例#6
0
        public async Task <int> ExecuteCommandAsync(
            IEnumerable <string> packagesToSign,
            AuthorSignPackageRequest signPackageRequest,
            string timestamper,
            ILogger logger,
            string outputDirectory,
            bool overwrite,
            CancellationToken token)
        {
            var success = true;

            try
            {
                SigningUtility.Verify(signPackageRequest, logger);
            }
            catch (Exception e)
            {
                success = false;
                ExceptionUtilities.LogException(e, logger);
            }

            if (success)
            {
                var signatureProvider = GetSignatureProvider(timestamper);

                foreach (var packagePath in packagesToSign)
                {
                    try
                    {
                        string outputPath;

                        if (string.IsNullOrEmpty(outputDirectory))
                        {
                            outputPath = packagePath;
                        }
                        else
                        {
                            outputPath = Path.Combine(outputDirectory, Path.GetFileName(packagePath));
                        }

                        await SignPackageAsync(packagePath, outputPath, logger, overwrite, signatureProvider, signPackageRequest, token);
                    }
                    catch (Exception e)
                    {
                        success = false;
                        ExceptionUtilities.LogException(e, logger);
                    }
                }
            }

            if (success)
            {
                logger.LogInformation(Strings.SignCommandSuccess);
            }

            return(success ? 0 : 1);
        }
示例#7
0
        public async Task <int> ExecuteCommandAsync(SignArgs signArgs)
        {
            // resolve path into multiple packages if needed.
            IEnumerable <string> packagesToSign = signArgs.PackagePaths.SelectMany(packagePath =>
            {
                IEnumerable <string> packages = LocalFolderUtility.ResolvePackageFromPath(packagePath);
                LocalFolderUtility.EnsurePackageFileExists(packagePath, packages);
                return(packages);
            });

            var success = true;

            X509Certificate2 cert = null;

            try
            {
                cert = await GetCertificateAsync(signArgs);
            }
            catch (Exception e)
            {
                success = false;
                ExceptionUtilities.LogException(e, signArgs.Logger);
            }

            if (success)
            {
                signArgs.Logger.LogInformation(Environment.NewLine);
                signArgs.Logger.LogInformation(Strings.SignCommandDisplayCertificate);
                signArgs.Logger.LogInformation(CertificateUtility.X509Certificate2ToString(cert, HashAlgorithmName.SHA256));

                if (!string.IsNullOrEmpty(signArgs.Timestamper))
                {
                    signArgs.Logger.LogInformation(Strings.SignCommandDisplayTimestamper);
                    signArgs.Logger.LogInformation(signArgs.Timestamper);
                }

                if (!string.IsNullOrEmpty(signArgs.OutputDirectory))
                {
                    signArgs.Logger.LogInformation(Strings.SignCommandOutputPath);
                    signArgs.Logger.LogInformation(signArgs.OutputDirectory);
                }

                using (var signRequest = new AuthorSignPackageRequest(cert, signArgs.SignatureHashAlgorithm, signArgs.TimestampHashAlgorithm))
                {
                    return(await ExecuteCommandAsync(
                               packagesToSign,
                               signRequest,
                               signArgs.Timestamper,
                               signArgs.Logger,
                               signArgs.OutputDirectory,
                               signArgs.Overwrite,
                               signArgs.Token));
                }
            }

            return(success ? 0 : 1);
        }
示例#8
0
        public override bool Execute()
        {
#if DEBUG
            var debugRestoreTask = Environment.GetEnvironmentVariable("DEBUG_RESTORE_TASK");
            if (!string.IsNullOrEmpty(debugRestoreTask) && debugRestoreTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
#if IS_CORECLR
                Console.WriteLine("Waiting for debugger to attach.");
                Console.WriteLine($"Process ID: {Process.GetCurrentProcess().Id}");

                while (!Debugger.IsAttached)
                {
                    System.Threading.Thread.Sleep(100);
                }
                Debugger.Break();
#else
                Debugger.Launch();
#endif
            }
#endif
            var log = new MSBuildLogger(Log);

            // Log inputs
            log.LogDebug($"(in) RestoreGraphItems Count '{RestoreGraphItems?.Count() ?? 0}'");
            log.LogDebug($"(in) RestoreDisableParallel '{RestoreDisableParallel}'");
            log.LogDebug($"(in) RestoreNoCache '{RestoreNoCache}'");
            log.LogDebug($"(in) RestoreIgnoreFailedSources '{RestoreIgnoreFailedSources}'");
            log.LogDebug($"(in) RestoreRecursive '{RestoreRecursive}'");
            log.LogDebug($"(in) RestoreForce '{RestoreForce}'");
            log.LogDebug($"(in) HideWarningsAndErrors '{HideWarningsAndErrors}'");
            log.LogDebug($"(in) RestoreForceEvaluate '{RestoreForceEvaluate}'");

            try
            {
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !Interactive);
                return(ExecuteAsync(log).Result);
            }
            catch (AggregateException ex) when(_cts.Token.IsCancellationRequested && ex.InnerException is TaskCanceledException)
            {
                // Canceled by user
                log.LogError(Strings.RestoreCanceled);
                return(false);
            }
            catch (Exception e)
            {
                ExceptionUtilities.LogException(e, log);
                return(false);
            }
            finally
            {
                // The CredentialService lifetime is for the duration of the process. We should not leave a potentially unavailable logger.
                // We need to update the delegating logger with a null instance
                // because the tear downs of the plugins and similar rely on idleness and process exit.
                DefaultCredentialServiceUtility.UpdateCredentialServiceDelegatingLogger(NullLogger.Instance);
            }
        }
示例#9
0
        public override bool Execute()
        {
#if DEBUG
            var debugRestoreTask = Environment.GetEnvironmentVariable("DEBUG_RESTORE_TASK");
            if (!string.IsNullOrEmpty(debugRestoreTask) && debugRestoreTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
#if IS_CORECLR
                Console.WriteLine("Waiting for debugger to attach.");
                Console.WriteLine($"Process ID: {Process.GetCurrentProcess().Id}");

                while (!Debugger.IsAttached)
                {
                    System.Threading.Thread.Sleep(100);
                }
                Debugger.Break();
#else
                Debugger.Launch();
#endif
            }
#endif
            var log = new MSBuildLogger(Log);

            // Log inputs
            log.LogDebug($"(in) RestoreGraphItems Count '{RestoreGraphItems?.Count() ?? 0}'");
            log.LogDebug($"(in) RestoreDisableParallel '{RestoreDisableParallel}'");
            log.LogDebug($"(in) RestoreNoCache '{RestoreNoCache}'");
            log.LogDebug($"(in) RestoreIgnoreFailedSources '{RestoreIgnoreFailedSources}'");
            log.LogDebug($"(in) RestoreRecursive '{RestoreRecursive}'");
            log.LogDebug($"(in) RestoreForce '{RestoreForce}'");
            log.LogDebug($"(in) HideWarningsAndErrors '{HideWarningsAndErrors}'");
            log.LogDebug($"(in) RestoreForceEvaluate '{RestoreForceEvaluate}'");
            log.LogDebug($"(in) RestorePackagesConfig '{RestorePackagesConfig}'");

            try
            {
                return(ExecuteAsync(log).Result);
            }
            catch (AggregateException ex) when(_cts.Token.IsCancellationRequested && ex.InnerException is TaskCanceledException)
            {
                // Canceled by user
                log.LogError(Strings.RestoreCanceled);
                return(false);
            }
            catch (Exception e)
            {
                ExceptionUtilities.LogException(e, log);
                return(false);
            }
        }
示例#10
0
        public override bool Execute()
        {
            try
            {
#if DEBUG
                var debugPackTask = Environment.GetEnvironmentVariable("DEBUG_PACK_TASK");
                if (!string.IsNullOrEmpty(debugPackTask) && debugPackTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
                {
#if IS_CORECLR
                    Console.WriteLine("Waiting for debugger to attach.");
                    Console.WriteLine($"Process ID: {Process.GetCurrentProcess().Id}");

                    while (!Debugger.IsAttached)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    Debugger.Break();
#else
                    Debugger.Launch();
#endif
                }
#endif

                var            request        = GetRequest();
                var            logic          = PackTaskLogic;
                PackageBuilder packageBuilder = null;
                var            packArgs       = logic.GetPackArgs(request);

                // If packing using a Nuspec file, we don't need to build a PackageBuilder here
                // as the package builder is built by reading the manifest file later in the code path.
                // Passing a null package builder for nuspec file code path is perfectly valid.
                if (string.IsNullOrEmpty(request.NuspecFile))
                {
                    packageBuilder = logic.GetPackageBuilder(request);
                }
                var packRunner = logic.GetPackCommandRunner(request, packArgs, packageBuilder);
                logic.BuildPackage(packRunner);

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionUtilities.LogException(ex, Logger);
                return(false);
            }
        }
示例#11
0
        public static object GetValueFromRegistryKey(string name, string registryKeyPath, RegistryKey registryKey, ILogger logger)
        {
            try
            {
                using (var key = registryKey?.OpenSubKey(name))
                {
                    var result = key?.GetValue(name);

                    return(result);
                }
            }
            catch (SecurityException ex)
            {
                // If the user doesn't have access to the registry, then we'll return null
                ExceptionUtilities.LogException(ex, logger);
                return(null);
            }
        }
        public async Task <int> ExecuteCommandAsync(VerifyArgs verifyArgs)
        {
            if (verifyArgs.Verifications.Count == 0)
            {
                verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_VerificationTypeNotSupported));
                return(FailureCode);
            }

            var errorCount = 0;

            if (ShouldExecuteVerification(verifyArgs, Verification.Signatures))
            {
                var packagesToVerify = LocalFolderUtility.ResolvePackageFromPath(verifyArgs.PackagePath);
                LocalFolderUtility.EnsurePackageFileExists(verifyArgs.PackagePath, packagesToVerify);

                var allowListEntries = verifyArgs.CertificateFingerprint.Select(fingerprint =>
                                                                                new CertificateHashAllowListEntry(
                                                                                    VerificationTarget.Author | VerificationTarget.Repository,
                                                                                    SignaturePlacement.PrimarySignature,
                                                                                    fingerprint,
                                                                                    _defaultFingerprintAlgorithm)).ToList();

                var verifierSettings      = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy(clientAllowListEntries: allowListEntries);
                var verificationProviders = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
                var verifier = new PackageSignatureVerifier(verificationProviders);

                foreach (var package in packagesToVerify)
                {
                    try
                    {
                        errorCount += await VerifySignatureForPackageAsync(package, verifyArgs.Logger, verifier, verifierSettings);
                    }
                    catch (InvalidDataException e)
                    {
                        verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_PackageIsNotValid, package));
                        ExceptionUtilities.LogException(e, verifyArgs.Logger);
                    }
                }
            }

            return(errorCount == 0 ? SuccessCode : FailureCode);
        }
示例#13
0
        public override bool Execute()
        {
            // Log Inputs
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectUniqueName '{ProjectUniqueName}'");
            if (RestoreSources != null)
            {
                log.LogDebug($"(in) RestoreSources '{string.Join(";", RestoreSources.Select(p => p))}'");
            }
            if (RestorePackagesPath != null)
            {
                log.LogDebug($"(in) RestorePackagesPath '{RestorePackagesPath}'");
            }
            if (RestoreFallbackFolders != null)
            {
                log.LogDebug($"(in) RestoreFallbackFolders '{string.Join(";", RestoreFallbackFolders.Select(p => p))}'");
            }
            if (RestoreConfigFile != null)
            {
                log.LogDebug($"(in) RestoreConfigFile '{RestoreConfigFile}'");
            }

            if (RestoreSolutionDirectory != null)
            {
                log.LogDebug($"(in) RestoreSolutionDirectory '{RestoreSolutionDirectory}'");
            }

            if (RestoreAdditionalProjectSources != null)
            {
                log.LogDebug($"(in) RestoreAdditionalProjectSources '{RestoreAdditionalProjectSources}'");
            }

            if (RestoreAdditionalProjectFallbackFolders != null)
            {
                log.LogDebug($"(in) RestoreAdditionalProjectFallbackFolders '{RestoreAdditionalProjectFallbackFolders}'");
            }

            try
            {
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, Path.GetDirectoryName(ProjectUniqueName), RestoreConfigFile, _machineWideSettings);

                OutputPackagesPath = RestoreSettingsUtils.GetPackagesPath(ProjectUniqueName, settings, RestorePackagesPath);

                if (RestoreSources == null)
                {
                    var packageSourceProvider      = new PackageSourceProvider(settings);
                    var packageSourcesFromProvider = packageSourceProvider.LoadPackageSources();
                    OutputSources = packageSourcesFromProvider.Select(e => e.Source).ToArray();
                }
                else if (MSBuildRestoreUtility.ContainsClearKeyword(RestoreSources))
                {
                    if (MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                    {
                        // Fail due to invalid combination
                        return(false);
                    }

                    OutputSources = new string[] { };
                }
                else
                {
                    // Relative -> Absolute paths
                    OutputSources = RestoreSources.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray();
                }

                // Append additional sources
                OutputSources = AppendItems(OutputSources, RestoreAdditionalProjectSources);

                if (RestoreFallbackFolders == null)
                {
                    OutputFallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToArray();
                }
                else if (MSBuildRestoreUtility.ContainsClearKeyword(RestoreFallbackFolders))
                {
                    if (MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                    {
                        // Fail due to invalid combination
                        return(false);
                    }

                    OutputFallbackFolders = new string[] { };
                }
                else
                {
                    // Relative -> Absolute paths
                    OutputFallbackFolders = RestoreFallbackFolders.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray();
                }

                // Append additional fallback folders
                OutputFallbackFolders = AppendItems(OutputFallbackFolders, RestoreAdditionalProjectFallbackFolders);

                OutputConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).ToArray();
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            log.LogDebug($"(out) OutputPackagesPath '{OutputPackagesPath}'");
            log.LogDebug($"(out) OutputSources '{string.Join(";", OutputSources.Select(p => p))}'");
            log.LogDebug($"(out) OutputFallbackFolders '{string.Join(";", OutputFallbackFolders.Select(p => p))}'");
            log.LogDebug($"(out) OutputConfigFilePaths '{string.Join(";", OutputConfigFilePaths.Select(p => p))}'");

            return(true);
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildStartupDirectory), MSBuildStartupDirectory);

            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                // Find the absolute path of nuget.config, this should only be set on the command line. Setting the path in project files
                // is something that could happen, but it is not supported.
                var absoluteConfigFilePath = GetGlobalAbsolutePath(RestoreConfigFile);
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, Path.GetDirectoryName(ProjectUniqueName), absoluteConfigFilePath, _machineWideSettings);
                OutputConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                // Sources
                var currentSources = RestoreSettingsUtils.GetValue(
                    () => RestoreSourcesOverride?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => GetGlobalAbsolutePath(e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreSources) ? new string[0] : null,
                    () => RestoreSources?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => (new PackageSourceProvider(settings)).LoadPackageSources().Where(e => e.IsEnabled).Select(e => e.Source).ToArray());

                // Append additional sources
                // Escape strings to avoid xplat path issues with msbuild.
                var additionalProjectSources = MSBuildRestoreUtility.AggregateSources(
                    values: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectSources"),
                    excludeValues: Enumerable.Empty <string>())
                                               .Select(MSBuildRestoreUtility.FixSourcePath)
                                               .ToArray();

                OutputSources = AppendItems(currentSources, additionalProjectSources);

                // Fallback folders
                var currentFallbackFolders = RestoreSettingsUtils.GetValue(
                    () => RestoreFallbackFoldersOverride?.Select(e => GetGlobalAbsolutePath(e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreFallbackFolders) ? new string[0] : null,
                    () => RestoreFallbackFolders?.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => SettingsUtility.GetFallbackPackageFolders(settings).ToArray());

                // Append additional fallback folders after removing excluded folders
                var additionalProjectFallbackFolders = MSBuildRestoreUtility.AggregateSources(
                    values: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFolders"),
                    excludeValues: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFoldersExcludes"))
                                                       .ToArray();

                OutputFallbackFolders = AppendItems(currentFallbackFolders, additionalProjectFallbackFolders);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
        public async Task <int> ExecuteCommandAsync(VerifyArgs verifyArgs)
        {
            if (verifyArgs.Verifications.Count == 0)
            {
                verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_VerificationTypeNotSupported));
                return(FailureCode);
            }

            var errorCount = 0;

            if (ShouldExecuteVerification(verifyArgs, Verification.Signatures))
            {
                if (!IsSignatureVerifyCommandSupported())
                {
                    verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_NotSupported));
                    return(FailureCode);
                }

                var packagesToVerify = verifyArgs.PackagePaths.SelectMany(packagePath =>
                {
                    var packages = LocalFolderUtility.ResolvePackageFromPath(packagePath);
                    LocalFolderUtility.EnsurePackageFileExists(packagePath, packages);
                    return(packages);
                });

                ClientPolicyContext clientPolicyContext = ClientPolicyContext.GetClientPolicy(verifyArgs.Settings, verifyArgs.Logger);

                // List of values passed through --certificate-fingerprint option read
                var allowListEntries = verifyArgs.CertificateFingerprint.Select(fingerprint =>
                                                                                new CertificateHashAllowListEntry(
                                                                                    VerificationTarget.Author | VerificationTarget.Repository,
                                                                                    SignaturePlacement.PrimarySignature,
                                                                                    fingerprint,
                                                                                    _defaultFingerprintAlgorithm)).ToList();

                var verifierSettings      = SignedPackageVerifierSettings.GetVerifyCommandDefaultPolicy();
                var verificationProviders = new List <ISignatureVerificationProvider>()
                {
                    new IntegrityVerificationProvider()
                };

                // trustedSigners section >> Owners are considered here.
                verificationProviders.Add(
                    new AllowListVerificationProvider(
                        clientPolicyContext.AllowList,
                        requireNonEmptyAllowList: clientPolicyContext.Policy == SignatureValidationMode.Require,
                        emptyListErrorMessage: Strings.Error_NoClientAllowList,
                        noMatchErrorMessage: Strings.Error_NoMatchingClientCertificate));

                IEnumerable <KeyValuePair <string, HashAlgorithmName> > trustedSignerAllowUntrustedRootList = clientPolicyContext.AllowList?
                                                                                                              .Where(c => c.AllowUntrustedRoot)
                                                                                                              .Select(c => new KeyValuePair <string, HashAlgorithmName>(c.Fingerprint, c.FingerprintAlgorithm));

                // trustedSigners section >> allowUntrustedRoot set true are considered here.
                verificationProviders.Add(new SignatureTrustAndValidityVerificationProvider(trustedSignerAllowUntrustedRootList));

                // List of values passed through --certificate-fingerprint option are considered here.
                verificationProviders.Add(
                    new AllowListVerificationProvider(
                        allowListEntries,
                        requireNonEmptyAllowList: false,
                        noMatchErrorMessage: Strings.Error_NoMatchingCertificate));

                var verifier = new PackageSignatureVerifier(verificationProviders);

                foreach (var package in packagesToVerify)
                {
                    try
                    {
                        errorCount += await VerifySignatureForPackageAsync(package, verifyArgs.Logger, verifier, verifierSettings);
                    }
                    catch (InvalidDataException e)
                    {
                        verifyArgs.Logger.LogError(string.Format(CultureInfo.CurrentCulture, Strings.VerifyCommand_PackageIsNotValid, package));
                        ExceptionUtilities.LogException(e, verifyArgs.Logger);
                    }
                }
            }

            return(errorCount == 0 ? SuccessCode : FailureCode);
        }
        private static void LogException(Exception exception, IConsole console)
        {
            var logStackAsError = console.Verbosity == Verbosity.Detailed;

            ExceptionUtilities.LogException(exception, console, logStackAsError);
        }
示例#17
0
        public static int MainCore(string workingDirectory, string[] args)
        {
            // First, optionally disable localization in resources.
            if (args.Any(arg => string.Equals(arg, ForceEnglishOutputOption, StringComparison.OrdinalIgnoreCase)))
            {
                CultureUtility.DisableLocalization();
            }

            // set output encoding to UTF8 if -utf8 is specified
            var oldOutputEncoding = System.Console.OutputEncoding;

            if (args.Any(arg => string.Equals(arg, Utf8Option, StringComparison.OrdinalIgnoreCase)))
            {
                args = args.Where(arg => !string.Equals(arg, Utf8Option, StringComparison.OrdinalIgnoreCase)).ToArray();
                SetConsoleOutputEncoding(Encoding.UTF8);
            }

            // Increase the maximum number of connections per server.
            if (!RuntimeEnvironmentHelper.IsMono)
            {
                ServicePointManager.DefaultConnectionLimit = 64;
            }
            else
            {
                // Keep mono limited to a single download to avoid issues.
                ServicePointManager.DefaultConnectionLimit = 1;
            }

            NetworkProtocolUtility.ConfigureSupportedSslProtocols();

            var console         = new Console();
            var fileSystem      = new CoreV2.NuGet.PhysicalFileSystem(workingDirectory);
            var logStackAsError = console.Verbosity == Verbosity.Detailed;

            try
            {
                // Remove NuGet.exe.old
                RemoveOldFile(fileSystem);

                // Import Dependencies
                var p = new Program();
                p.Initialize(fileSystem, console);

                // Add commands to the manager
                foreach (var cmd in p.Commands)
                {
                    p.Manager.RegisterCommand(cmd);
                }

                var parser = new CommandLineParser(p.Manager);

                // Parse the command
                var command = parser.ParseCommandLine(args) ?? p.HelpCommand;
                command.CurrentDirectory = workingDirectory;

                // Fallback on the help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    // Get the command name and add it to the argument list of the help command
                    var commandName = command.CommandAttribute.CommandName;

                    // Print invalid command then show help
                    console.WriteLine(LocalizedResourceManager.GetString("InvalidArguments"), commandName);

                    p.HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    SetConsoleInteractivity(console, command as Command);

                    try
                    {
                        command.Execute();
                    }
                    catch (AggregateException e)
                    {
                        var unwrappedEx = ExceptionUtility.Unwrap(e);

                        if (unwrappedEx is CommandLineArgumentCombinationException)
                        {
                            var commandName = command.CommandAttribute.CommandName;

                            console.WriteLine($"{string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InvalidArguments"), commandName)} {unwrappedEx.Message}");

                            p.HelpCommand.ViewHelpForCommand(commandName);

                            return(1);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    catch (CommandLineArgumentCombinationException e)
                    {
                        var commandName = command.CommandAttribute.CommandName;

                        console.WriteLine($"{string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InvalidArguments"), commandName)} {e.Message}");

                        p.HelpCommand.ViewHelpForCommand(commandName);

                        return(1);
                    }
                }
            }
            catch (AggregateException exception)
            {
                var unwrappedEx   = ExceptionUtility.Unwrap(exception);
                var rootException = ExceptionUtility.GetRootException(exception);

                if (unwrappedEx is ExitCodeException)
                {
                    // Return the exit code without writing out the exception type
                    var exitCodeEx = unwrappedEx as ExitCodeException;
                    return(exitCodeEx.ExitCode);
                }
                if (rootException is PathTooLongException)
                {
                    LogHelperMessageForPathTooLongException(console);
                }

                // Log the exception and stack trace.
                ExceptionUtilities.LogException(unwrappedEx, console, logStackAsError);
                return(1);
            }
            catch (ExitCodeException e)
            {
                return(e.ExitCode);
            }
            catch (PathTooLongException e)
            {
                // Log the exception and stack trace.
                ExceptionUtilities.LogException(e, console, logStackAsError);
                LogHelperMessageForPathTooLongException(console);
                return(1);
            }
            catch (Exception exception)
            {
                ExceptionUtilities.LogException(exception, console, logStackAsError);
                return(1);
            }
            finally
            {
                CoreV2.NuGet.OptimizedZipPackage.PurgeCache();
                SetConsoleOutputEncoding(oldOutputEncoding);
            }

            return(0);
        }
        public override bool Execute()
        {
#if DEBUG
            var debugRestoreTask = Environment.GetEnvironmentVariable("DEBUG_RESTORE_SETTINGS_TASK");
            if (!string.IsNullOrEmpty(debugRestoreTask) && debugRestoreTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
                System.Diagnostics.Debugger.Launch();
            }
#endif
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreRepositoryPath), RestoreRepositoryPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreRootConfigDirectory), RestoreRootConfigDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreProjectStyle), RestoreProjectStyle);
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildStartupDirectory), MSBuildStartupDirectory);


            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                // Find the absolute path of nuget.config, this should only be set on the command line. Setting the path in project files
                // is something that could happen, but it is not supported.
                var    absoluteConfigFilePath = GetGlobalAbsolutePath(RestoreConfigFile);
                string restoreDir;
                // To match non-msbuild behavior, we only default the restoreDir for non-PackagesConfig scenarios.
                if (string.IsNullOrEmpty(RestoreRootConfigDirectory))
                {
                    restoreDir = Path.GetDirectoryName(ProjectUniqueName);
                }
                else
                {
                    restoreDir = RestoreRootConfigDirectory;
                }
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, restoreDir, absoluteConfigFilePath, _machineWideSettings);
                OutputConfigFilePaths = settings.GetConfigFilePaths().ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                OutputRepositoryPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestoreRepositoryPathOverride),
                    () => string.IsNullOrEmpty(RestoreRepositoryPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestoreRepositoryPath),
                    () => SettingsUtility.GetRepositoryPath(settings));

                // Sources
                OutputSources = BuildTasksUtility.GetSources(
                    MSBuildStartupDirectory,
                    Path.GetDirectoryName(ProjectUniqueName),
                    RestoreSources,
                    RestoreSourcesOverride,
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectSources"),
                    settings);

                // Fallback folders
                OutputFallbackFolders = BuildTasksUtility.GetFallbackFolders(
                    MSBuildStartupDirectory,
                    Path.GetDirectoryName(ProjectUniqueName),
                    RestoreFallbackFolders, RestoreFallbackFoldersOverride,
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFolders"),
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFoldersExcludes"),
                    settings);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputRepositoryPath), OutputRepositoryPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreAdditionalProjectSources), RestoreAdditionalProjectSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreAdditionalProjectFallbackFolders), RestoreAdditionalProjectFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);

            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, Path.GetDirectoryName(ProjectUniqueName), RestoreConfigFile, _machineWideSettings);
                OutputConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => string.IsNullOrEmpty(RestorePackagesPathOverride) ? null : UriUtility.GetAbsolutePath(MSBuildStartupDirectory, RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                // Sources
                var currentSources = RestoreSettingsUtils.GetValue(
                    () => RestoreSourcesOverride?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePath(MSBuildStartupDirectory, e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreSources) ? new string[0] : null,
                    () => RestoreSources?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => (new PackageSourceProvider(settings)).LoadPackageSources().Select(e => e.Source).ToArray());

                // Append additional sources
                // Escape strings to avoid xplat path issues with msbuild.
                OutputSources = AppendItems(currentSources, RestoreAdditionalProjectSources?.Select(MSBuildRestoreUtility.FixSourcePath).ToArray());

                // Fallback folders
                var currentFallbackFolders = RestoreSettingsUtils.GetValue(
                    () => RestoreFallbackFoldersOverride?.Select(e => UriUtility.GetAbsolutePath(MSBuildStartupDirectory, e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreFallbackFolders) ? new string[0] : null,
                    () => RestoreFallbackFolders?.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => SettingsUtility.GetFallbackPackageFolders(settings).ToArray());

                // Append additional fallback folders
                OutputFallbackFolders = AppendItems(currentFallbackFolders, RestoreAdditionalProjectFallbackFolders);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
示例#20
0
        public async Task <int> ExecuteCommandAsync(
            IEnumerable <string> packagesToSign,
            SignPackageRequest signPackageRequest,
            string timestamper,
            ILogger logger,
            string outputDirectory,
            bool overwrite,
            CancellationToken token)
        {
            var success = true;

            try
            {
                SigningUtility.Verify(signPackageRequest, logger);
            }
            catch (Exception e)
            {
                success = false;
                ExceptionUtilities.LogException(e, logger);
            }

            if (success)
            {
                var signatureProvider = GetSignatureProvider(timestamper);

                foreach (var packagePath in packagesToSign)
                {
                    // Set the output of the signing operation to a temp file because signing cannot be done in place.
                    var tempPackageFile = new FileInfo(Path.GetTempFileName());

                    try
                    {
                        string outputPath;

                        if (string.IsNullOrEmpty(outputDirectory))
                        {
                            outputPath = packagePath;
                        }
                        else
                        {
                            outputPath = Path.Combine(outputDirectory, Path.GetFileName(packagePath));
                        }

                        using (var options = SigningOptions.CreateFromFilePaths(
                                   packagePath,
                                   tempPackageFile.FullName,
                                   overwrite,
                                   signatureProvider,
                                   logger))
                        {
                            await SigningUtility.SignAsync(options, signPackageRequest, token);
                        }

                        if (tempPackageFile.Length > 0)
                        {
                            FileUtility.Replace(tempPackageFile.FullName, outputPath);
                        }
                        else
                        {
                            throw new SignatureException(Strings.Error_UnableToSignPackage);
                        }
                    }
                    catch (Exception e)
                    {
                        success = false;
                        ExceptionUtilities.LogException(e, logger);
                    }
                    finally
                    {
                        FileUtility.Delete(tempPackageFile.FullName);
                    }
                }
            }

            if (success)
            {
                logger.LogInformation(Strings.SignCommandSuccess);
            }

            return(success ? 0 : 1);
        }