private static void Process(FileInfo file, string id, VersionRange version)
        {
            Console.WriteLine(file.FullName);
            var json = JObject.Parse(File.ReadAllText(file.FullName));

            var found = false;

            foreach (var dependency in SpecUtility.GetDependencies(json))
            {
                var packageDependency = SpecUtility.GetDependency(dependency);

                if (packageDependency.Id.Equals(id, StringComparison.OrdinalIgnoreCase))
                {
                    var orig = dependency.Value.ToString();

                    if (orig != version.OriginalString)
                    {
                        Console.WriteLine($"{dependency.Value.ToString()} -> {version.OriginalString}");
                        dependency.Value = version.OriginalString;
                        found = true;
                    }
                }
            }

            if (found)
            {
                File.WriteAllText(file.FullName, json.ToString(), Encoding.UTF8);
            }
        }
Beispiel #2
0
        public async Task <IEnumerable <NuGetVersion> > DownloadPackagesAsync(
            IEnumerable <string> sources,
            IEnumerable <string> ids,
            NuGetVersionRange versionRange,
            SourceCacheContext sourceCacheContext,
            ILogger log,
            CancellationToken token)
        {
            var versions = await GetAvailableVersionsAsync(sources, ids, log, token);

            var limitedVersions = versions
                                  .Where(x => versionRange.Satisfies(x));

            var identities = ids
                             .SelectMany(id => limitedVersions.Select(version => new PackageIdentity(id, version)));

            await _packageRangeDownloader.DownloadPackagesAsync(
                sources,
                identities,
                sourceCacheContext,
                log,
                token);

            return(versions);
        }
        /// <summary>
        /// Retrieve dependency info for a single package.
        /// </summary>
        /// <param name="package">package id and version</param>
        /// <param name="projectFramework">project target framework. This is used for finding the dependency group</param>
        /// <param name="token">cancellation token</param>
        /// <returns>
        /// Returns dependency info for the given package if it exists. If the package is not found null is
        /// returned.
        /// </returns>
        public override async Task<SourcePackageDependencyInfo> ResolvePackage(PackageIdentity package, NuGetFramework projectFramework, CancellationToken token)
        {
            try
            {
                SourcePackageDependencyInfo result = null;

                // Construct the registration index url
                var uri = _regResource.GetUri(package.Id);

                // Retrieve the registration blob
                var singleVersion = new VersionRange(minVersion: package.Version, includeMinVersion: true, maxVersion: package.Version, includeMaxVersion: true);
                var regInfo = await ResolverMetadataClient.GetRegistrationInfo(_client, uri, singleVersion, projectFramework, token);

                // regInfo is null if the server returns a 404 for the package to indicate that it does not exist
                if (regInfo != null)
                {
                    // Parse package and dependeny info from the blob
                    result = GetPackagesFromRegistration(regInfo, token).FirstOrDefault();
                }

                return result;
            }
            catch (Exception ex)
            {
                // Wrap exceptions coming from the server with a user friendly message
                var error = String.Format(CultureInfo.CurrentUICulture, Strings.Protocol_PackageMetadataError, package, _source);

                throw new NuGetProtocolException(error, ex);
            }
        }
        /// <summary>
        /// Retrieve the <see cref="RemoteSourceDependencyInfo" /> for a registration.
        /// </summary>
        /// <returns>Returns an empty sequence if the package does not exist.</returns>
        public static async Task<IEnumerable<RemoteSourceDependencyInfo>> GetDependencies(
            HttpClient httpClient,
            Uri registrationUri,
            VersionRange range,
            CancellationToken token)
        {
            var ranges = await Utils.LoadRanges(httpClient, registrationUri, range, token);

            var results = new HashSet<RemoteSourceDependencyInfo>();
            foreach (var rangeObj in ranges)
            {
                if (rangeObj == null)
                {
                    throw new InvalidDataException(registrationUri.AbsoluteUri);
                }

                foreach (JObject packageObj in rangeObj["items"])
                {
                    var catalogEntry = (JObject)packageObj["catalogEntry"];
                    var version = NuGetVersion.Parse(catalogEntry["version"].ToString());

                    if (range.Satisfies(version))
                    {
                        results.Add(ProcessPackageVersion(packageObj, version, range.IncludePrerelease));
                    }
                }
            }

            return results;
        }
        public void VersionRange_Exact()
        {
            // Act 
            var versionInfo = new VersionRange(new NuGetVersion(4, 3, 0), true, new NuGetVersion(4, 3, 0), true, false);

            // Assert
            Assert.True(versionInfo.Satisfies(NuGetVersion.Parse("4.3.0")));
        }
Beispiel #6
0
        public void ParseVersionRangeNoPrerelease()
        {
            // Act 
            var versionInfo =  new VersionRange(minVersion: new NuGetVersion("1.2-Alpha"), includePrerelease: false);

            // Assert
            Assert.False(versionInfo.IncludePrerelease);
        }
Beispiel #7
0
        public string GetBestLockFilePath(string packageId, VersionRange versionRange, NuGetFramework framework)
        {
            var availableToolVersions = GetAvailableToolVersions(packageId);

            var bestVersion = versionRange.FindBestMatch(availableToolVersions);

            return GetLockFilePath(packageId, bestVersion, framework);
        }
Beispiel #8
0
        public static string RenderVersion(VersionRange range)
        {
            if (range == null)
            {
                return null;
            }

            if (range.MinVersion == range.MaxVersion &&
                (range.Float == null || range.Float.FloatBehavior == NuGetVersionFloatBehavior.None))
            {
                return range.MinVersion.ToNormalizedString();
            }
            var sb = new StringBuilder();
            sb.Append(">= ");
            switch (range?.Float?.FloatBehavior)
            {
                case null:
                case NuGetVersionFloatBehavior.None:
                    sb.Append(range.MinVersion.ToNormalizedString());
                    break;
                case NuGetVersionFloatBehavior.Prerelease:
                    // Work around nuget bug: https://github.com/NuGet/Home/issues/1598
                    // sb.AppendFormat("{0}-*", range.MinVersion);
                    sb.Append($"{range.MinVersion.Version.Major}.{range.MinVersion.Version.Minor}.{range.MinVersion.Version.Build}");
                    if (string.IsNullOrEmpty(range.MinVersion.Release) || 
                        string.Equals("-", range.MinVersion.Release))
                    {
                        sb.Append($"-*");
                    }
                    else
                    {
                        sb.Append($"-{range.MinVersion.Release}*");
                    }
                    break;
                case NuGetVersionFloatBehavior.Revision:
                    sb.Append($"{range.MinVersion.Version.Major}.{range.MinVersion.Version.Minor}.{range.MinVersion.Version.Build}.*");
                    break;
                case NuGetVersionFloatBehavior.Patch:
                    sb.Append($"{range.MinVersion.Version.Major}.{range.MinVersion.Version.Minor}.*");
                    break;
                case NuGetVersionFloatBehavior.Minor:
                    sb.AppendFormat($"{range.MinVersion.Version.Major}.*");
                    break;
                case NuGetVersionFloatBehavior.Major:
                    sb.AppendFormat("*");
                    break;
                default:
                    break;
            }

            if (range.MaxVersion != null)
            {
                sb.Append(range.IsMaxInclusive ? " <= " : " < ");
                sb.Append(range.MaxVersion);
            }

            return sb.ToString();
        }
Beispiel #9
0
 /// <summary>
 /// Creates a new packages config entry
 /// </summary>
 /// <param name="identity">Package id and version</param>
 /// <param name="targetFramework">Package target framework installed to the project</param>
 /// <param name="userInstalled">True if the user installed this package directly</param>
 /// <param name="developmentDependency">True if the package is a development dependency</param>
 /// <param name="requireReinstallation">True if this package needs to be reinstalled</param>
 /// <param name="allowedVersions">Restrict package versions to the allowedVersions range</param>
 public PackageReference(PackageIdentity identity, NuGetFramework targetFramework, bool userInstalled, bool developmentDependency, bool requireReinstallation, VersionRange allowedVersions)
 {
     _identity = identity;
     _allowedVersions = allowedVersions;
     _targetFramework = targetFramework;
     _developmentDependency = developmentDependency;
     _userInstalled = userInstalled;
     _requireReinstallation = requireReinstallation;
 }
Beispiel #10
0
        public void ParseVersionRangeParts(NuGetVersion min, NuGetVersion max, bool minInc, bool maxInc)
        {
            // Act
            var versionInfo = new VersionRange(min, minInc, max, maxInc);

            // Assert
            Assert.Equal(min, versionInfo.MinVersion, VersionComparer.Default);
            Assert.Equal(max, versionInfo.MaxVersion, VersionComparer.Default);
            Assert.Equal(minInc, versionInfo.IsMinInclusive);
            Assert.Equal(maxInc, versionInfo.IsMaxInclusive);
        }
 /// <summary>
 /// Initialise a new insatnce of <see cref="ReadSnippetError"/>.
 /// </summary>
 public ReadSnippetError(VersionRange version, string key, int line, string file, string message)
 {
     Guard.AgainstNegativeAndZero(line, "line");
     Guard.AgainstNullAndEmpty(key, "key");
     Guard.AgainstNullAndEmpty(message, "message");
     Version = version;
     Key = key;
     Line = line;
     File = file;
     Message = message;
 }
Beispiel #12
0
        public void ParseVersionRangeToStringReParse(NuGetVersion min, NuGetVersion max, bool minInc, bool maxInc)
        {
            // Act
            var original = new VersionRange(min, minInc, max, maxInc);
            var versionInfo = VersionRange.Parse(original.ToString());

            // Assert
            Assert.Equal(min, versionInfo.MinVersion, VersionComparer.Default);
            Assert.Equal(max, versionInfo.MaxVersion, VersionComparer.Default);
            Assert.Equal(minInc, versionInfo.IsMinInclusive);
            Assert.Equal(maxInc, versionInfo.IsMaxInclusive);
        }
		public void AddPackageReference (string id, string version, VersionRange versionRange = null)
		{
			var packageId = new PackageIdentity (id, new NuGetVersion (version));
			var packageReference = new PackageReference (
				packageId,
				new NuGetFramework ("net45"),
				true,
				false,
				false,
				versionRange
			);
			InstalledPackages.Add (packageReference);
		}
Beispiel #14
0
        internal static IVersionSpec SafeToVerSpec(VersionRange versionRange)
        {
            if (versionRange == null)
            {
                return null;
            }

            return new VersionSpec()
            {
                IsMaxInclusive = versionRange.IsMaxInclusive,
                IsMinInclusive = versionRange.IsMinInclusive,
                MaxVersion = SafeToSemanticVersion(versionRange.MaxVersion),
                MinVersion = SafeToSemanticVersion(versionRange.MinVersion)
            };
        }
        /// <summary>
        /// Retrieves all the package and all dependant packages
        /// </summary>
        public override async Task<IEnumerable<PackageDependencyInfo>> ResolvePackages(IEnumerable<PackageIdentity> packages, NuGetFramework projectFramework, bool includePrerelease, CancellationToken token)
        {
            // compare results based on the id/version
            HashSet<PackageDependencyInfo> results = new HashSet<PackageDependencyInfo>(PackageIdentity.Comparer);

            foreach (var package in packages)
            {
                var range = new VersionRange(package.Version, true, package.Version, true);

                foreach (var result in await GetPackagesFromRegistration(package.Id, range, projectFramework, token))
                {
                    results.Add(result);
                }
            }

            return results.Where(e => includePrerelease || !e.Version.IsPrerelease);
        }
 /// <summary>
 /// Initialise a new insatnce of <see cref="ReadSnippet"/>.
 /// </summary>
 public ReadSnippet(int startLine, int endLine, string value, string key, string language, string file, VersionRange version)
 {
     Guard.AgainstNullAndEmpty(key, "key");
     Guard.AgainstUpperCase(key, "key");
     Guard.AgainstNull(language, "language");
     Guard.AgainstUpperCase(language, "language");
     Guard.AgainstNegativeAndZero(startLine, "startLine");
     Guard.AgainstNegativeAndZero(endLine, "endLine");
    
     StartLine = startLine;
     EndLine = endLine;
     Value = value;
     ValueHash = value.RemoveWhitespace().GetHashCode();
     Key = key;
     Language = language;
     File = file;
     Version = version;
 }
Beispiel #17
0
        public override async Task<IEnumerable<UIPackageMetadata>> GetMetadata(IEnumerable<PackageIdentity> packages, CancellationToken token)
        {
            var results = new List<UIPackageMetadata>();

            // group by id to optimize
            foreach (var group in packages.GroupBy(e => e.Id, StringComparer.OrdinalIgnoreCase))
            {
                var versions = group.OrderBy(e => e.Version, VersionComparer.VersionRelease);

                // find the range of versions we need
                var range = new VersionRange(versions.First().Version, true, versions.Last().Version, true, true);

                var metadataList = await _regResource.GetPackageMetadata(group.Key, range, true, true, token);

                results.AddRange(metadataList.Select(item => ParseMetadata(item)));
            }

            return results;
        }
Beispiel #18
0
        public async static Task<IEnumerable<JObject>> LoadRanges(
            HttpClient httpClient,
            Uri registrationUri,
            VersionRange range,
            CancellationToken token)
        {
            var index = await LoadResource(httpClient, registrationUri, token);

            if (index == null)
            {
                // The server returned a 404, the package does not exist
                return Enumerable.Empty<JObject>();
            }

            var preFilterRange = Utils.SetIncludePrerelease(range, true);

            IList<Task<JObject>> rangeTasks = new List<Task<JObject>>();

            foreach (JObject item in index["items"])
            {
                var lower = NuGetVersion.Parse(item["lower"].ToString());
                var upper = NuGetVersion.Parse(item["upper"].ToString());

                if (IsItemRangeRequired(preFilterRange, lower, upper))
                {
                    JToken items;
                    if (!item.TryGetValue("items", out items))
                    {
                        var rangeUri = item["@id"].ToObject<Uri>();

                        rangeTasks.Add(LoadResource(httpClient, rangeUri, token));
                    }
                    else
                    {
                        rangeTasks.Add(Task.FromResult(item));
                    }
                }
            }

            await Task.WhenAll(rangeTasks.ToArray());

            return rangeTasks.Select((t) => t.Result);
        }
        /// <summary>
        /// Returns inlined catalog entry items for each registration blob
        /// </summary>
        /// <remarks>The inlined entries are potentially going away soon</remarks>
        public virtual async Task<IEnumerable<JObject>> GetPackageMetadata(string packageId, VersionRange range, bool includePrerelease, bool includeUnlisted, CancellationToken token)
        {
            var results = new List<JObject>();

            var registrationUri = GetUri(packageId);

            var ranges = await Utils.LoadRanges(_client, registrationUri, range, token);

            foreach (var rangeObj in ranges)
            {
                if (rangeObj == null)
                {
                    throw new InvalidDataException(registrationUri.AbsoluteUri);
                }

                foreach (JObject packageObj in rangeObj["items"])
                {
                    var catalogEntry = (JObject)packageObj["catalogEntry"];
                    var version = NuGetVersion.Parse(catalogEntry["version"].ToString());

                    var listedToken = catalogEntry["listed"];

                    var listed = (listedToken != null) ? listedToken.Value<bool>() : true;

                    if (range.Satisfies(version)
                        && (includePrerelease || !version.IsPrerelease)
                        && (includeUnlisted || listed))
                    {
                        // add in the download url
                        if (packageObj["packageContent"] != null)
                        {
                            catalogEntry["packageContent"] = packageObj["packageContent"];
                        }

                        results.Add(catalogEntry);
                    }
                }
            }

            return results;
        }
 public static bool TryParseVersion(string stringVersion, out VersionRange parsedVersion)
 {
     if (stringVersion == "all")
     {
         parsedVersion = VersionRange.All;
         return true;
     }
     int intversion;
     if (int.TryParse(stringVersion, out intversion))
     {
         var semanticVersion = new NuGetVersion(intversion, 0, 0);
         parsedVersion = new VersionRange(
             minVersion: semanticVersion,
             includeMinVersion: true,
             maxVersion: new NuGetVersion(intversion + 1, 0, 0),
             includeMaxVersion: false
             );
         return true;
     }
     return VersionRange.TryParse(stringVersion, out parsedVersion);
 }
Beispiel #21
0
        private static async Task DownloadAsync(
            List <string> sources,
            AlignedVersionsDownloader alignedVersionDownloader,
            SourceCacheContext sourceCacheContext,
            ILogger log)
        {
            await alignedVersionDownloader.DownloadPackagesAsync(
                sources,
                ToolsFactory.PackageIds2x,
                VersionRange.Parse("[2.5.0, )", allowFloating: false),
                sourceCacheContext,
                log,
                CancellationToken.None);

            await alignedVersionDownloader.DownloadPackagesAsync(
                sources,
                ToolsFactory.PackageIds3x,
                VersionRange.All,
                sourceCacheContext,
                log,
                CancellationToken.None);
        }
        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);
        }
Beispiel #23
0
        private static string Format(char c, VersionRange range)
        {
            string s = null;

            switch (c)
            {
                case 'P':
                    s = PrettyPrint(range);
                    break;
                case 'L':
                    s =  range.HasLowerBound ? String.Format(new VersionFormatter(), "{0:N}", range.MinVersion) : string.Empty;
                    break;
                case 'U':
                    s = range.HasUpperBound ? String.Format(new VersionFormatter(), "{0:N}", range.MaxVersion) : string.Empty;
                    break;
                case 'N':
                    s = GetToString(range);
                    break;
            }

            return s;
        }
Beispiel #24
0
        public async Task DependencyInfo_XunitRetrieveDependencies()
        {
            // Arrange
            var repo = Repository.Factory.GetCoreV2("https://www.nuget.org/api/v2/");
            var resource = await repo.GetResourceAsync<DependencyInfoResource>();

            var package = new PackageIdentity("xunit", NuGetVersion.Parse("2.1.0-beta1-build2945"));

            // filter to keep this test consistent
            var filterRange = new VersionRange(NuGetVersion.Parse("2.0.0-rc4-build2924"), true, NuGetVersion.Parse("2.1.0-beta1-build2945"), true);

            // Act
            var results = await resource.ResolvePackages("xunit", NuGetFramework.Parse("net45"), CancellationToken.None);

            var filtered = results.Where(result => filterRange.Satisfies(result.Version));

            var target = filtered.Single(p => PackageIdentity.Comparer.Equals(p, package));

            // Assert
            Assert.Equal(3, filtered.Count());
            Assert.Equal(2, target.Dependencies.Count());
            Assert.Equal("[2.1.0-beta1-build2945, 2.1.0-beta1-build2945]", target.Dependencies.Single(dep => dep.Id == "xunit.core").VersionRange.ToNormalizedString());
            Assert.Equal("[2.1.0-beta1-build2945, 2.1.0-beta1-build2945]", target.Dependencies.Single(dep => dep.Id == "xunit.assert").VersionRange.ToNormalizedString());
        }
		public DisplayVersion(
			VersionRange range,
			string additionalInfo)
		{
			Range = range;
			_additionalInfo = additionalInfo;

			Version = range.MinVersion;

			// Display a single version if the range is locked
			if (range.HasLowerAndUpperBounds && range.MinVersion == range.MaxVersion)
			{
				_toString = string.IsNullOrEmpty(_additionalInfo) ?
				                  Version.ToNormalizedString() :
				                  _additionalInfo + " " + Version.ToNormalizedString();
			}
			else
			{
				// Display the range, use the original value for floating ranges
				_toString = string.IsNullOrEmpty(_additionalInfo) ?
				                  Range.OriginalString :
				                  _additionalInfo + " " + Range.OriginalString;
			}
		}
Beispiel #26
0
        /// <summary>
        /// A pretty print representation of the VersionRange.
        /// </summary>
        private string PrettyPrint(VersionRange range)
        {
            StringBuilder sb = new StringBuilder("(");

            // no upper
            if (range.HasLowerBound && !range.HasUpperBound)
            {
                sb.Append(GreaterThanOrEqualTo);
                sb.AppendFormat(_versionFormatter, " {0:N}", range.MinVersion);
            }
            // single version
            else if (range.HasLowerAndUpperBounds && range.MaxVersion.Equals(range.MinVersion) && range.IsMinInclusive && range.IsMaxInclusive)
            {
                sb.AppendFormat(_versionFormatter, "= {0:N}", range.MinVersion);
            }
            else // normal range
            {
                if (range.HasLowerBound)
                {
                    if (range.IsMinInclusive)
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", GreaterThanOrEqualTo);
                    }
                    else
                    {
                        sb.Append("> ");
                    }

                    sb.AppendFormat(_versionFormatter, ZeroN, range.MinVersion);
                }

                if (range.HasLowerAndUpperBounds)
                {
                    sb.Append(" && ");
                }

                if (range.HasUpperBound)
                {
                    if (range.IsMaxInclusive)
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LessThanOrEqualTo);
                    }
                    else
                    {
                        sb.Append("< ");
                    }

                    sb.AppendFormat(_versionFormatter, ZeroN, range.MaxVersion);
                }
            }

            sb.Append(")");

            // avoid ()
            if (sb.Length == 2)
            {
                sb.Clear();
            }

            return(sb.ToString());
        }
Beispiel #27
0
        /// <summary>
        /// Returns the smallest range that includes all given ranges.
        /// </summary>
        public static VersionRange Combine(IEnumerable <VersionRange> ranges, IVersionComparer comparer)
        {
            if (ranges == null)
            {
                throw new ArgumentNullException(nameof(ranges));
            }

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

            // Default to None for empty lists
            var result = None;

            // Remove zero width ranges. Ex: (1.0.0, 1.0.0)
            // This includes VersionRange.None and any other ranges that satisfy zero versions
            ranges = ranges.Where(range => HasValidRange(range));

            if (ranges.Any())
            {
                var rangeComparer = new VersionRangeComparer(comparer);

                // start with the first range in the list
                var first = ranges.First();

                var lowest  = first.MinVersion;
                var highest = first.MaxVersion;

                // To keep things consistent set min/max inclusive to false when there is no boundary
                // It is possible to denote an inclusive range with no bounds, but it has no useful meaning for combine
                var includeLowest  = first.IsMinInclusive && first.HasLowerBound;
                var includeHighest = first.IsMaxInclusive && first.HasUpperBound;

                // expand the range to inclue all other ranges
                foreach (var range in ranges.Skip(1))
                {
                    // once we have an unbounded lower we can stop checking
                    if (lowest != null)
                    {
                        if (range.HasLowerBound)
                        {
                            var lowerCompare = comparer.Compare(range.MinVersion, lowest);

                            if (lowerCompare < 0)
                            {
                                // A new lowest was found
                                lowest        = range.MinVersion;
                                includeLowest = range.IsMinInclusive;
                            }
                            else if (lowerCompare == 0)
                            {
                                // The lower ends are identical, update the inclusiveness
                                includeLowest |= range.IsMinInclusive;
                            }
                            // lowerCompare > 0 falls into the current range, this is a no-op
                        }
                        else
                        {
                            // No lower bound
                            lowest        = null;
                            includeLowest = false;
                        }
                    }

                    // null is the highest we can get, stop checking once it is hit
                    if (highest != null)
                    {
                        if (range.HasUpperBound)
                        {
                            var higherCompare = comparer.Compare(range.MaxVersion, highest);

                            if (higherCompare > 0)
                            {
                                // A new highest was found
                                highest        = range.MaxVersion;
                                includeHighest = range.IsMaxInclusive;
                            }
                            else if (higherCompare == 0)
                            {
                                // The higher ends are identical, update the inclusiveness
                                includeHighest |= range.IsMaxInclusive;
                            }
                            // higherCompare < 0 falls into the current range, this is a no-op
                        }
                        else
                        {
                            // No higher bound
                            highest        = null;
                            includeHighest = false;
                        }
                    }
                }

                // Create the new range using the maximums found
                result = new VersionRange(lowest, includeLowest, highest, includeHighest);
            }

            return(result);
        }
        /// <summary>
        /// Helper for finding all versions of a package and all dependencies.
        /// </summary>
        private async Task<IEnumerable<PackageDependencyInfo>> GetPackagesFromRegistration(string packageId, VersionRange range, NuGetFramework projectFramework, CancellationToken cancellationToken)
        {
            HashSet<PackageDependencyInfo> results = new HashSet<PackageDependencyInfo>(PackageIdentity.Comparer);

            Uri uri = _regResource.GetUri(packageId);

            try
            {
                var regInfo = await ResolverMetadataClient.GetRegistrationInfo(_client, uri, range, projectFramework, _cache);

                var result = await ResolverMetadataClient.GetTree(_client, regInfo, projectFramework, _cache);

                foreach (var currentPackage in GetPackagesFromRegistration(result, cancellationToken))
                {
                    results.Add(currentPackage);
                }
            }
            catch (ArgumentException)
            {
                // ignore missing packages
                // TODO: add an exception type for missing packages to be thrown in the metadata client
            }

            return results;
        }
		public async Task GetUpdatedPackages_OnePackageReferencedWithConstraintAndUpdatesAvailable_LatestVersionReturnedBasedOnConstraint ()
		{
			CreateUpdatedPackagesInWorkspace ();
			FakeNuGetProject project = AddNuGetProjectToSolution ();
			var versionRange = new VersionRange (
				minVersion: new NuGetVersion ("1.0"),
				includeMinVersion: true,
				maxVersion: new NuGetVersion ("2.0"),
				includeMaxVersion: true);
			project.AddPackageReference ("Test", "1.0", versionRange);
			var package = packageMetadataResource.AddPackageMetadata ("Test", "2.0").Identity;
			packageMetadataResource.AddPackageMetadata ("Test", "3.0");
			var expectedPackages = new [] {
				package
			};
			await CheckForUpdates ();

			var updatedPackages = updatedPackagesInWorkspace.GetUpdatedPackages (dotNetProject);

			CollectionAssert.AreEqual (expectedPackages, updatedPackages.GetPackages ());
		}
Beispiel #30
0
 /// <summary>
 /// Parses a VersionRange from its string representation.
 /// </summary>
 public static bool TryParse(string value, out VersionRange versionRange)
 {
     return(TryParse(value, true, out versionRange));
 }
		public PackageDependencyMetadata(string id, VersionRange range)
		{
			Id = id;
			Range = range;
		}
Beispiel #32
0
        /// <summary>
        /// Parses a VersionRange from its string representation.
        /// </summary>
        public static bool TryParse(string value, bool allowFloating, out VersionRange versionRange)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            versionRange = null;

            var trimmedValue = value.Trim();

            var charArray = trimmedValue.ToCharArray();

            // * is the only range below 3 chars
            if (allowFloating &&
                charArray.Length == 1 &&
                charArray[0] == '*')
            {
                versionRange = new VersionRange(null, true, null, true, new FloatRange(NuGetVersionFloatBehavior.Major), originalString: value);
                return(true);
            }

            // Fail early if the string is too short to be valid
            if (charArray.Length < 3)
            {
                return(false);
            }

            string       minVersionString = null;
            string       maxVersionString = null;
            var          isMinInclusive   = false;
            var          isMaxInclusive   = false;
            NuGetVersion minVersion       = null;
            NuGetVersion maxVersion       = null;
            FloatRange   floatRange       = null;

            if (charArray[0] == '(' ||
                charArray[0] == '[')
            {
                // The first character must be [ to (
                switch (charArray[0])
                {
                case '[':
                    isMinInclusive = true;
                    break;

                case '(':
                    isMinInclusive = false;
                    break;

                default:
                    return(false);
                }

                // The last character must be ] ot )
                switch (charArray[charArray.Length - 1])
                {
                case ']':
                    isMaxInclusive = true;
                    break;

                case ')':
                    isMaxInclusive = false;
                    break;

                default:
                    return(false);
                }

                // Get rid of the two brackets
                trimmedValue = trimmedValue.Substring(1, trimmedValue.Length - 2);

                // Split by comma, and make sure we don't get more than two pieces
                var parts = trimmedValue.Split(',');
                if (parts.Length > 2)
                {
                    return(false);
                }
                else
                {
                    var allEmpty = true;

                    for (int i = 0; i < parts.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(parts[i]))
                        {
                            allEmpty = false;
                            break;
                        }
                    }

                    // If all parts are empty, then neither of upper or lower bounds were specified. Version spec is of the format (,]
                    if (allEmpty)
                    {
                        return(false);
                    }
                }

                // If there is only one piece, we use it for both min and max
                minVersionString = parts[0];
                maxVersionString = (parts.Length == 2) ? parts[1] : parts[0];
            }
            else
            {
                // default to min inclusive when there are no braces
                isMinInclusive = true;

                // use the entire value as the version
                minVersionString = trimmedValue;
            }

            if (!String.IsNullOrWhiteSpace(minVersionString))
            {
                // parse the min version string
                if (allowFloating && minVersionString.Contains("*"))
                {
                    // single floating version
                    if (FloatRange.TryParse(minVersionString, out floatRange) &&
                        floatRange.HasMinVersion)
                    {
                        minVersion = floatRange.MinVersion;
                    }
                    else
                    {
                        // invalid float
                        return(false);
                    }
                }
                else
                {
                    // single non-floating version
                    if (!NuGetVersion.TryParse(minVersionString, out minVersion))
                    {
                        // invalid version
                        return(false);
                    }
                }
            }

            // parse the max version string, the max cannot float
            if (!String.IsNullOrWhiteSpace(maxVersionString))
            {
                if (!NuGetVersion.TryParse(maxVersionString, out maxVersion))
                {
                    // invalid version
                    return(false);
                }
            }

            // Successful parse!
            versionRange = new VersionRange(
                minVersion: minVersion,
                includeMinVersion: isMinInclusive,
                maxVersion: maxVersion,
                includeMaxVersion: isMaxInclusive,
                floatRange: floatRange,
                originalString: value);

            return(true);
        }
Beispiel #33
0
 /// <summary>
 /// Clones a version range and applies a new float range.
 /// </summary>
 public VersionRange(VersionRange range, FloatRange floatRange)
     : this(range.MinVersion, range.IsMinInclusive, range.MaxVersion, range.IsMaxInclusive, floatRange)
 {
 }
Beispiel #34
0
 /// <summary>
 /// Find the version that best matches the VersionRange and the floating behavior.
 /// </summary>
 public static INuGetVersionable FindBestMatch(this IEnumerable <INuGetVersionable> items, VersionRange ideal)
 {
     return(FindBestMatch <INuGetVersionable>(items, ideal, (e => e.Version)));
 }
		public static async Task<IPackageSearchMetadata> GetLatestPackageMetadataAsync(
			this SourceRepository sourceRepository, string packageId, bool includePrerelease, CancellationToken cancellationToken, VersionRange allowedVersions)
		{
			var metadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource>(cancellationToken);
			var packages = await metadataResource?.GetMetadataAsync(
				packageId,
				includePrerelease,
				false,
				Common.NullLogger.Instance,
				cancellationToken);

			// filter packages based on allowed versions
			var updatedPackages = packages.Where(p => allowedVersions.Satisfies(p.Identity.Version));

			var highest = updatedPackages
				.OrderByDescending(e => e.Identity.Version, VersionComparer.VersionRelease)
				.FirstOrDefault();

			return highest?.WithVersions(ToVersionInfo(packages, includePrerelease));
		}
Beispiel #36
0
        private static VersionRange AggregateVersions(VersionRange aggregate, VersionRange next)
        {
            var versionRange = new VersionRange();
            SetMinVersion(ref versionRange, aggregate);
            SetMinVersion(ref versionRange, next);
            SetMaxVersion(ref versionRange, aggregate);
            SetMaxVersion(ref versionRange, next);

            if (versionRange.MinVersion == null && versionRange.MaxVersion == null)
            {
                versionRange = null;
            }

            return versionRange;
        }
Beispiel #37
0
        /// <summary>
        /// Parses a VersionRange from its string representation.
        /// </summary>
        public static bool TryParse(string value, bool allowFloating, out VersionRange versionRange)
        {
            versionRange = null;

            var trimmedValue = value?.Trim();

            if (string.IsNullOrEmpty(trimmedValue))
            {
                return(false);
            }

            var charArray = trimmedValue.ToCharArray();

            // * is the only 1 char range
            if (allowFloating &&
                charArray.Length == 1 &&
                charArray[0] == '*')
            {
                versionRange = new VersionRange(new NuGetVersion(0, 0, 0), true, null, true, FloatRange.Parse(trimmedValue), originalString: value);
                return(true);
            }

            string       minVersionString = null;
            string       maxVersionString = null;
            var          isMinInclusive   = false;
            var          isMaxInclusive   = false;
            NuGetVersion minVersion       = null;
            NuGetVersion maxVersion       = null;
            FloatRange   floatRange       = null;

            if (charArray[0] == '(' ||
                charArray[0] == '[')
            {
                // The first character must be [ to (
                switch (charArray[0])
                {
                case '[':
                    isMinInclusive = true;
                    break;

                case '(':
                    isMinInclusive = false;
                    break;

                default:
                    return(false);
                }

                // The last character must be ] ot )
                switch (charArray[charArray.Length - 1])
                {
                case ']':
                    isMaxInclusive = true;
                    break;

                case ')':
                    isMaxInclusive = false;
                    break;

                default:
                    return(false);
                }

                // Get rid of the two brackets
                trimmedValue = trimmedValue.Substring(1, trimmedValue.Length - 2);

                // Split by comma, and make sure we don't get more than two pieces
                var parts = trimmedValue.Split(',');

                if (parts.Length > 2)
                {
                    return(false);
                }
                else
                {
                    var allEmpty = true;

                    for (int i = 0; i < parts.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(parts[i]))
                        {
                            allEmpty = false;
                            break;
                        }
                    }

                    // If all parts are empty, then neither of upper or lower bounds were specified. Version spec is of the format (,]
                    if (allEmpty)
                    {
                        return(false);
                    }
                }

                // (1.0.0] and [1.0.0),(1.0.0) are invalid.
                if (parts.Length == 1 &&
                    !(isMinInclusive && isMaxInclusive))
                {
                    return(false);
                }

                // If there is only one piece, we use it for both min and max
                minVersionString = parts[0];
                maxVersionString = (parts.Length == 2) ? parts[1] : parts[0];
            }
            else
            {
                // default to min inclusive when there are no braces
                isMinInclusive = true;

                // use the entire value as the version
                minVersionString = trimmedValue;
            }

            if (!string.IsNullOrWhiteSpace(minVersionString))
            {
                // parse the min version string
                if (allowFloating && minVersionString.Contains("*"))
                {
                    // single floating version
                    if (FloatRange.TryParse(minVersionString, out floatRange) &&
                        floatRange.HasMinVersion)
                    {
                        minVersion = floatRange.MinVersion;
                    }
                    else
                    {
                        // invalid float
                        return(false);
                    }
                }
                else
                {
                    // single non-floating version
                    if (!NuGetVersion.TryParse(minVersionString, out minVersion))
                    {
                        // invalid version
                        return(false);
                    }
                }
            }

            // parse the max version string, the max cannot float
            if (!string.IsNullOrWhiteSpace(maxVersionString))
            {
                if (!NuGetVersion.TryParse(maxVersionString, out maxVersion))
                {
                    // invalid version
                    return(false);
                }
            }

            if (minVersion != null && maxVersion != null)
            {
                int result = minVersion.CompareTo(maxVersion);

                // minVersion > maxVersion
                if (result > 0)
                {
                    return(false);
                }

                // minVersion is equal to maxVersion (1.0.0, 1.0.0], [1.0.0, 1.0.0)
                if (result == 0 &&
                    (isMinInclusive ^ isMaxInclusive))
                {
                    return(false);
                }
            }

            // Successful parse!
            versionRange = new VersionRange(
                minVersion: minVersion,
                includeMinVersion: isMinInclusive,
                maxVersion: maxVersion,
                includeMaxVersion: isMaxInclusive,
                floatRange: floatRange,
                originalString: value);

            return(true);
        }
Beispiel #38
0
        private static void SetMaxVersion(ref VersionRange target, VersionRange source)
        {
            if (source == null || source.MaxVersion == null)
            {
                return;
            }

            bool update = false;
            NuGetVersion maxVersion = target.MaxVersion;
            bool includeMaxVersion = target.IsMaxInclusive;

            if (target.MaxVersion == null)
            {
                update = true;
                maxVersion = source.MaxVersion;
                includeMaxVersion = source.IsMaxInclusive;
            }

            if (target.MaxVersion > source.MaxVersion)
            {
                update = true;
                maxVersion = source.MaxVersion;
                includeMaxVersion = source.IsMaxInclusive;
            }

            if (target.MaxVersion == source.MaxVersion)
            {
                update = true;
                includeMaxVersion = target.IsMaxInclusive && source.IsMaxInclusive;
            }

            if (update)
            {
                target = new VersionRange(target.MinVersion, target.IsMinInclusive, maxVersion, includeMaxVersion, target.IncludePrerelease, target.Float, target.OriginalString);
            }
        }
Beispiel #39
0
 private string GetVersionRangeNormalizedString(string input)
 {
     return(NuGetVersionRange.Parse(input).ToNormalizedString());
 }
Beispiel #40
0
        public static void PopulateDependencies(ProjectContext context, PackageBuilder packageBuilder)
        {
            var dependencies = new List<PackageDependency>();
            var project = context.RootProject;

            foreach (var dependency in project.Dependencies)
            {
                if (!dependency.HasFlag(LibraryDependencyTypeFlag.BecomesNupkgDependency))
                {
                    continue;
                }

                // TODO: Efficiency
                var dependencyDescription = context.LibraryManager.GetLibraries().First(l => l.RequestedRanges.Contains(dependency));

                // REVIEW: Can we get this far with unresolved dependencies
                if (dependencyDescription == null || !dependencyDescription.Resolved)
                {
                    continue;
                }

                if (dependencyDescription.Identity.Type == LibraryType.Project &&
                    ((ProjectDescription)dependencyDescription).Project.EmbedInteropTypes)
                {
                    continue;
                }

                if (dependency.Target == LibraryType.ReferenceAssembly)
                {
                    packageBuilder.FrameworkAssemblies.Add(new FrameworkAssemblyReference(dependency.Name, new[] { context.TargetFramework }));

                    Reporter.Verbose.WriteLine($"Adding framework assembly {dependency.Name.Yellow()}");
                }
                else
                {
                    VersionRange dependencyVersion = null;

                    if (dependency.VersionRange == null ||
                        dependency.VersionRange.IsFloating)
                    {
                        dependencyVersion = new VersionRange(dependencyDescription.Identity.Version);
                    }
                    else
                    {
                        dependencyVersion = dependency.VersionRange;
                    }

                    Reporter.Verbose.WriteLine($"Adding dependency {dependency.Name.Yellow()} {VersionUtility.RenderVersion(dependencyVersion).Yellow()}");

                    dependencies.Add(new PackageDependency(dependency.Name, dependencyVersion));
                }
            }

            packageBuilder.DependencySets.Add(new PackageDependencySet(context.TargetFramework, dependencies));
        }