Exemple #1
0
        private void SetComboboxCurrentVersion(string comboboxText, IEnumerable <NuGetVersion> versions)
        {
            NuGetVersion matchVersion = null;
            VersionRange userRange    = null;

            // Get the best version from the range if the user typed a custom version
            bool userTypedAValidVersionRange = VersionRange.TryParse(comboboxText, out userRange);

            if (userTypedAValidVersionRange)
            {
                matchVersion = userRange.FindBestMatch(versions);
            }

            if (matchVersion == null && userRange == null)
            {
                return;
            }

            // If the selected version is not the correct one, deselect a version so Install/Update button is disabled.
            if (_versions.SelectedIndex != -1 && matchVersion?.ToString() != _versions.Items[_versions.SelectedIndex].ToString())
            {
                _versions.SelectedIndex = -1;
            }

            // Automatically select the item when the input or custom range text matches it
            for (int i = 0; i < _versions.Items.Count; i++)
            {
                DisplayVersion currentItem = _versions.Items[i] as DisplayVersion;
                if (currentItem != null && (comboboxText == _versions.Items[i].ToString() || _versions.Items[i].ToString() == matchVersion?.ToString()))
                {
                    _versions.SelectedIndex = i; // This is the "select" effect in the dropdown
                    PackageDetailControlModel.SelectedVersion = new DisplayVersion(userRange, matchVersion, additionalInfo: null);
                }
            }
        }
Exemple #2
0
        public static InstalledPackage GetGlobalInstalledPackage(
            string packageId,
            [CanBeNull] VersionRange versionRange,
            [CanBeNull] string packagesConfigFile,
            bool?includePrereleases = null)
        {
            packageId = packageId.ToLowerInvariant();
            var packagesDirectory = GetPackagesDirectory(packagesConfigFile);

            if (packagesDirectory == null)
            {
                return(null);
            }

            var packagesDirectoryInfo = new DirectoryInfo(packagesDirectory);
            var packages = packagesDirectoryInfo
                           .GetDirectories(packageId)
                           .SelectMany(x => x.GetDirectories())
                           .SelectMany(x => x.GetFiles($"{packageId}*.nupkg"))
                           .Concat(packagesDirectoryInfo
                                   .GetDirectories($"{packageId}*")
                                   .SelectMany(x => x.GetFiles($"{packageId}*.nupkg")))
                           .Select(x => x.FullName);

            var candidatePackages = packages.Select(x => new InstalledPackage(x))
                                    // packages can contain false positives due to present/missing version specification
                                    .Where(x => x.Id.EqualsOrdinalIgnoreCase(packageId))
                                    .Where(x => !x.Version.IsPrerelease || !includePrereleases.HasValue || includePrereleases.Value)
                                    .OrderByDescending(x => x.Version)
                                    .ToList();

            return(versionRange == null
                ? candidatePackages.FirstOrDefault()
                : candidatePackages.SingleOrDefault(x => x.Version == versionRange.FindBestMatch(candidatePackages.Select(y => y.Version))));
        }
Exemple #3
0
        private MockFeedPackage GetPackage(
            string packageId,
            VersionRange versionRange = null,
            FilePath?nugetConfig      = null)
        {
            var allPackages = _feeds
                              .Where(f =>
            {
                if (nugetConfig != null)
                {
                    return(ExcludeOtherFeeds(nugetConfig, f));
                }

                return(true);
            })
                              .SelectMany(f => f.Packages)
                              .Where(f => f.PackageId == packageId);

            var bestVersion = versionRange.FindBestMatch(allPackages.Select(p => NuGetVersion.Parse(p.Version)));

            var package = allPackages.Where(p => NuGetVersion.Parse(p.Version).Equals(bestVersion)).FirstOrDefault();

            if (package == null)
            {
                _reporter?.WriteLine($"Error: failed to restore package {packageId}.");
                throw new ToolPackageException(LocalizableStrings.ToolInstallationRestoreFailed);
            }

            return(package);
        }
        public string GetBestLockFilePath(string packageId, VersionRange versionRange, NuGetFramework framework)
        {
            if (versionRange == null)
            {
                throw new ArgumentNullException(nameof(versionRange));
            }

            if (framework == null)
            {
                throw new ArgumentNullException(nameof(framework));
            }

            var availableToolVersions = GetAvailableToolVersions(packageId);

            var bestVersion = versionRange.FindBestMatch(availableToolVersions);

            if (bestVersion == null)
            {
                throw new GracefulException(string.Format(
                                                LocalizableStrings.VersionForPackageCouldNotBeResolved,
                                                packageId));
            }

            return(GetLockFilePath(packageId, bestVersion, framework));
        }
        public static InstalledPackage GetGlobalInstalledPackage(
            string packageId,
            VersionRange versionRange = null,
            string packagesDirectory  = null,
            bool?includePrereleases   = null)
        {
            packageId         = packageId.ToLowerInvariant();
            packagesDirectory = packagesDirectory ?? GetPackagesDirectory(GetBuildPackagesConfigFile());

            var packagesDirectoryInfo = new DirectoryInfo(packagesDirectory);
            var packageFiles          = packagesDirectoryInfo
                                        .GetDirectories(packageId)
                                        .SelectMany(x => x.GetDirectories())
                                        .SelectMany(x => x.GetFiles($"{packageId}*.nupkg"))
                                        .Concat(packagesDirectoryInfo
                                                .GetDirectories($"{packageId}*")
                                                .SelectMany(x => x.GetFiles($"{packageId}*.nupkg")))
                                        .Select(x => x.FullName);

            var candidatePackages = packageFiles.Select(x => new InstalledPackage(x))
                                    .Where(x => x.Id.EqualsOrdinalIgnoreCase(packageId)) // packageFiles can contain wrong packages
                                    .Where(x => !x.Version.IsPrerelease || !includePrereleases.HasValue || includePrereleases.Value)
                                    .OrderByDescending(x => x.Version)
                                    .ToList();

            return(versionRange == null
                ? candidatePackages.FirstOrDefault()
                : candidatePackages.SingleOrDefault(x => x.Version == versionRange.FindBestMatch(candidatePackages.Select(y => y.Version))));
        }
Exemple #6
0
        public string GetBestLockFilePath(string packageId, VersionRange versionRange, NuGetFramework framework)
        {
            var availableToolVersions = GetAvailableToolVersions(packageId);

            var bestVersion = versionRange.FindBestMatch(availableToolVersions);

            return(GetLockFilePath(packageId, bestVersion, framework));
        }
Exemple #7
0
        private static bool MatchPackage(MockFeedPackage p, string packageId, VersionRange versionRange)
        {
            if (string.Compare(p.PackageId, packageId, StringComparison.CurrentCultureIgnoreCase) != 0)
            {
                return(false);
            }

            return(versionRange == null ||
                   versionRange.FindBestMatch(new[] { NuGetVersion.Parse(p.Version) }) != null);
        }
Exemple #8
0
        public void FloatRange_OutsideOfRangeOpen()
        {
            VersionRange range = VersionRange.Parse("[1.0.*, )");

            var versions = new List <NuGetVersion>()
            {
                NuGetVersion.Parse("0.1.0"),
                NuGetVersion.Parse("0.2.0"),
                NuGetVersion.Parse("1.0.0-alpha.2")
            };

            Assert.Null(range.FindBestMatch(versions));
        }
Exemple #9
0
        /// <summary>
        /// Returns the directory (packagesFolder/.tools/id/version for example) for the best matching version if any.
        /// </summary>
        /// <returns></returns>
        public string GetBestToolDirectoryPath(string packageId, VersionRange versionRange, NuGetFramework framework)
        {
            var availableToolVersions = GetAvailableToolVersions(packageId);

            var bestVersion = versionRange.FindBestMatch(availableToolVersions);

            if (bestVersion == null)
            {
                return(null);
            }

            return(GetToolDirectoryPath(packageId, bestVersion, framework));
        }
Exemple #10
0
        public void FloatingRange_FloatNoneBest()
        {
            VersionRange range = VersionRange.Parse("1.0.0");

            var versions = new List <NuGetVersion>()
            {
                NuGetVersion.Parse("1.0.0"),
                NuGetVersion.Parse("1.0.1"),
                NuGetVersion.Parse("2.0.0"),
            };

            Assert.Equal("1.0.0", range.FindBestMatch(versions).ToNormalizedString());
        }
        private BestVersionMatch GetBestVersionMatch(
            VersionRange versionRange,
            IReadOnlyList <NuGetVersion> inputVersions,
            HashSet <NuGetVersion> listed,
            bool showUnlisted)
        {
            var outputVersions = new List <VersionCompatibility>();
            var output         = new BestVersionMatch
            {
                VersionRange = versionRange,
                Versions     = outputVersions,
            };

            var remainingVersions = new List <NuGetVersion>(inputVersions);

            while (remainingVersions.Any())
            {
                var version = versionRange.FindBestMatch(remainingVersions);
                if (version == null)
                {
                    break;
                }

                var compatibility = new VersionCompatibility(
                    version,
                    isCompatible: true,
                    isListed: listed?.Contains(version));

                if (output.BestMatch == null)
                {
                    output.BestMatch = compatibility;
                    outputVersions.Add(compatibility);
                }
                else if (showUnlisted || compatibility.IsListed != false)
                {
                    outputVersions.Add(compatibility);
                }

                remainingVersions.Remove(version);
            }

            outputVersions.AddRange(remainingVersions
                                    .OrderBy(version => version)
                                    .Select(version => new VersionCompatibility(
                                                version,
                                                isCompatible: false,
                                                isListed: listed?.Contains(version)))
                                    .Where(version => showUnlisted || version.IsListed != false));

            return(output);
        }
Exemple #12
0
        private static async Task <bool> TryUpdateVersionAsync(
            XAttribute versionAttribute,
            string packageId,
            IEnumerable <PackageMetadataResource> packageMetadataResources,
            ILogger logger,
            SourceCacheContext cacheContext)
        {
            var currentVersion = NuGetVersion.Parse(versionAttribute.Value);
            var versionRange   = new VersionRange(
                currentVersion,
                new FloatRange(NuGetVersionFloatBehavior.Patch, currentVersion));

            var searchMetadatas = await Task.WhenAll(
                packageMetadataResources.Select(async pmr => await pmr.GetMetadataAsync(
                                                    packageId,
                                                    includePrerelease: false,
                                                    includeUnlisted: true, // Microsoft.AspNetCore.DataOrotection.Redis package is not listed.
                                                    sourceCacheContext: cacheContext,
                                                    log: logger,
                                                    token: CancellationToken.None)));

            // Find the latest version among each search metadata
            NuGetVersion latestVersion = null;

            foreach (var searchMetadata in searchMetadatas)
            {
                var potentialLatestVersion = versionRange.FindBestMatch(
                    searchMetadata.Select(metadata => metadata.Identity.Version));
                if (latestVersion == null ||
                    (potentialLatestVersion != null && potentialLatestVersion.CompareTo(latestVersion) > 0))
                {
                    latestVersion = potentialLatestVersion;
                }
            }

            if (latestVersion == null)
            {
                logger.LogWarning($"Unable to find latest version of '{packageId}'.");
                return(false);
            }

            var hasChanged = false;

            if (latestVersion != currentVersion)
            {
                hasChanged             = true;
                versionAttribute.Value = latestVersion.ToNormalizedString();
            }

            return(hasChanged);
        }
Exemple #13
0
        public IPackageSearchMetadata FindBestPackage(String id, VersionRange versionRange)
        {
            List <IPackageSearchMetadata> matchingPackages = FindPackages(id);

            if (matchingPackages == null)
            {
                return(null);
            }

            var versions    = matchingPackages.Select(package => package.Identity.Version);
            var bestVersion = versionRange.FindBestMatch(versions);

            return(matchingPackages.Where(package => package.Identity.Version == bestVersion).FirstOrDefault());
        }
Exemple #14
0
        public void FloatRange_RangeOpen()
        {
            VersionRange range = VersionRange.Parse("[1.0.*, )");

            var versions = new List <NuGetVersion>()
            {
                NuGetVersion.Parse("0.1.0"),
                NuGetVersion.Parse("0.2.0"),
                NuGetVersion.Parse("1.0.0-alpha.2"),
                NuGetVersion.Parse("101.0.0")
            };

            Assert.Equal("101.0.0", range.FindBestMatch(versions).ToNormalizedString());
        }
Exemple #15
0
        public void FloatingRange_FloatMinorPrefixNotFoundBest()
        {
            VersionRange range = VersionRange.Parse("1.*");

            var versions = new List <NuGetVersion>()
            {
                NuGetVersion.Parse("0.1.0"),
                NuGetVersion.Parse("2.0.0"),
                NuGetVersion.Parse("2.5.0"),
                NuGetVersion.Parse("3.3.0"),
            };

            // take the nearest when the prefix is not matched
            Assert.Equal("2.0.0", range.FindBestMatch(versions).ToNormalizedString());
        }
Exemple #16
0
        public void FloatingRange_FloatPrereleasePartialBest()
        {
            VersionRange range = VersionRange.Parse("1.0.0-alpha*");

            var versions = new List <NuGetVersion>()
            {
                NuGetVersion.Parse("0.1.0-alpha"),
                NuGetVersion.Parse("1.0.0-alpha01"),
                NuGetVersion.Parse("1.0.0-alpha02"),
                NuGetVersion.Parse("2.0.0-beta"),
                NuGetVersion.Parse("2.0.1"),
            };

            Assert.Equal("1.0.0-alpha02", range.FindBestMatch(versions).ToNormalizedString());
        }
        private async Task <PackageIdentity> GetLatestPackageInternalAsync(string packageId, VersionRange versionRange, CancellationToken cancellationToken)
        {
            versionRange = new VersionRange(versionRange ?? VersionRange.All, new FloatRange(VersionFloatBehavior));

            var packageVersions = await this.GetPackageVersionsAsync(packageId, cancellationToken).ConfigureAwait(false);

            if (!packageVersions.Any())
            {
                throw new PackageNotFoundException($"Package \"{packageId}\" not found in repository {this.feedUrl.ToString()}");
            }

            var packageVersion = versionRange.FindBestMatch(packageVersions) ??
                                 throw new PackageVersionNotFoundException($"Package \"{packageId}\" has no versions compatible with range \"{versionRange.ToString()}\".");

            return(new PackageIdentity(packageId, packageVersion));
        }
Exemple #18
0
        public async Task <NuGetVersion> ResolvePackageVersions(string packageName, NuGetVersion referencedVersion, IEnumerable <Uri> sources, VersionRange currentVersionRange,
                                                                VersionLock versionLock, PrereleaseReporting prerelease, NuGetFramework targetFrameworkName, string projectFilePath, bool isDevelopmentDependency, int olderThanDays, bool ignoreFailedSources = false)
        {
            // Determine whether we are interested in pre-releases
            bool includePrerelease = referencedVersion.IsPrerelease;

            if (prerelease == PrereleaseReporting.Always)
            {
                includePrerelease = true;
            }
            else if (prerelease == PrereleaseReporting.Never)
            {
                includePrerelease = false;
            }

            string cacheKey = (packageName + "-" + includePrerelease + "-" + targetFrameworkName + "-" + olderThanDays).ToLowerInvariant();

            // Get all the available versions
            var allVersionsRequest = new Lazy <Task <IReadOnlyList <NuGetVersion> > >(() => this._nugetService.GetAllVersions(packageName, sources, includePrerelease, targetFrameworkName, projectFilePath, isDevelopmentDependency, olderThanDays, ignoreFailedSources));
            var allVersions        = await this._cache.GetOrAdd(cacheKey, allVersionsRequest).Value;

            // Determine the floating behaviour
            var floatingBehaviour = includePrerelease ? NuGetVersionFloatBehavior.AbsoluteLatest : NuGetVersionFloatBehavior.Major;

            if (versionLock == VersionLock.Major)
            {
                floatingBehaviour = includePrerelease ? NuGetVersionFloatBehavior.PrereleaseMinor : NuGetVersionFloatBehavior.Minor;
            }
            if (versionLock == VersionLock.Minor)
            {
                floatingBehaviour = includePrerelease ? NuGetVersionFloatBehavior.PrereleasePatch : NuGetVersionFloatBehavior.Patch;
            }

            string releasePrefix = null;

            if (referencedVersion.IsPrerelease)
            {
                releasePrefix = referencedVersion.ReleaseLabels.First(); // TODO Not sure exactly what to do for this bit
            }
            // Create a new version range for comparison
            var latestVersionRange = new VersionRange(currentVersionRange, new FloatRange(floatingBehaviour, referencedVersion, releasePrefix));

            // Use new version range to determine latest version
            NuGetVersion latestVersion = latestVersionRange.FindBestMatch(allVersions);

            return(latestVersion);
        }
Exemple #19
0
        private static NuGetVersion GetNuGetVersion(PackageReference package, IEnumerable <SourceRepository> repositories, NuGetFramework targetFramework, SourceCacheContext sourceCacheContext, ILogger logger)
        {
            NuGetVersion version      = null;
            VersionRange versionRange = null;

            if (package.Parameters.ContainsKey("version"))
            {
                var versionString = package.Parameters["version"].First();
                if (NuGetVersion.TryParse(versionString, out version))
                {
                    return(version);
                }
                VersionRange.TryParse(versionString, out versionRange);
            }

            var includePrerelease = package.IsPrerelease();

            foreach (var sourceRepository in repositories)
            {
                try
                {
                    var dependencyInfoResource = sourceRepository.GetResourceAsync <DependencyInfoResource>().Result;
                    var dependencyInfo         = dependencyInfoResource.ResolvePackages(package.Package, targetFramework, sourceCacheContext, logger, CancellationToken.None).Result;
                    var foundVersions          = dependencyInfo
                                                 .Where(p => p.Listed && (includePrerelease || !p.Version.IsPrerelease))
                                                 .OrderByDescending(p => p.Version, VersionComparer.Default)
                                                 .Select(p => p.Version);
                    var foundVersion = versionRange != null?versionRange.FindBestMatch(foundVersions) : foundVersions.FirstOrDefault();

                    // Find the highest possible version
                    if (version == null || foundVersion > version)
                    {
                        version = foundVersion;
                    }
                }
                catch (AggregateException ae)
                {
                    ae.Handle(e =>
                    {
                        logger.LogWarning(e.Message);
                        return(true);
                    });
                }
            }
            return(version);
        }
Exemple #20
0
        public async Task <PackageInfo> GetBestMatchPackageVersionsAsync(string packageId, VersionRange range)
        {
            cancellationToken = CancellationToken.None;
            FindPackageByIdResource resource = await repository.GetResourceAsync <FindPackageByIdResource>();

            IEnumerable <NuGetVersion> versions = await resource.GetAllVersionsAsync(
                packageId,
                cache,
                logger,
                cancellationToken);

            NuGetVersion bestMatchVersion = range.FindBestMatch(versions);

            return(new PackageInfo {
                packageId = packageId, packageVersion = bestMatchVersion
            });
        }
        public async Task <NuGetVersion> ResolvePackageVersions(string packageName, NuGetVersion referencedVersion, IEnumerable <Uri> sources, VersionRange currentVersionRange,
                                                                VersionLock versionLock, PrereleaseReporting prerelease, NuGetFramework targetFrameworkName, string projectFilePath, bool isDevelopmentDependency)
        {
            // Determine whether we are interested in pre-releases
            bool includePrerelease = referencedVersion.IsPrerelease;

            if (prerelease == PrereleaseReporting.Always)
            {
                includePrerelease = true;
            }
            else if (prerelease == PrereleaseReporting.Never)
            {
                includePrerelease = false;
            }

            string cacheKey = (packageName + "-" + includePrerelease + "-" + targetFrameworkName).ToLowerInvariant();

            if (!_cache.TryGetValue(cacheKey, out var allVersions))
            {
                // Get all the available versions
                allVersions = await _nugetService.GetAllVersions(packageName, sources, includePrerelease, targetFrameworkName, projectFilePath, isDevelopmentDependency);

                _cache.Add(cacheKey, allVersions);
            }

            // Determine the floating behaviour
            var floatingBehaviour = includePrerelease ? NuGetVersionFloatBehavior.AbsoluteLatest : NuGetVersionFloatBehavior.Major;

            if (versionLock == VersionLock.Major)
            {
                floatingBehaviour = NuGetVersionFloatBehavior.Minor;
            }
            if (versionLock == VersionLock.Minor)
            {
                floatingBehaviour = NuGetVersionFloatBehavior.Patch;
            }

            // Create a new version range for comparison
            var latestVersionRange = new VersionRange(currentVersionRange, new FloatRange(floatingBehaviour, referencedVersion));

            // Use new version range to determine latest version
            NuGetVersion latestVersion = latestVersionRange.FindBestMatch(allVersions);

            return(latestVersion);
        }
Exemple #22
0
        private static DependencyPackageKeys GetDependencyPackageKeys(
            IReadOnlyDictionary <NuGetVersion, PackageEntity> versionToPackage,
            VersionRange parsedVersionRange)
        {
            parsedVersionRange = parsedVersionRange ?? VersionRange.All;

            var minimumMatch = versionToPackage
                               .Keys
                               .Where(x => parsedVersionRange.Satisfies(x))
                               .OrderBy(x => x)
                               .FirstOrDefault();
            var bestMatch = parsedVersionRange
                            .FindBestMatch(versionToPackage.Keys);

            var minimumKey = minimumMatch != null ? versionToPackage[minimumMatch].PackageKey : (long?)null;
            var bestKey    = bestMatch != null ? versionToPackage[bestMatch].PackageKey : (long?)null;

            return(new DependencyPackageKeys(minimumKey, bestKey));
        }
        public static LocalPackageInfo GetPackage(
            string id,
            VersionRange versionRange)
        {
            var packageCandidates = repo
                                    .FindPackagesById(id)
                                    .ToList();

            if (packageCandidates.Count == 0)
            {
                return(null);
            }

            var bestVersion = versionRange.FindBestMatch(
                packageCandidates.Select(p => p.Version));

            return(packageCandidates.FirstOrDefault(
                       p => p.Version == bestVersion));
        }
Exemple #24
0
        private async Task <PackageInfo> GetBestMatchPackageVersionsAsync(SourceRepository repository, string packageId, VersionRange range)
        {
            ILogger                 logger            = NullLogger.Instance;
            CancellationToken       cancellationToken = CancellationToken.None;
            SourceCacheContext      cache             = new SourceCacheContext();
            FindPackageByIdResource resource          = await repository.GetResourceAsync <FindPackageByIdResource>();

            IEnumerable <NuGetVersion> versions = await resource.GetAllVersionsAsync(
                packageId,
                cache,
                logger,
                cancellationToken);

            NuGetVersion bestMatchVersion = range.FindBestMatch(versions);

            return(new PackageInfo {
                packageId = packageId, packageVersion = bestMatchVersion
            });
        }
Exemple #25
0
        public async Task <(NuGetVersion referencedVersion, NuGetVersion latestVersion)> ResolvePackageVersions(
            string package, List <Uri> sources, VersionRange currentVersionRange, VersionLock versionLock, PrereleaseReporting prerelease)
        {
            // Get all the available versions
            var allVersions = await _nugetService.GetAllVersions(package, sources);

            // Resolve the referenced versions
            NuGetVersion referencedVersion = currentVersionRange.FindBestMatch(allVersions);

            // Determine whether we are interested in pre-releases
            bool includePrerelease = referencedVersion.IsPrerelease;

            if (prerelease == PrereleaseReporting.Always)
            {
                includePrerelease = true;
            }
            else if (prerelease == PrereleaseReporting.Never)
            {
                includePrerelease = false;
            }

            // Determine the floating behaviour
            var floatingBehaviour = includePrerelease ? NuGetVersionFloatBehavior.AbsoluteLatest : NuGetVersionFloatBehavior.Major;

            if (versionLock == VersionLock.Major)
            {
                floatingBehaviour = NuGetVersionFloatBehavior.Minor;
            }
            if (versionLock == VersionLock.Minor)
            {
                floatingBehaviour = NuGetVersionFloatBehavior.Patch;
            }

            // Create a new version range for comparison
            var latestVersionRange = new VersionRange(currentVersionRange, new FloatRange(floatingBehaviour, referencedVersion));

            // Use new version range to determine latest version
            NuGetVersion latestVersion = latestVersionRange.FindBestMatch(allVersions);

            return(referencedVersion, latestVersion);
        }
Exemple #26
0
        private static async Task <bool> TryUpdateVersionAsync(
            XAttribute versionAttribute,
            string packageId,
            PackageMetadataResource packageMetadataResource,
            ILogger logger,
            SourceCacheContext cacheContext)
        {
            var searchMetadata = await packageMetadataResource.GetMetadataAsync(
                packageId,
                includePrerelease : false,
                includeUnlisted : true, // Microsoft.AspNetCore.DataOrotection.Redis package is not listed.
                sourceCacheContext : cacheContext,
                log : logger,
                token : CancellationToken.None);

            var currentVersion = NuGetVersion.Parse(versionAttribute.Value);
            var versionRange   = new VersionRange(
                currentVersion,
                new FloatRange(NuGetVersionFloatBehavior.Patch, currentVersion));

            var latestVersion = versionRange.FindBestMatch(
                searchMetadata.Select(metadata => metadata.Identity.Version));

            if (latestVersion == null)
            {
                logger.LogWarning($"Unable to find latest version of '{packageId}'.");
                return(false);
            }

            var hasChanged = false;

            if (latestVersion != currentVersion)
            {
                hasChanged             = true;
                versionAttribute.Value = latestVersion.ToNormalizedString();
            }

            return(hasChanged);
        }
        public string GetBestLockFilePath(string packageId, VersionRange versionRange, NuGetFramework framework)
        {
            if (versionRange == null)
            {
                throw new ArgumentNullException(nameof(versionRange));
            }

            if (framework == null)
            {
                throw new ArgumentNullException(nameof(framework));
            }

            var availableToolVersions = GetAvailableToolVersions(packageId);

            var bestVersion = versionRange.FindBestMatch(availableToolVersions);

            if (bestVersion == null)
            {
                throw new GracefulException($"Version for package `{packageId}` could not be resolved.");
            }

            return(GetLockFilePath(packageId, bestVersion, framework));
        }
Exemple #28
0
        private MockFeedPackage GetPackage(
            string packageId,
            VersionRange versionRange = null,
            FilePath?nugetConfig      = null,
            string source             = null)
        {
            var allPackages = _feeds
                              .Where(f => {
                if (nugetConfig != null)
                {
                    return(f.Type == MockFeedType.ExplicitNugetConfig && f.Uri == nugetConfig.Value.Value);
                }
                if (source != null)
                {
                    return(f.Type == MockFeedType.Source && f.Uri == source);
                }
                return(true);
            })
                              .SelectMany(f => f.Packages)
                              .Where(f => f.PackageId == packageId);

            var bestVersion = versionRange.FindBestMatch(allPackages.Select(p => NuGetVersion.Parse(p.Version)));

            var package = allPackages.Where(p => NuGetVersion.Parse(p.Version).Equals(bestVersion)).FirstOrDefault();

            if (package == null)
            {
                if (_reporter != null)
                {
                    _reporter.WriteLine($"Error: failed to restore package {packageId}.");
                }
                throw new ToolPackageException(LocalizableStrings.ToolInstallationRestoreFailed);
            }

            return(package);
        }
Exemple #29
0
        private async Task <NuGetVersion> GetPackageVersion(VersionRange range)
        {
            if (!range.IsFloating)
            {
                return(range.MinVersion);
            }

            using (var cacheContext = new SourceCacheContext())
            {
                var log             = new MSBuildLogger(Log);
                var defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null);
                var sourceProvider  = new CachingSourceProvider(new PackageSourceProvider(defaultSettings));

                var repo = sourceProvider.CreateRepository(new PackageSource(LineupPackageRestoreSource));

                var metadata = await repo.GetResourceAsync <MetadataResource>();

                if (!await metadata.Exists(LineupPackageId, cacheContext, log, _cts.Token))
                {
                    Log.LogError($"Package {LineupPackageId} is not available on '{repo}'");
                    return(null);
                }

                try
                {
                    var versions = await metadata.GetVersions(LineupPackageId, includePrerelease : true, includeUnlisted : false, sourceCacheContext : cacheContext, log : log, token : _cts.Token);

                    return(range.FindBestMatch(versions));
                }
                catch (Exception ex)
                {
                    Log.LogError($"Unexpected error while fetching versions from {repo.PackageSource.Source}: " + ex.Message);
                    return(null);
                }
            }
        }
Exemple #30
0
        public MockFeedPackage GetPackage(
            string packageId,
            VersionRange versionRange,
            FilePath?nugetConfig = null,
            DirectoryPath?rootConfigDirectory = null)
        {
            var allPackages = _feeds
                              .Where(feed =>
            {
                if (nugetConfig == null)
                {
                    return(SimulateNugetSearchNugetConfigAndMatch(
                               rootConfigDirectory,
                               feed));
                }
                else
                {
                    return(ExcludeOtherFeeds(nugetConfig.Value, feed));
                }
            })
                              .SelectMany(f => f.Packages)
                              .Where(f => f.PackageId == packageId)
                              .ToList();

            var bestVersion = versionRange.FindBestMatch(allPackages.Select(p => NuGetVersion.Parse(p.Version)));

            var package = allPackages.FirstOrDefault(p => NuGetVersion.Parse(p.Version).Equals(bestVersion));

            if (package == null)
            {
                _reporter?.WriteLine($"Error: failed to restore package {packageId}.");
                throw new ToolPackageException(LocalizableStrings.ToolInstallationRestoreFailed);
            }

            return(package);
        }