protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { try { base.ProcessPackage(provider, searchKey, package); // return the object to the caller now. WriteObject(package); if (IncludeDependencies) { var missingDependencies = new HashSet<string>(); foreach (var dep in package.Dependencies) { // note: future work may be needed if the package sources currently selected by the user don't // contain the dependencies. var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this); var depPkg = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault(); if (depPkg == null) { missingDependencies.Add(dep); Warning(Constants.Messages.UnableToFindDependencyPackage, dep); } else { ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg); } } if (missingDependencies.Any()) { Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma()); } } } catch (Exception ex) { Debug("Calling ProcessPackage {0}", ex.ToString()); } }
private static void InstallPackageViaPowerShellGet(PackageJson packageJson, PackageSourceListRequest request, SoftwareIdentity[] packages) { var provider = PackageSourceListRequest.FindProvider(request, packageJson.Type, request, true); if (provider == null) return; IHostApi installRequest = request; if (provider.Name.EqualsIgnoreCase(Constants.ProviderNames.PowerShellGet) && !request.ProviderServices.IsElevated) { // if we're not elevated, we want powershellget to install to the user scope installRequest = PackageSourceListRequest.ExtendRequest( new Dictionary<string, string[]> { {"Scope", new[] {"CurrentUser"}} }, null, packageJson.IsTrustedSource, request); } else { installRequest = PackageSourceListRequest.ExtendRequest( new Dictionary<string, string[]> { {"Destination", new[] {packageJson.Destination ?? ""}} }, null, packageJson.IsTrustedSource, request); } request.Debug("Calling '{0}' provider to install the package '{1}.{2}'", provider.Name, packageJson.Name, packageJson.Version); var installing = provider.InstallPackage(packages[0], installRequest); if (installing == null || !installing.Any()) { request.Verbose(Resources.Messages.NumberOfPackagesRecevied, 0, provider.Name, "InstallPackage"); request.Warning(Resources.Messages.FailToInstallPackage, Constants.ProviderName, packages[0].Name); return; } int packagesRecevied = 0; foreach (var i in installing) { request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename); if (request.IsCanceled) { installing.Cancel(); } else { request.Verbose(Resources.Messages.SuccessfullyInstalled, "{0}.{1}".format(packageJson.Name, packageJson.Version)); //load provider if (packageJson.IsPackageProvider) { //Per provider development guidance: provider name and module name should be the same otherwise we can not import it. request.PackageManagementService.ImportPackageProvider(request, packageJson.Name, null, null, null, isRooted: false, force: false); } } packagesRecevied++; } request.Verbose(Resources.Messages.NumberOfPackagesRecevied, packagesRecevied, provider.Name, "install-package"); }
protected bool IsPackageInVersionRange(SoftwareIdentity pkg) { if (RequiredVersion != null && SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, RequiredVersion) != 0) { return false; } if (MinimumVersion != null && SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, MinimumVersion) < 0) { return false; } if (MaximumVersion != null && SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, MaximumVersion) > 0) { return false; } return true; }
protected virtual void ProcessPackage(SoftwareIdentity package) { // Check for duplicates if (!IsDuplicate(package)) { WriteObject(package); } }
private string GetSoftwareIdentityTypeName(SoftwareIdentity package) { if(_initializedTypeName) { return _softwareIdentityTypeName; } //check if a user specifies -source with a long source name such as http://www.powershellgallery.com/api/v2, // if so we will choose the longsource column format. if (!UseDefaultSourceFormat) { _softwareIdentityTypeName += "#DisplayLongSourceName"; _hasTypeNameChanged = true; } //provider has the "DisplayCulture" in the Get-DynamicOption() if (IsDisplayCulture) { _softwareIdentityTypeName += "#DisplayCulture"; _hasTypeNameChanged = true; } //provider defines the 'DisplayLongName' feature in the Get-Feature() if (package != null && (package.Provider != null && (package.Provider.Features != null && package.Provider.Features.ContainsKey("DisplayLongName")))) { _softwareIdentityTypeName += "#DisplayLongName"; _hasTypeNameChanged = true; } _initializedTypeName = true; return _softwareIdentityTypeName; }
/// <summary> /// This method is used for customizing the format of the OneGet *-Package output display. /// </summary> /// <param name="package"></param> /// <returns></returns> protected object AddPropertyToSoftwareIdentity(SoftwareIdentity package) { // Use the default output format if a user does not provide the -providername property, e.g. find-package if (package == null || (!_isUserSpecifyOneProviderName && !IsDisplayCulture && UseDefaultSourceFormat)) { return package; } // Customize the output format var typeName = GetSoftwareIdentityTypeName(package); // For the find-package -providername nuget case, we can return right away. if (!_hasTypeNameChanged) { return package; } var swidTagAsPsobj = PSObject.AsPSObject(package); var noteProperty = new PSNoteProperty("PropertyOfSoftwareIdentity", "PropertyOfSoftwareIdentity"); swidTagAsPsobj.Properties.Add(noteProperty, true); swidTagAsPsobj.TypeNames.Insert(0, typeName); return swidTagAsPsobj; }
/// <summary> /// Validate if the package is a provider package. /// </summary> /// <param name="package"></param> /// <returns></returns> protected bool ValidatePackageProvider(SoftwareIdentity package) { //no need to filter on the packages from the bootstrap site as only providers will be published out there. if (package.ProviderName.EqualsIgnoreCase("Bootstrap")) { return true; } //get the tags info from the package's swid var tags = package.Metadata["tags"].ToArray(); //Check if the provider has provider tags var found = false; foreach (var filter in ProviderFilters) { found = false; if (tags.Any(tag => tag.ContainsIgnoreCase(filter))) { found = true; } else { break; } } return found; }
private static void InstallPackageReference(PackageJson package, PackageSourceListRequest request, SoftwareIdentity[] packages) { var installRequest = PackageSourceListRequest.ExtendRequest( new Dictionary<string, string[]> { {"Destination", new[] {package.Destination ?? ""}} }, new[] { package.Source ?? "" }, package.IsTrustedSource, request); var provider = PackageSourceListRequest.FindProvider(request, package.Type, installRequest, true); if (provider == null) { return; } var installing = provider.InstallPackage(packages[0], installRequest); foreach (var i in installing) { request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename); if (request.IsCanceled) { installing.Cancel(); } } }
protected bool IsDuplicate(SoftwareIdentity package) { // todo: add duplicate checking (need canonical ids) return false; }
protected override void ProcessPackage(string query, SoftwareIdentity package) { // mark down that we found something for that query _resultsPerName.GetOrAdd(query, () => new List<SoftwareIdentity>()).Add(package); }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { if (WhatIf) { // grab the dependencies and return them *first* foreach (var dep in package.Dependencies) { // note: future work may be needed if the package sources currently selected by the user don't // contain the dependencies. var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this); foreach (var depPackage in dependendcies) { ProcessPackage(depPackage.Provider, searchKey.Select(each => each + depPackage.Name).ToArray(), depPackage); } } } base.ProcessPackage(provider, searchKey, package); }
protected virtual void ProcessPackage(SoftwareIdentity package) { // Check for duplicates if (!IsDuplicate(package)) { // Display the SoftwareIdentity object in a format: Name, Version, Source and Provider var swidTagAsPsobj = PSObject.AsPSObject(package); var noteProperty = new PSNoteProperty("PropertyOfSoftwareIdentity", "PropertyOfSoftwareIdentity"); swidTagAsPsobj.Properties.Add(noteProperty, true); swidTagAsPsobj.TypeNames.Insert(0, _newSoftwareIdentityTypeName); WriteObject(swidTagAsPsobj); } }
protected virtual void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { foreach (var key in searchKey) { _resultsPerName.GetOrSetIfDefault(key, () => new List<SoftwareIdentity>()).Add(package); } }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { Debug("Calling ProcessPackage SearchKey = '{0}' and provider name ='{1}'", searchKey, package.ProviderName); try { base.ProcessPackage(provider, searchKey, package); // output to console WriteObject(package); if (IncludeDependencies) { var missingDependencies = new HashSet<string>(); foreach (var dep in package.Dependencies) { var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this); var depPkg = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault(); if (depPkg == null) { missingDependencies.Add(dep); Warning(Constants.Messages.UnableToFindDependencyPackage, dep); } else { ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg); } } if (missingDependencies.Any()) { Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma()); } } } catch (Exception ex) { Debug("Calling ProcessPackage {0}", ex.Message); } }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { ProcessPackage(provider, searchKey, package, IncludeDependencies ? new HashSet<string>() : null); }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { // if provider does not implement downloadpackage throw error saying that save-package is not implemented by provider if (!provider.IsMethodImplemented("DownloadPackage")) { Error(Constants.Errors.MethodNotImplemented, provider.ProviderName, "Save-Package"); } base.ProcessPackage(provider, searchKey, package); // if we do save-package jquery -path C:\test then savepath would be C:\test var savePath = SaveFileName(package.PackageFilename); bool mainPackageDownloaded = false; if (!string.IsNullOrWhiteSpace(savePath)) { // let the provider handles everything if (ShouldProcess(savePath, FormatMessageString(Resources.Messages.SavePackage)).Result) { foreach (var downloadedPkg in provider.DownloadPackage(package, savePath, this.ProviderSpecific(provider)).CancelWhen(CancellationEvent.Token)) { if (IsCanceled) { Error(Constants.Errors.ProviderFailToDownloadFile, downloadedPkg.PackageFilename, provider.ProviderName); return; } // check whether main package is downloaded; if (string.Equals(downloadedPkg.CanonicalId, package.CanonicalId, StringComparison.OrdinalIgnoreCase)) { mainPackageDownloaded = true; } WriteObject(downloadedPkg); } } } if (!mainPackageDownloaded) { Error(Constants.Errors.ProviderFailToDownloadFile, package.PackageFilename, provider.ProviderName); return; } }
// Performs a reverse lookup from Package Source Location -> Source Name for a Provider private string GetPackageSourceNameOrLocation(SoftwareIdentity package) { // Default to Source Location Url string packageSourceName = package.Source; // Get the package provider object var packageProvider = SelectProviders(package.ProviderName).ReEnumerable(); if (!packageProvider.Any()) { return packageSourceName; } // For any issues with reverse lookup (SourceLocation -> SourceName), return Source Location Url try { var packageSource = packageProvider.Select(each => each.ResolvePackageSources(this.SuppressErrorsAndWarnings(IsProcessing)).Where(source => source.IsRegistered && (source.Location.EqualsIgnoreCase(package.Source)))).ReEnumerable(); if (packageSource.Any()) { var pkgSource = packageSource.FirstOrDefault(); if (pkgSource != null) { var source = pkgSource.FirstOrDefault(); if (source != null) { packageSourceName = source.Name; } } } } catch (Exception e) { e.Dump(); } return packageSourceName; }
protected override bool EnsurePackageIsProvider(SoftwareIdentity package) { //Make sure the package is a provider package return ValidatePackageProvider(package); }
private bool ImportProvider(SoftwareIdentity[] list) { Verbose("Importing the package provider {0}", Name.JoinWithComma()); //after the provider gets installed, we are trying to load it var providers = list.SelectMany(each => PackageManagementService.ImportPackageProvider(this.SuppressErrorsAndWarnings(IsProcessing), each.Name, each.Version.ToVersion(), null, null, false, true)).ToArray(); if (providers.Any()) { Verbose(Resources.Messages.ProviderImported, providers.Select(e => e.ProviderPath).JoinWithComma()); return true; } else { Warning(Resources.Messages.ProviderNameDifferentFromPackageName, Name.JoinWithComma()); } return false; }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { if (WhatIf) { // grab the dependencies and return them *first* bool hasDependencyLoop = false; var dependencies = GetDependenciesToInstall(package, ref hasDependencyLoop); if (!hasDependencyLoop) { foreach (var dependency in dependencies) { base.ProcessPackage(provider, searchKey.Select(each => each+dependency.Name).ToArray(), dependency); } } } base.ProcessPackage(provider, searchKey, package); }
private IEnumerable<SoftwareIdentity> GetDependenciesToInstall(SoftwareIdentity package, ref bool hasDependencyLoop) { // No dependency if (package.Dependencies == null || package.Dependencies.Count() == 0) { return Enumerable.Empty<SoftwareIdentity>(); } // Returns list of dependency to be installed in the correct order that we should install them List<SoftwareIdentity> dependencyToBeInstalled = new List<SoftwareIdentity>(); HashSet<SoftwareIdentity> permanentlyMarked = new HashSet<SoftwareIdentity>(new SoftwareIdentityNameVersionComparer()); HashSet<SoftwareIdentity> temporarilyMarked = new HashSet<SoftwareIdentity>(new SoftwareIdentityNameVersionComparer()); // checks that there are no dependency loop hasDependencyLoop = !DepthFirstVisit(package, temporarilyMarked, permanentlyMarked, dependencyToBeInstalled); if (!hasDependencyLoop) { // remove the last item of the list because that is the package itself dependencyToBeInstalled.RemoveAt(dependencyToBeInstalled.Count - 1); return dependencyToBeInstalled; } // there are dependency loop. return Enumerable.Empty<SoftwareIdentity>(); }
protected override void ProcessPackage(SoftwareIdentity package) { if (null != package && !package.CanonicalId.IsNullOrEmpty()) { // mark down that we found something for that query // Need a identifier for maintaining the list of packages to uninstall in a dictionary. // Canonical ID consists of packagename, version, repo which is unique _resultsPerName.GetOrAdd(package.CanonicalId, () => new List<SoftwareIdentity>()).Add(package); } }
/// <summary> /// Do a dfs visit. returns false if a cycle is encountered. Add the packageItem to the list at the end of each visit /// </summary> /// <param name="packageItem"></param> /// <param name="dependencyToBeInstalled"></param> /// <param name="permanentlyMarked"></param> /// <param name="temporarilyMarked"></param> /// <returns></returns> internal bool DepthFirstVisit(SoftwareIdentity packageItem, HashSet<SoftwareIdentity> temporarilyMarked, HashSet<SoftwareIdentity> permanentlyMarked, List<SoftwareIdentity> dependencyToBeInstalled) { // dependency loop detected because the element is temporarily marked if (temporarilyMarked.Contains(packageItem)) { return false; } // this is permanently marked. So we don't have to visit it. // This is to resolve a case where we have: A->B->C and A->C. Then we need this when we visit C again from either B or A. if (permanentlyMarked.Contains(packageItem)) { return true; } // Mark this node temporarily so we can detect cycle. temporarilyMarked.Add(packageItem); // Visit the dependency foreach (var dependency in packageItem.Dependencies) { var dependencies = PackageManagementService.FindPackageByCanonicalId(dependency, this); var depPkg = dependencies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault(); if (!DepthFirstVisit(depPkg, temporarilyMarked, permanentlyMarked, dependencyToBeInstalled)) { // if dfs returns false then we have encountered a loop return false; } // otherwise visit the next dependency } // Add the package to the list so we can install later dependencyToBeInstalled.Add(packageItem); // Done with this node so mark it permanently permanentlyMarked.Add(packageItem); // Unmark it temporarily temporarilyMarked.Remove(packageItem); return true; }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { base.ProcessPackage(provider, searchKey, package); var savePath = SaveFileName(package.PackageFilename); if (savePath.FileExists()) { if (Force) { savePath.TryHardToDelete(); if (savePath.FileExists()) { Error(Constants.Errors.UnableToOverwrite, savePath); return; } } else { Error(Constants.Errors.PackageFileExists, savePath); return; } } // if we have a valid path, make a local copy of the file. if (!string.IsNullOrWhiteSpace(savePath)) { if (ShouldProcess(savePath, Constants.Messages.SavePackage).Result) { provider.DownloadPackage(package, SaveFileName(savePath), this.ProviderSpecific(provider)).Wait(); if (File.Exists(savePath)) { package.FullPath = savePath; } } // return the object to the caller. WriteObject(package); } }
protected virtual bool EnsurePackageIsProvider(SoftwareIdentity package) { return true; }