/// <summary> /// Parse package identity from path to .nupkg file, such as https://az320820.vo.msecnd.net/packages/microsoft.aspnet.mvc.4.0.20505.nupkg /// </summary> /// <param name="sourceUrl"></param> /// <returns></returns> private PackageIdentity ParsePackageIdentityFromNupkgPath(string path, string divider) { if (!string.IsNullOrEmpty(path)) { string lastPart = path.Split(new string[] { divider }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault(); lastPart = lastPart.Replace(Constants.PackageExtension, ""); string[] parts = lastPart.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); StringBuilder builderForId = new StringBuilder(); StringBuilder builderForVersion = new StringBuilder(); foreach (string s in parts) { int n; bool isNumeric = int.TryParse(s, out n); // Take pre-release versions such as EntityFramework.6.1.3-beta1 into account. if ((!isNumeric || string.IsNullOrEmpty(builderForId.ToString())) && string.IsNullOrEmpty(builderForVersion.ToString())) { builderForId.Append(s); builderForId.Append("."); } else { builderForVersion.Append(s); builderForVersion.Append("."); } } NuGetVersion nVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(builderForVersion.ToString().TrimEnd('.')); // Set _allowPrerelease to true if nVersion is prerelease version. if (nVersion != null && nVersion.IsPrerelease) { _allowPrerelease = true; } return(new PackageIdentity(builderForId.ToString().TrimEnd('.'), nVersion)); } return(null); }
/// <summary> /// Install package by Id /// </summary> /// <param name="project"></param> /// <param name="packageId"></param> /// <param name="resolutionContext"></param> /// <param name="projectContext"></param> /// <param name="isPreview"></param> /// <param name="isForce"></param> /// <param name="uninstallContext"></param> /// <returns></returns> protected async Task InstallPackageByIdAsync(NuGetProject project, string packageId, ResolutionContext resolutionContext, INuGetProjectContext projectContext, bool isPreview, bool isForce = false, UninstallationContext uninstallContext = null) { List <NuGetProjectAction> actions = new List <NuGetProjectAction>(); // For Install-Package -Force if (isForce) { PackageReference installedReference = project.GetInstalledPackagesAsync(CancellationToken.None).Result.Where(p => StringComparer.OrdinalIgnoreCase.Equals(packageId, p.PackageIdentity.Id)).FirstOrDefault(); if (installedReference != null) { actions.AddRange(await PackageManager.PreviewUninstallPackageAsync(project, packageId, uninstallContext, projectContext, CancellationToken.None)); } NuGetVersion nVersion = PowerShellCmdletsUtility.GetLastestVersionForPackageId(ActiveSourceRepository, packageId, project, resolutionContext.IncludePrerelease); if (nVersion != null) { PackageIdentity identityToInstall = new PackageIdentity(packageId, nVersion); NuGetProjectAction installAction = NuGetProjectAction.CreateInstallProjectAction(identityToInstall, ActiveSourceRepository); actions.Add(installAction); } } else { actions.AddRange(await PackageManager.PreviewInstallPackageAsync(project, packageId, resolutionContext, projectContext, ActiveSourceRepository, null, CancellationToken.None)); } if (isPreview) { PreviewNuGetPackageActions(actions); } else { await PackageManager.ExecuteNuGetProjectActionsAsync(project, actions, this, CancellationToken.None); } }
protected override void ProcessRecordCore() { Preprocess(); // If Remote & Updates set of parameters are not specified, list the installed package. if (!UseRemoteSource) { CheckForSolutionOpen(); Dictionary <NuGetProject, IEnumerable <PackageReference> > packagesToDisplay = GetInstalledPackages(Projects, Filter, Skip, First).Result; WriteInstalledPackages(packagesToDisplay); } else { if (PageSize != 0) { _enablePaging = true; First = PageSize; } else if (First == 0) { First = DefaultFirstValue; } if (Filter == null) { Filter = string.Empty; } // Find avaiable packages from the current source and not taking targetframeworks into account. if (UseRemoteSourceOnly) { IEnumerable <PSSearchMetadata> remotePackages = GetPackagesFromRemoteSource(Filter, Enumerable.Empty <string>(), IncludePrerelease.IsPresent, Skip, First); WritePackagesFromRemoteSource(remotePackages, true); if (_enablePaging) { WriteMoreRemotePackagesWithPaging(remotePackages); } } // Get package udpates from the current source and taking targetframeworks into account. else { CheckForSolutionOpen(); foreach (NuGetProject project in Projects) { IEnumerable <string> frameworks = PowerShellCmdletsUtility.GetProjectTargetFrameworks(project); IEnumerable <PackageReference> installedPackages = project.GetInstalledPackagesAsync(CancellationToken.None).Result; Dictionary <PSSearchMetadata, NuGetVersion> remoteUpdates = GetPackageUpdatesFromRemoteSource(installedPackages, frameworks, IncludePrerelease.IsPresent, Skip, First); WriteUpdatePackagesFromRemoteSource(remoteUpdates, project); } } } }
/// <summary> /// Preview update actions for single package /// </summary> /// <returns></returns> private async Task PreviewAndExecuteUpdateActionsForSinglePackage() { var actions = Enumerable.Empty <NuGetProjectAction>(); using (var sourceCacheContext = new SourceCacheContext()) { var resolutionContext = new ResolutionContext( GetDependencyBehavior(), _allowPrerelease, ShouldAllowDelistedPackages(), DetermineVersionConstraints(), new GatherCache(), sourceCacheContext); // PackageReference projects don't support `Update-Package -Reinstall`. List <NuGetProject> applicableProjects = GetApplicableProjectsAndWarnForRest(Projects); // If -Version switch is specified if (!string.IsNullOrEmpty(Version)) { actions = await PackageManager.PreviewUpdatePackagesAsync( new PackageIdentity(Id, PowerShellCmdletsUtility.GetNuGetVersionFromString(Version)), applicableProjects, resolutionContext, this, PrimarySourceRepositories, EnabledSourceRepositories, Token); } else { actions = await PackageManager.PreviewUpdatePackagesAsync( Id, applicableProjects, resolutionContext, this, PrimarySourceRepositories, EnabledSourceRepositories, Token); } if (!actions.Any()) { _status = NuGetOperationStatus.NoOp; } else { _packageCount = actions.Select( action => action.PackageIdentity.Id).Distinct(StringComparer.OrdinalIgnoreCase).Count(); } await ExecuteActions(actions, sourceCacheContext); } }
/// <summary> /// Parse user input for -Version switch. /// If Version is given as prerelease versions, automatically append -Prerelease /// </summary> private void ParseUserInputForVersion() { if (!string.IsNullOrEmpty(Version)) { _nugetVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(Version); if (_nugetVersion.IsPrerelease) { _versionSpecifiedPrerelease = true; } } _allowPrerelease = IncludePrerelease.IsPresent || _versionSpecifiedPrerelease; }
/// <summary> /// Preview update actions for single package /// </summary> /// <param name="project"></param> /// <returns></returns> private async Task PreviewAndExecuteUpdateActionsforSinglePackage(NuGetProject project) { var token = CancellationToken.None; PackageReference installedPackage = (await project.GetInstalledPackagesAsync(token)) .Where(p => string.Equals(p.PackageIdentity.Id, Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); // If package Id exists in Packages folder but is not actually installed to the current project, throw. if (installedPackage == null) { Log(MessageLevel.Error, string.Format(Resources.PackageNotInstalledInAnyProject, Id)); } else { // If -Version switch is specified if (!string.IsNullOrEmpty(Version)) { PackageIdentity update = GetUpdatePackageIdentityWhenVersionSpecified(project, installedPackage); if (update != null) { // Update by package identity await InstallPackageByIdentityAsync(project, update, ResolutionContext, this, WhatIf.IsPresent, Reinstall.IsPresent, UninstallContext); } else { Log(MessageLevel.Info, string.Format(Resources.Cmdlet_NoPackageUpdates, project.GetMetadata <string>(NuGetProjectMetadataKeys.Name))); } } else { if (Reinstall.IsPresent) { // Update-Package Id -Reinstall PackageIdentity identity = installedPackage.PackageIdentity; await InstallPackageByIdentityAsync(project, identity, ResolutionContext, this, WhatIf.IsPresent, Reinstall.IsPresent, UninstallContext); } else { // Update-Package Id NormalizePackageId(project); NuGetVersion latestVersion = PowerShellCmdletsUtility.GetLastestVersionForPackageId(ActiveSourceRepository, Id, project, _allowPrerelease); if (latestVersion > installedPackage.PackageIdentity.Version) { await InstallPackageByIdAsync(project, Id, ResolutionContext, this, WhatIf.IsPresent, Reinstall.IsPresent, UninstallContext); } else { Log(MessageLevel.Info, string.Format(Resources.Cmdlet_NoPackageUpdates, project.GetMetadata <string>(NuGetProjectMetadataKeys.Name))); } } } } }
/// <summary> /// Parse user input for -Version switch /// </summary> private void ParseUserInputForVersion() { if (!string.IsNullOrEmpty(Version)) { // If Version is prerelease, automatically allow prerelease (i.e. append -Prerelease switch). _nugetVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(Version); if (_nugetVersion.IsPrerelease) { _versionSpecifiedPrerelease = true; } } _allowPrerelease = IncludePrerelease.IsPresent || _versionSpecifiedPrerelease; }
/// <summary> /// Preview update actions for single package /// </summary> /// <returns></returns> private async Task PreviewAndExecuteUpdateActionsForSinglePackage() { var actions = Enumerable.Empty <NuGetProjectAction>(); using (var sourceCacheContext = new SourceCacheContext()) { var resolutionContext = new ResolutionContext( GetDependencyBehavior(), _allowPrerelease, false, DetermineVersionConstraints(), new GatherCache(), sourceCacheContext); // If -Version switch is specified if (!string.IsNullOrEmpty(Version)) { actions = await PackageManager.PreviewUpdatePackagesAsync( new PackageIdentity(Id, PowerShellCmdletsUtility.GetNuGetVersionFromString(Version)), Projects, resolutionContext, this, PrimarySourceRepositories, EnabledSourceRepositories, Token); } else { actions = await PackageManager.PreviewUpdatePackagesAsync( Id, Projects, resolutionContext, this, PrimarySourceRepositories, EnabledSourceRepositories, Token); } if (!actions.Any()) { _status = NuGetOperationStatus.NoOp; } else { _packageCount = actions.Select( action => action.PackageIdentity.Id).Distinct().Count(); } await ExecuteActions(actions, sourceCacheContext); } }
/// <summary> /// Output package updates to current project(s) found from the current remote source /// </summary> /// <param name="packagesToDisplay"></param> private async Task WriteUpdatePackagesFromRemoteSourceAsync(NuGetProject project) { var frameworks = PowerShellCmdletsUtility.GetProjectTargetFrameworks(project); var installedPackages = await project.GetInstalledPackagesAsync(Token); VersionType versionType; if (CollapseVersions) { versionType = VersionType.Latest; } else { versionType = VersionType.Updates; } var projectHasUpdates = false; var metadataTasks = installedPackages.Select(installedPackage => Task.Run(async() => { var metadata = await GetLatestPackageFromRemoteSourceAsync(installedPackage.PackageIdentity, IncludePrerelease.IsPresent); if (metadata != null) { await metadata.GetVersionsAsync(); } return(metadata); })); foreach (var task in installedPackages.Zip(metadataTasks, (p, t) => Tuple.Create(t, p))) { var metadata = await task.Item1; if (metadata != null) { var package = PowerShellUpdatePackage.GetPowerShellPackageUpdateView(metadata, task.Item2.PackageIdentity.Version, versionType, project); var versions = package.Versions ?? Enumerable.Empty <NuGetVersion>(); if (versions.Any()) { projectHasUpdates = true; WriteObject(package); } } } if (!projectHasUpdates) { LogCore(ProjectManagement.MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_NoPackageUpdates, project.GetMetadata <string>(NuGetProjectMetadataKeys.Name))); } }
/// <summary> /// Returns single package identity for resolver when Id is specified /// </summary> /// <returns></returns> private async Task <PackageIdentity> GetPackageIdentity() { PackageIdentity identity = null; if (!string.IsNullOrEmpty(Version)) { NuGetVersion nVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(Version); identity = new PackageIdentity(Id, nVersion); } else { identity = (await Project.GetInstalledPackagesAsync(CancellationToken.None)) .Where(p => string.Equals(p.PackageIdentity.Id, Id, StringComparison.OrdinalIgnoreCase)) .Select(v => v.PackageIdentity).FirstOrDefault(); } return(identity); }
/// <summary> /// Preview update actions for single package /// </summary> /// <returns></returns> private async Task PreviewAndExecuteUpdateActionsForSinglePackage() { var actions = Enumerable.Empty <NuGetProjectAction>(); // If -Version switch is specified if (!string.IsNullOrEmpty(Version)) { actions = await PackageManager.PreviewUpdatePackagesAsync( new PackageIdentity(Id, PowerShellCmdletsUtility.GetNuGetVersionFromString(Version)), Projects, ResolutionContext, this, PrimarySourceRepositories, EnabledSourceRepositories, Token); } else { actions = await PackageManager.PreviewUpdatePackagesAsync( Id, Projects, ResolutionContext, this, PrimarySourceRepositories, EnabledSourceRepositories, Token); } if (!actions.Any()) { _status = NuGetOperationStatus.NoOp; } else { _packageCount = actions.Select( action => action.PackageIdentity.Id).Distinct().Count(); } await ExecuteActions(actions); }
/// <summary> /// Get update identity for a package that is installed to a project. Used for Update-Package Id -Version. /// </summary> /// <param name="installedPackage"></param> /// <param name="project"></param> /// <param name="includePrerelease"></param> /// <param name="isSafe"></param> /// <param name="version"></param> /// <param name="isEnum"></param> /// <param name="dependencyEnum"></param> /// <returns></returns> protected PackageIdentity GetPackageUpdate(PackageReference installedPackage, NuGetProject project, bool includePrerelease, bool isSafe, string version = null, bool isEnum = false, DependencyBehavior dependencyEnum = DependencyBehavior.Lowest) { PackageIdentity identity = null; if (isSafe) { identity = PowerShellCmdletsUtility.GetSafeUpdateForPackageIdentity(ActiveSourceRepository, installedPackage.PackageIdentity, project, includePrerelease, installedPackage.PackageIdentity.Version); } else if (isEnum) { identity = PowerShellCmdletsUtility.GetUpdateForPackageByDependencyEnum(ActiveSourceRepository, installedPackage.PackageIdentity, project, dependencyEnum, includePrerelease); } else { NuGetVersion nVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(version); identity = new PackageIdentity(installedPackage.PackageIdentity.Id, nVersion); } // Since package downgrade is allowed, we will not check nVersion > installedPackage.PackageIdentity.Version here. return(identity); }
/// <summary> /// Preview update actions for single package /// </summary> /// <param name="project"></param> /// <returns></returns> private async Task PreviewAndExecuteUpdateActionsforSinglePackage(NuGetProject project) { var installedPackage = (await project.GetInstalledPackagesAsync(Token)) .FirstOrDefault(p => string.Equals(p.PackageIdentity.Id, Id, StringComparison.OrdinalIgnoreCase)); if (installedPackage != null) { // set _installed to true, if package to update is installed. _isPackageInstalled = true; var actions = Enumerable.Empty <NuGetProjectAction>(); // If -Version switch is specified if (!string.IsNullOrEmpty(Version)) { actions = await PackageManager.PreviewUpdatePackagesAsync( new PackageIdentity(installedPackage.PackageIdentity.Id, PowerShellCmdletsUtility.GetNuGetVersionFromString(Version)), project, ResolutionContext, this, PrimarySourceRepositories, EnabledSourceRepositories, Token); } else { actions = await PackageManager.PreviewUpdatePackagesAsync( installedPackage.PackageIdentity.Id, project, ResolutionContext, this, PrimarySourceRepositories, EnabledSourceRepositories, Token); } await ExecuteActions(project, actions); } }
/// <summary> /// Parse user input for -Version switch /// </summary> private void ParseUserInputForVersion() { if (!string.IsNullOrEmpty(Version)) { DependencyBehavior updateVersion; IsVersionEnum = Enum.TryParse <DependencyBehavior>(Version, true, out updateVersion); if (IsVersionEnum) { _updateVersionEnum = updateVersion; } // If Version is prerelease, automatically allow prerelease (i.e. append -Prerelease switch). else { _nugetVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(Version); if (_nugetVersion.IsPrerelease) { _versionSpecifiedPrerelease = true; } } } _allowPrerelease = IncludePrerelease.IsPresent || _versionSpecifiedPrerelease; }
protected override void ProcessRecordCore() { Preprocess(); IPackageSearchMetadata package = null; try { var metadata = NuGetUIThreadHelper.JoinableTaskFactory.Run(() => GetPackagesFromRemoteSourceAsync(Id, IncludePrerelease.IsPresent)); if (!string.IsNullOrEmpty(Version)) { NuGetVersion nVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(Version); metadata = metadata.Where(p => p.Identity.Version == nVersion); } package = metadata .OrderByDescending(v => v.Identity.Version) .FirstOrDefault(); } catch { } if (package != null && package.Identity != null) { Uri targetUrl = null; if (License.IsPresent) { targetUrl = package.LicenseUrl; } else if (ReportAbuse.IsPresent) { targetUrl = package.ReportAbuseUrl; } else { targetUrl = package.ProjectUrl; } if (targetUrl != null) { OpenUrl(targetUrl); if (PassThru.IsPresent) { WriteObject(targetUrl); } } else { WriteError(String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_UrlMissing, package.Identity.Id + " " + package.Identity.Version)); } } else { // show appropriate error message depending on whether Version parameter is set. if (string.IsNullOrEmpty(Version)) { WriteError(String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_PackageIdNotFound, Id)); } else { WriteError(String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_PackageIdAndVersionNotFound, Id, Version)); } } }
protected override void ProcessRecordCore() { Preprocess(); IPackageSearchMetadata package = null; try { var metadata = Task.Run(() => GetPackagesFromRemoteSourceAsync(Id, IncludePrerelease.IsPresent)).Result; if (!string.IsNullOrEmpty(Version)) { NuGetVersion nVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(Version); metadata = metadata.Where(p => p.Identity.Version == nVersion); } package = metadata .OrderByDescending(v => v.Identity.Version) .FirstOrDefault(); } catch { } if (package != null && package.Identity != null) { Uri targetUrl = null; if (License.IsPresent) { targetUrl = package.LicenseUrl; } else if (ReportAbuse.IsPresent) { targetUrl = package.ReportAbuseUrl; } else { targetUrl = package.ProjectUrl; } if (targetUrl != null) { OpenUrl(targetUrl); if (PassThru.IsPresent) { WriteObject(targetUrl); } } else { WriteError(String.Format( CultureInfo.CurrentCulture, "The package '{0}' does not provide the requested URL.", package.Identity.Id + " " + package.Identity.Version)); } } else { // show appropriate error message depending on whether Version parameter is set. if (string.IsNullOrEmpty(Version)) { WriteError(String.Format( CultureInfo.CurrentCulture, "Package with the Id '{0}' is not found in the specified source.", Id)); } else { WriteError(String.Format( CultureInfo.CurrentCulture, "Package with the Id '{0}' and version '{1}' is not found in the specified source.", Id, Version)); } } }
protected override void ProcessRecordCore() { Preprocess(); UIPackageMetadata package = null; try { UIMetadataResource resource = ActiveSourceRepository.GetResource <UIMetadataResource>(); Task <IEnumerable <UIPackageMetadata> > task = resource.GetMetadata(Id, IncludePrerelease.IsPresent, false, CancellationToken.None); var metadata = task.Result; if (!string.IsNullOrEmpty(Version)) { NuGetVersion nVersion = PowerShellCmdletsUtility.GetNuGetVersionFromString(Version); metadata = metadata.Where(p => p.Identity.Version == nVersion); } package = metadata.Where(p => string.Equals(p.Identity.Id, Id, StringComparison.OrdinalIgnoreCase)) .OrderByDescending(v => v.Identity.Version) .FirstOrDefault(); } catch (Exception) { } if (package != null) { Uri targetUrl = null; if (License.IsPresent) { targetUrl = package.LicenseUrl; } else if (ReportAbuse.IsPresent) { targetUrl = package.ReportAbuseUrl; } else { targetUrl = package.ProjectUrl; } if (targetUrl != null) { OpenUrl(targetUrl); if (PassThru.IsPresent) { WriteObject(targetUrl); } } else { WriteError(String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_UrlMissing, Id + " " + Version)); } } else { // show appropriate error message depending on whether Version parameter is set. if (string.IsNullOrEmpty(Version)) { WriteError(String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_PackageIdNotFound, Id)); } else { WriteError(String.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_PackageIdAndVersionNotFound, Id, Version)); } } }