private static void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { ProgressRecord record = new ProgressRecord(1, "Downloading wsusscn2.cab", ""); record.RecordType = ProgressRecordType.Processing; record.PercentComplete = e.ProgressPercentage; record.CurrentOperation = $"{e.BytesReceived} of {e.TotalBytesToReceive}"; _command?.WriteProgress(record); }
private List <PSResourceInfo> InstallPackage( IEnumerable <PSResourceInfo> pkgsToInstall, // those found to be required to be installed (includes Dependency packages as well) string repoName, string repoUri, PSCredentialInfo repoCredentialInfo, PSCredential credential, bool isLocalRepo) { List <PSResourceInfo> pkgsSuccessfullyInstalled = new List <PSResourceInfo>(); int totalPkgs = pkgsToInstall.Count(); // Counters for tracking current package out of total int totalInstalledPkgCount = 0; foreach (PSResourceInfo pkg in pkgsToInstall) { totalInstalledPkgCount++; var tempInstallPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { // Create a temp directory to install to var dir = Directory.CreateDirectory(tempInstallPath); // should check it gets created properly // To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator // with a mask (bitwise complement of desired attributes combination). // TODO: check the attributes and if it's read only then set it // attribute may be inherited from the parent // TODO: are there Linux accommodations we need to consider here? dir.Attributes &= ~FileAttributes.ReadOnly; _cmdletPassedIn.WriteVerbose(string.Format("Begin installing package: '{0}'", pkg.Name)); if (!_quiet) { int activityId = 0; int percentComplete = ((totalInstalledPkgCount * 100) / totalPkgs); string activity = string.Format("Installing {0}...", pkg.Name); string statusDescription = string.Format("{0}% Complete", percentComplete); _cmdletPassedIn.WriteProgress( new ProgressRecord(activityId, activity, statusDescription)); } // Create PackageIdentity in order to download string createFullVersion = pkg.Version.ToString(); if (pkg.IsPrerelease) { createFullVersion = pkg.Version.ToString() + "-" + pkg.Prerelease; } if (!NuGetVersion.TryParse(createFullVersion, out NuGetVersion pkgVersion)) { var message = String.Format("{0} package could not be installed with error: could not parse package '{0}' version '{1} into a NuGetVersion", pkg.Name, pkg.Version.ToString()); var ex = new ArgumentException(message); var packageIdentityVersionParseError = new ErrorRecord(ex, "psdataFileNotExistError", ErrorCategory.ReadError, null); _cmdletPassedIn.WriteError(packageIdentityVersionParseError); _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase)); continue; } var pkgIdentity = new PackageIdentity(pkg.Name, pkgVersion); var cacheContext = new SourceCacheContext(); if (isLocalRepo) { /* Download from a local repository -- this is slightly different process than from a server */ var localResource = new FindLocalPackagesResourceV2(repoUri); var resource = new LocalDownloadResource(repoUri, localResource); // Actually downloading the .nupkg from a local repo var result = resource.GetDownloadResourceResultAsync( identity: pkgIdentity, downloadContext: new PackageDownloadContext(cacheContext), globalPackagesFolder: tempInstallPath, logger: NullLogger.Instance, token: _cancellationToken).GetAwaiter().GetResult(); // Create the package extraction context PackageExtractionContext packageExtractionContext = new PackageExtractionContext( packageSaveMode: PackageSaveMode.Nupkg, xmlDocFileSaveMode: PackageExtractionBehavior.XmlDocFileSaveMode, clientPolicyContext: null, logger: NullLogger.Instance); // Extracting from .nupkg and placing files into tempInstallPath result.PackageReader.CopyFiles( destination: tempInstallPath, packageFiles: result.PackageReader.GetFiles(), extractFile: new PackageFileExtractor( result.PackageReader.GetFiles(), packageExtractionContext.XmlDocFileSaveMode).ExtractPackageFile, logger: NullLogger.Instance, token: _cancellationToken); result.Dispose(); } else { /* Download from a non-local repository */ // Set up NuGet API resource for download PackageSource source = new PackageSource(repoUri); // Explicitly passed in Credential takes precedence over repository CredentialInfo if (credential != null) { string password = new NetworkCredential(string.Empty, credential.Password).Password; source.Credentials = PackageSourceCredential.FromUserInput(repoUri, credential.UserName, password, true, null); } else if (repoCredentialInfo != null) { PSCredential repoCredential = Utils.GetRepositoryCredentialFromSecretManagement( repoName, repoCredentialInfo, _cmdletPassedIn); string password = new NetworkCredential(string.Empty, repoCredential.Password).Password; source.Credentials = PackageSourceCredential.FromUserInput(repoUri, repoCredential.UserName, password, true, null); } var provider = FactoryExtensionsV3.GetCoreV3(NuGet.Protocol.Core.Types.Repository.Provider); SourceRepository repository = new SourceRepository(source, provider); /* Download from a non-local repository -- ie server */ var downloadResource = repository.GetResourceAsync <DownloadResource>().GetAwaiter().GetResult(); DownloadResourceResult result = null; try { result = downloadResource.GetDownloadResourceResultAsync( identity: pkgIdentity, downloadContext: new PackageDownloadContext(cacheContext), globalPackagesFolder: tempInstallPath, logger: NullLogger.Instance, token: _cancellationToken).GetAwaiter().GetResult(); } catch (Exception e) { _cmdletPassedIn.WriteVerbose(string.Format("Error attempting download: '{0}'", e.Message)); } finally { // Need to close the .nupkg if (result != null) { result.Dispose(); } } } _cmdletPassedIn.WriteVerbose(string.Format("Successfully able to download package from source to: '{0}'", tempInstallPath)); // pkgIdentity.Version.Version gets the version without metadata or release labels. string newVersion = pkgIdentity.Version.ToNormalizedString(); string normalizedVersionNoPrerelease = newVersion; if (pkgIdentity.Version.IsPrerelease) { // eg: 2.0.2 normalizedVersionNoPrerelease = pkgIdentity.Version.ToNormalizedString().Substring(0, pkgIdentity.Version.ToNormalizedString().IndexOf('-')); } string tempDirNameVersion = isLocalRepo ? tempInstallPath : Path.Combine(tempInstallPath, pkgIdentity.Id.ToLower(), newVersion); var version4digitNoPrerelease = pkgIdentity.Version.Version.ToString(); string moduleManifestVersion = string.Empty; var scriptPath = Path.Combine(tempDirNameVersion, pkg.Name + PSScriptFileExt); var modulePath = Path.Combine(tempDirNameVersion, pkg.Name + PSDataFileExt); // Check if the package is a module or a script var isModule = File.Exists(modulePath); string installPath; if (_savePkg) { // For save the installation path is what is passed in via -Path installPath = _pathsToInstallPkg.FirstOrDefault(); // If saving as nupkg simply copy the nupkg and move onto next iteration of loop // asNupkg functionality only applies to Save-PSResource if (_asNupkg) { var nupkgFile = pkgIdentity.ToString().ToLower() + ".nupkg"; File.Copy(Path.Combine(tempDirNameVersion, nupkgFile), Path.Combine(installPath, nupkgFile)); _cmdletPassedIn.WriteVerbose(string.Format("'{0}' moved into file path '{1}'", nupkgFile, installPath)); pkgsSuccessfullyInstalled.Add(pkg); continue; } } else { // PSModules: /// ./Modules /// ./Scripts /// _pathsToInstallPkg is sorted by desirability, Find will pick the pick the first Script or Modules path found in the list installPath = isModule ? _pathsToInstallPkg.Find(path => path.EndsWith("Modules", StringComparison.InvariantCultureIgnoreCase)) : _pathsToInstallPkg.Find(path => path.EndsWith("Scripts", StringComparison.InvariantCultureIgnoreCase)); } if (isModule) { var moduleManifest = Path.Combine(tempDirNameVersion, pkgIdentity.Id + PSDataFileExt); if (!File.Exists(moduleManifest)) { var message = String.Format("{0} package could not be installed with error: Module manifest file: {1} does not exist. This is not a valid PowerShell module.", pkgIdentity.Id, moduleManifest); var ex = new ArgumentException(message); var psdataFileDoesNotExistError = new ErrorRecord(ex, "psdataFileNotExistError", ErrorCategory.ReadError, null); _cmdletPassedIn.WriteError(psdataFileDoesNotExistError); _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase)); continue; } if (!Utils.TryParsePSDataFile(moduleManifest, _cmdletPassedIn, out Hashtable parsedMetadataHashtable)) { // Ran into errors parsing the module manifest file which was found in Utils.ParseModuleManifest() and written. continue; } moduleManifestVersion = parsedMetadataHashtable["ModuleVersion"] as string; // Accept License verification if (!_savePkg && !CallAcceptLicense(pkg, moduleManifest, tempInstallPath, newVersion)) { continue; } // If NoClobber is specified, ensure command clobbering does not happen if (_noClobber && !DetectClobber(pkg.Name, parsedMetadataHashtable)) { continue; } } // Delete the extra nupkg related files that are not needed and not part of the module/script DeleteExtraneousFiles(pkgIdentity, tempDirNameVersion); if (_includeXML) { CreateMetadataXMLFile(tempDirNameVersion, installPath, pkg, isModule); } MoveFilesIntoInstallPath( pkg, isModule, isLocalRepo, tempDirNameVersion, tempInstallPath, installPath, newVersion, moduleManifestVersion, scriptPath); _cmdletPassedIn.WriteVerbose(String.Format("Successfully installed package '{0}' to location '{1}'", pkg.Name, installPath)); pkgsSuccessfullyInstalled.Add(pkg); } catch (Exception e) { _cmdletPassedIn.WriteError( new ErrorRecord( new PSInvalidOperationException( message: $"Unable to successfully install package '{pkg.Name}': '{e.Message}'", innerException: e), "InstallPackageFailed", ErrorCategory.InvalidOperation, _cmdletPassedIn)); _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase)); } finally { // Delete the temp directory and all its contents _cmdletPassedIn.WriteVerbose(string.Format("Attempting to delete '{0}'", tempInstallPath)); if (Directory.Exists(tempInstallPath)) { if (!TryDeleteDirectory(tempInstallPath, out ErrorRecord errorMsg)) { _cmdletPassedIn.WriteError(errorMsg); } else { _cmdletPassedIn.WriteVerbose(String.Format("Successfully deleted '{0}'", tempInstallPath)); } } } } return(pkgsSuccessfullyInstalled); }