Ejemplo n.º 1
0
        private async Task <PackageReaderBase> DownloadPackage(
            SourcePackageDependencyInfo packageToInstall,
            PackageExtractionContext packageExtractionContext,
            ILogger nugetLogger)
        {
            nugetLogger.LogInformationSummary($"Downloading {Display(packageToInstall)}");
            var downloadResource = await packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None);

            using (var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                       packageToInstall,
                       new PackageDownloadContext(nugetCache),
                       globalPackageFolder,
                       nugetLogger, CancellationToken.None))
            {
                nugetLogger.LogInformationSummary($"Extracting {Display(packageToInstall)}");
                await PackageExtractor.ExtractPackageAsync(
                    downloadResult.PackageSource,
                    downloadResult.PackageStream,
                    packagePathResolver,
                    packageExtractionContext,
                    CancellationToken.None);

                return(downloadResult.PackageReader);
            }
        }
Ejemplo n.º 2
0
        private async Task GetPackageDependenciesAsync(PackageIdentity package,
                                                       NuGetFramework framework,
                                                       SourceCacheContext cacheContext,
                                                       ILogger logger,
                                                       IEnumerable <SourceRepository> repositories,
                                                       ISet <SourcePackageDependencyInfo> availablePackages)
        {
            if (availablePackages.Contains(package))
            {
                return;
            }

            foreach (SourceRepository sourceRepository in repositories)
            {
                DependencyInfoResource dependencyInfoResource = await sourceRepository.GetResourceAsync <DependencyInfoResource>();

                SourcePackageDependencyInfo dependencyInfo = await dependencyInfoResource.ResolvePackage(
                    package, framework, cacheContext, logger, CancellationToken.None);

                if (dependencyInfo == null)
                {
                    continue;
                }

                availablePackages.Add(dependencyInfo);
                foreach (PackageDependency dependency in dependencyInfo.Dependencies)
                {
                    await GetPackageDependenciesAsync(
                        new PackageIdentity(dependency.Id, dependency.VersionRange.MinVersion),
                        framework, cacheContext, logger, repositories, availablePackages);
                }
            }
        }
        /// <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, Common.ILogger log, 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, log, 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 FatalProtocolException(error, ex);
            }
        }
Ejemplo n.º 4
0
        public async Task DownloadResourceFromUrl()
        {
            // Arrange
            var repo = Repository.Factory.GetCoreV3(TestSources.NuGetV2Uri);

            var downloadResource = await repo.GetResourceAsync <DownloadResource>();

            var package = new SourcePackageDependencyInfo("WindowsAzure.Storage", new NuGetVersion("6.2.0"), null, true, repo, new Uri($@"{TestSources.NuGetV2Uri}/package/WindowsAzure.Storage/6.2.0"), "");

            // Act & Assert
            using (var packagesFolder = TestDirectory.Create())
                using (var cacheContext = new SourceCacheContext())
                    using (var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                               package,
                               new PackageDownloadContext(cacheContext),
                               packagesFolder,
                               NullLogger.Instance,
                               CancellationToken.None))
                    {
                        var packageReader = downloadResult.PackageReader;
                        var files         = packageReader.GetFiles();

                        Assert.Equal(13, files.Count());
                    }
        }
Ejemplo n.º 5
0
        public async Task GetPackageDependencies(PackageIdentity package, SourceCacheContext cacheContext, ISet <SourcePackageDependencyInfo> availablePackages)
        {
            if (availablePackages.Contains(package))
            {
                return;
            }
            var repositories = GetSortedRepositories();

            foreach (var sourceRepository in repositories)
            {
                SourcePackageDependencyInfo dependencyInfo = null;
                try
                {
                    var dependencyInfoResource = await sourceRepository.GetResourceAsync <DependencyInfoResource>();

                    dependencyInfo = await dependencyInfoResource.ResolvePackage(
                        package, NuGetFramework, cacheContext, NullLogger.Instance, CancellationToken.None);

                    if (dependencyInfo == null)
                    {
                        continue;
                    }
                    availablePackages.Add(dependencyInfo);
                }
                catch (Exception ex)
                {
                }
                foreach (var dependency in dependencyInfo.Dependencies)
                {
                    var identity = new PackageIdentity(dependency.Id, dependency.VersionRange.MinVersion);
                    await GetPackageDependencies(identity, cacheContext, availablePackages);
                }
                break;
            }
        }
Ejemplo n.º 6
0
        private async Task <DownloadResourceResult> DownloadPackageResourceAsync(
            SourcePackageDependencyInfo package, SourceCacheContext cacheContext, CancellationToken cancellationToken, string globalFolder = "")
        {
            if (string.Equals(globalFolder, ""))
            {
                globalFolder = DefaultNuGetFolders.GetGlobalPackagesFolder();
            }

            using (var progressToken = await _downloadingProgressTrackerService?.TrackDownloadOperationAsync(this, package))
            {
                var downloadResource = await package.Source.GetResourceAsync <DownloadResource>(cancellationToken);

                var packageDownloadContext = new PackageDownloadContext(cacheContext);

                var downloadResult = await downloadResource.GetDownloadResourceResultAsync
                                     (
                    package,
                    new PackageDownloadContext(cacheContext),
                    globalFolder,
                    _nugetLogger,
                    cancellationToken
                                     );

                return(downloadResult);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Convert a V2 feed package into a V3 PackageDependencyInfo
        /// </summary>
        private SourcePackageDependencyInfo CreateDependencyInfo(
            V2FeedPackageInfo packageVersion,
            NuGetFramework projectFramework)
        {
            var deps = Enumerable.Empty <PackageDependency>();

            var identity = new PackageIdentity(packageVersion.Id, NuGetVersion.Parse(packageVersion.Version.ToString()));

            if (packageVersion.DependencySets != null &&
                packageVersion.DependencySets.Any())
            {
                // Take only the dependency group valid for the project TFM
                var nearestFramework = _frameworkReducer.GetNearest(
                    projectFramework,
                    packageVersion.DependencySets.Select(group => group.TargetFramework));

                if (nearestFramework != null)
                {
                    var matches = packageVersion.DependencySets.Where(e => (e.TargetFramework.Equals(nearestFramework)));
                    deps = matches.First().Packages;
                }
            }

            var result = new SourcePackageDependencyInfo(
                identity,
                deps,
                packageVersion.IsListed,
                _source,
                new Uri(packageVersion.DownloadUrl),
                packageVersion.PackageHash);

            return(result);
        }
        public async Task DownloadResourceFromInvalidIdInUrl()
        {
            // Arrange
            var repo = Repository.Factory.GetCoreV3(TestSources.NuGetV2Uri);

            var downloadResource = await repo.GetResourceAsync <DownloadResource>();

            var package = new SourcePackageDependencyInfo("not-found", new NuGetVersion("6.2.0"), null, true, repo, new Uri($@"{TestSources.NuGetV2Uri}/package/not-found/6.2.0"), "");

            // Act
            using (var packagesFolder = TestDirectory.Create())
                using (var cacheContext = new SourceCacheContext())
                {
                    var actual = await downloadResource.GetDownloadResourceResultAsync(
                        package,
                        new PackageDownloadContext(cacheContext),
                        packagesFolder,
                        NullLogger.Instance,
                        CancellationToken.None);

                    // Assert
                    Assert.NotNull(actual);
                    Assert.Equal(DownloadResourceResultStatus.NotFound, actual.Status);
                }
        }
        private static string FormatDependencyConstraint(SourcePackageDependencyInfo package, PackageDependency dependency)
        {
            var range            = dependency.VersionRange;
            var dependencyString = $"{dependency.Id} {range?.ToNonSnapshotRange().PrettyPrint() ?? string.Empty}";

            // A 1.0.0 dependency: B (= 1.5)
            return($"'{package.Id} {package.Version.ToNormalizedString()} {Strings.DependencyConstraint}: {dependencyString}'");
        }
        GetDependencies
        (
            string id,
            string version
        )
        {
            DependencyInfoResource resource = await repository.GetResourceAsync <DependencyInfoResource>(CancellationToken.None);

            SourcePackageDependencyInfo package = await resource.ResolvePackage
                                                  (
                new PackageIdentity(id, new NuGetVersion(version)),
                NuGetFramework.AnyFramework,
                source_cache,
                logger,
                cancellationToken
                                                  );

            if (package == null)
            {
                throw new InvalidOperationException("Could not locate dependency!");
            }

            //System.Collections.Concurrent.ConcurrentBag<string> dependency_collection;
            //dependency_collection = new System.Collections.Concurrent.ConcurrentBag<string>();

            Graph <string, string> dependency_graph = new Graph <string, string>();

            foreach (var dependency in package.Dependencies)
            {
                Node <string> dependency_node = new Node <string>()
                {
                };
                //dependency_collection.Add(dependency.Id + " " + dependency.VersionRange.MinVersion);
            }

            await Task.WhenAll
            (
                package.Dependencies.Select
                (
                    async(d) =>
            {
                var rec = await GetDependencies
                          (
                    d.Id,
                    d.VersionRange.MinVersion.ToNormalizedString()
                          );

                foreach (string s in rec)
                {
                    dependency_collection.Add(s);
                }
            }
                )
            );

            return(dependency_collection);
        }
        /// <summary>
        /// Add a single package
        /// </summary>
        public void AddPackageFromSingleVersionLookup(
            Configuration.PackageSource source,
            PackageIdentity identity,
            NuGetFramework framework,
            SourcePackageDependencyInfo package)
        {
            var key = new GatherSingleCacheKey(identity, source, framework);

            _singleVersion.TryAdd(key, package);
        }
Ejemplo n.º 12
0
        public async Task <IEnumerable <SourcePackageDependencyInfo> > GetPackageAndDependencies(
            PackageIdentity packageId,
            NuGetFramework packageFramework,
            string[] omitDependencies)
        {
            var availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default);

            await DoGetPackageDependencies(packageId);

            return(availablePackages);

            async Task DoGetPackageDependencies(PackageIdentity p)
            {
                if (availablePackages.Contains(p))
                {
                    return;
                }

                foreach (var sourceRepository in _repositories)
                {
                    var dependencyInfoResource = await sourceRepository.GetResourceAsync <DependencyInfoResource>();

                    var dependencyInfo = await dependencyInfoResource.ResolvePackage(p, packageFramework,
                                                                                     _sourceCacheContext, _logger, CancellationToken.None);

                    if (dependencyInfo == null)
                    {
                        continue;
                    }

                    if (omitDependencies.Any() && dependencyInfo.Dependencies.Any(d => omitDependencies.Contains(d.Id)))
                    {
                        var packageDependencies =
                            dependencyInfo.Dependencies
                            .Where(d => !omitDependencies.Contains(d.Id))
                            .Select(d => d);

                        dependencyInfo = new SourcePackageDependencyInfo(
                            dependencyInfo.Id,
                            dependencyInfo.Version,
                            packageDependencies,
                            dependencyInfo.Listed,
                            dependencyInfo.Source);
                    }

                    availablePackages.Add(dependencyInfo);

                    foreach (var dependency in dependencyInfo.Dependencies)
                    {
                        var packageIdentity = new PackageIdentity(dependency.Id, dependency.VersionRange.MinVersion);
                        await DoGetPackageDependencies(packageIdentity);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// This methods updates the project's .csproj file. It adds all the installed packages to the .csproj file.
        /// </summary>
        /// <param name="packageReader">The <see cref="PackageReaderBase"/> to use in reading the nuget package</param>
        /// <param name="installedPath">The folder path where the package was installed or downloaded to</param>
        /// <param name="packageToInstall">The package to install with all its dependencies.</param>
        /// <param name="nuGetFramework">The <see cref="NuGetFramework"/></param>
        private void UpdateProjectFile(
            PackageReaderBase packageReader,
            string installedPath,
            SourcePackageDependencyInfo packageToInstall,
            NuGetFramework nuGetFramework)
        {
            IEnumerable <FrameworkSpecificGroup> dllItems = packageReader.GetLibItems();

            if (dllItems != null)
            {
                FrameworkReducer frameworkReducer   = new FrameworkReducer();
                NuGetFramework   nearest            = frameworkReducer.GetNearest(nuGetFramework, dllItems.Select(x => x.TargetFramework));
                string           targetDllFramework = dllItems
                                                      .Where(x => x.TargetFramework.Equals(nearest))
                                                      .SelectMany(x => x.Items).Where(x => x.Contains(".dll")).FirstOrDefault();

                if (!string.IsNullOrEmpty(targetDllFramework) && !string.IsNullOrEmpty(installedPath))
                {
                    string      targetDllFrameworkPath = Path.Combine(installedPath, targetDllFramework.ToString());
                    string      dllName = Assembly.LoadFile(targetDllFrameworkPath).FullName;
                    string      dllNameWithProcessArchitecture = dllName + "," + " processorArchitecture=MSIL";
                    ProjectItem item = this.project.GetItems("Reference").FirstOrDefault(a => a.EvaluatedInclude.Contains(packageToInstall.Id));
                    if (item == null)
                    {
                        if (ProjectHelper.CheckIfSolutionAndProjectFilesAreInSameFolder(this.project.DirectoryPath))
                        {
                            ProjectItem projectItem = this.project.AddItem("Reference", dllNameWithProcessArchitecture).FirstOrDefault();
                            projectItem.HasMetadata("HintPath");
                            projectItem.SetMetadataValue("HintPath", $"packages\\{packageToInstall.Id}.{ packageToInstall.Version}\\{targetDllFramework.Replace(@"/", "\\")}".Replace(@"\\", "//"));
                        }
                        else
                        {
                            ProjectItem projectItem = this.project.AddItem("Reference", dllNameWithProcessArchitecture).FirstOrDefault();
                            projectItem.SetMetadataValue("HintPath", $"..\\packages\\{packageToInstall.Id}.{ packageToInstall.Version}\\{targetDllFramework.Replace(@"/", "\\")}".Replace(@"\\", "//"));
                        }

                        this.project.Save();
                    }

                    ProjectItem dataAnnotationsRef = this.project.GetItems("Reference").FirstOrDefault(a => a.EvaluatedInclude.Contains("System.ComponentModel.DataAnnotations"));
                    if (dataAnnotationsRef == null)
                    {
                        ProjectHelper.AddProjectItem(this.project, "Reference", "System.ComponentModel.DataAnnotations");
                    }

                    ProjectItem packageConfigRef = this.project.GetItems("None").FirstOrDefault(a => a.EvaluatedInclude.Contains("packages.config"));
                    if (packageConfigRef == null)
                    {
                        ProjectHelper.AddProjectItem(this.project, "None", "packages.config");
                    }
                }
            }
        }
Ejemplo n.º 14
0
        SourcePackageDependencyInfo ApplySource(SourcePackageDependencyInfo original)
        {
            if (original == null)
            {
                return(null);
            }

            return(new SourcePackageDependencyInfo(
                       original.Id,
                       original.Version,
                       original.Dependencies,
                       original.Listed,
                       Source));
        }
        private DownloadResourceResult DownloadFromUrl(
            SourcePackageDependencyInfo package,
            DataServicePackageRepository repository,
            NuGet.Common.ILogger logger,
            CancellationToken token)
        {
            IPackage newPackage      = null;
            var      version         = SemanticVersion.Parse(package.Version.ToString());
            var      cacheRepository = MachineCache.Default;

            try
            {
                // Try finding the package in the machine cache
                var localPackage = cacheRepository.FindPackage(package.Id, version)
                                   as OptimizedZipPackage;

                // Validate the package matches the hash
                if (localPackage != null &&
                    localPackage.IsValid &&
                    MatchPackageHash(localPackage, package.PackageHash))
                {
                    newPackage = localPackage;
                }
            }
            catch
            {
                // Ignore cache failures here to match NuGet.Core
                // The bad package will be deleted and replaced during the download.
            }

            // If the local package does not exist in the cache download it from the source
            if (newPackage == null)
            {
                newPackage = DownloadToMachineCache(
                    cacheRepository,
                    package,
                    repository,
                    package.DownloadUri,
                    logger,
                    token);
            }

            // Read the package from the machine cache
            if (newPackage != null)
            {
                return(new DownloadResourceResult(newPackage.GetStream()));
            }

            return(null);
        }
        private static IEnumerable <PackageDependency> GetBrokenDependencies(SourcePackageDependencyInfo package, IEnumerable <PackageIdentity> packages)
        {
            foreach (var dependency in package.Dependencies)
            {
                var target = packages.FirstOrDefault(targetPackage => StringComparer.OrdinalIgnoreCase.Equals(targetPackage.Id, dependency.Id));

                if (!ResolverUtility.IsDependencySatisfied(dependency, target))
                {
                    yield return(dependency);
                }
            }

            yield break;
        }
Ejemplo n.º 17
0
        public static async Task <PackageInformation> DetermineNewestPackage(List <SourceRepository> sourceRepositories, string packageId)
        {
            SourcePackageDependencyInfo latestPackage            = null;
            SourceRepository            selectedSourceRepository = null;

            foreach (var sourceRepository in sourceRepositories)
            {
                if (sourceRepository.PackageSource?.Credentials?.Password != null)
                {
                    await sourceRepository.GetResourceAsync <HttpHandlerResource>();
                }
                var resource = await sourceRepository.GetResourceAsync <DependencyInfoResource>();

                if (resource != null)
                {
                    var results = await resource.ResolvePackages(packageId, NuGetFramework.AnyFramework, new Common.NullLogger(), CancellationToken.None);

                    if (results.Count() > 0)
                    {
                        foreach (var result in results)
                        {
                            if (latestPackage == null)
                            {
                                latestPackage            = result;
                                selectedSourceRepository = sourceRepository;
                            }
                            else
                            {
                                if (result.Version.CompareTo(latestPackage.Version) > 0)
                                {
                                    latestPackage            = result;
                                    selectedSourceRepository = sourceRepository;
                                }
                            }
                        }
                        break;
                    }
                }
            }

            if (latestPackage == null && selectedSourceRepository == null)
            {
                return(null);
            }
            else
            {
                return(new PackageInformation(latestPackage, selectedSourceRepository));
            }
        }
        /// <summary>
        /// Convert a V2 IPackage into a V3 PackageDependencyInfo
        /// </summary>
        private SourcePackageDependencyInfo CreateDependencyInfo(IPackage packageVersion, NuGetFramework projectFramework)
        {
            var deps = Enumerable.Empty <V3PackageDependency>();

            var identity = new PackageIdentity(packageVersion.Id, NuGetVersion.Parse(packageVersion.Version.ToString()));

            if (packageVersion.DependencySets != null &&
                packageVersion.DependencySets.Any())
            {
                // Take only the dependency group valid for the project TFM
                var nearestFramework = _frameworkReducer.GetNearest(projectFramework, packageVersion.DependencySets.Select(GetFramework));

                if (nearestFramework != null)
                {
                    var matches = packageVersion.DependencySets.Where(e => (GetFramework(e).Equals(nearestFramework)));
                    IEnumerable <PackageDependency> dependencies = matches.First().Dependencies;
                    deps = dependencies.Select(item => GetPackageDependency(item));
                }
            }

            SourcePackageDependencyInfo result = null;

            var dataPackage = packageVersion as DataServicePackage;

            if (dataPackage != null)
            {
                // Online package
                result = new SourcePackageDependencyInfo(
                    identity,
                    deps,
                    PackageExtensions.IsListed(packageVersion),
                    _source,
                    dataPackage.DownloadUrl,
                    dataPackage.PackageHash);
            }
            else
            {
                // Offline package
                result = new SourcePackageDependencyInfo(
                    identity,
                    deps,
                    PackageExtensions.IsListed(packageVersion),
                    _source,
                    downloadUri: null,
                    packageHash: null);
            }

            return(result);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Convert a package into a PackageDependencyInfo
        /// </summary>
        private SourcePackageDependencyInfo CreateDependencyInfo(LocalPackageInfo package, NuGetFramework projectFramework)
        {
            // Take only the dependency group valid for the project TFM
            var group        = NuGetFrameworkUtility.GetNearest <PackageDependencyGroup>(package.Nuspec.GetDependencyGroups(), projectFramework);
            var dependencies = group?.Packages ?? Enumerable.Empty <PackageDependency>();

            var result = new SourcePackageDependencyInfo(
                package.Identity,
                dependencies,
                listed: true,
                source: _source,
                downloadUri: UriUtility.CreateSourceUri(package.Path, UriKind.Absolute),
                packageHash: null);

            return(result);
        }
Ejemplo n.º 20
0
        public async Task <NuGetPackageFilterResult> FilterAsync(SourceRepository repository, IPackageSearchMetadata package, CancellationToken cancellationToken)
        {
            if (!dependencies.Any())
            {
                return(NuGetPackageFilterResult.Ok);
            }

            DependencyInfoResource resource = await repository.GetResourceAsync <DependencyInfoResource>();

            if (resource == null)
            {
                return(NuGetPackageFilterResult.NotCompatible);
            }

            NuGetPackageFilterResult result = NuGetPackageFilterResult.Ok;

            foreach (NuGetFramework framework in frameworks)
            {
                SourcePackageDependencyInfo dependencyInfo = await resource.ResolvePackage(package.Identity, framework, new SourceCacheContext(), nuGetLogger, cancellationToken);

                if (dependencyInfo != null)
                {
                    // Dependency filtering:
                    // - When incompatible dependency version is found there is a chance that previous version has the right one.
                    // - When all dependencies are missing, don't even try previous versions.
                    foreach (var dependency in dependencies)
                    {
                        PackageDependency packageDependency = dependencyInfo.Dependencies.FirstOrDefault(p => string.Equals(p.Id, dependency.Id, StringComparison.CurrentCultureIgnoreCase));
                        if (packageDependency == null)
                        {
                            log.Info($"Package '{package.Identity}' skipped: missing dependency '{dependency.Id}'.");
                            result = NuGetPackageFilterResult.NotCompatible;
                        }

                        if (dependency.Version != null && !packageDependency.VersionRange.Satisfies(new NuGetVersion(dependency.Version)))
                        {
                            log.Info($"Package '{package.Identity}' skipped: not compatible version '{dependency.Version}' on dependency '{dependency.Id}'.");
                            return(NuGetPackageFilterResult.NotCompatibleVersion);
                        }
                    }

                    return(result);
                }
            }

            return(NuGetPackageFilterResult.NotCompatible);
        }
Ejemplo n.º 21
0
        private async Task DoSearch(NuGetFactory factory, D3DependencyChild current,
                                    int maxLevel,
                                    PackageIdentity package, NuGetFramework fx)
        {
            if (current.Level > maxLevel)
            {
                return;
            }

            // same package may be traversed multiple times, so we can cache it
            // don't cache the tree as depth may change for the same package
            SourcePackageDependencyInfo packageDependencyInfo = await CacheResolvePackage(factory, package, fx);

            if (packageDependencyInfo.Dependencies.Any())
            {
                if (current.children == null)
                {
                    current.children = new List <D3DependencyChild>();
                }

                foreach (var dependency in packageDependencyInfo.Dependencies)
                {
                    // unlikely that the version of a particular dependency will change in 30 minutes
                    // so we can cache it
                    IEnumerable <NuGetVersion> allVersions = await CacheGetAllVersionsOfDependency(factory, dependency);

                    if (allVersions.Any())
                    {
                        var bestMatch = dependency.VersionRange.FindBestMatch(allVersions);

                        var child = new D3DependencyChild
                        {
                            key     = dependency.Id,
                            version = bestMatch.Version.ToString(),
                            parent  = current.key,
                            Level   = current.Level + 1
                        };

                        current.children.Add(child);

                        var nextPackage = new PackageIdentity(child.key, bestMatch);
                        await DoSearch(factory, child, maxLevel, nextPackage, fx);
                    }
                }
            }
        }
        /// <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 Task <SourcePackageDependencyInfo> ResolvePackage(PackageIdentity package, NuGetFramework projectFramework, Common.ILogger log, CancellationToken token)
        {
            if (package == null)
            {
                throw new ArgumentNullException(null, nameof(package));
            }

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

            SourcePackageDependencyInfo result = null;

            SemanticVersion legacyVersion;

            // attempt to parse the semver into semver 1.0.0, if this fails then the v2 client would
            // not be able to find it anyways and we should return null
            if (SemanticVersion.TryParse(package.Version.ToString(), out legacyVersion))
            {
                try
                {
                    // Retrieve all packages
                    var repoPackage = GetRepository().FindPackage(
                        package.Id,
                        legacyVersion,
                        allowPrereleaseVersions: true,
                        allowUnlisted: true);

                    if (repoPackage != null)
                    {
                        // convert to v3 type
                        result = CreateDependencyInfo(repoPackage, projectFramework);
                    }
                }
                catch (Exception ex)
                {
                    // Wrap exceptions coming from the server with a user friendly message
                    var error = String.Format(CultureInfo.CurrentUICulture, Strings.Protocol_PackageMetadataError, package, V2Client.Source);

                    throw new FatalProtocolException(error, ex);
                }
            }

            return(Task.FromResult(result));
        }
Ejemplo n.º 23
0
        public async Task <string> GetLatestVersionAsync(string packageId)
        {
            using (SourceCacheContext cacheContext = new SourceCacheContext())
            {
                IEnumerable <SourceRepository> repositories = _sourceRepositoryProvider.GetRepositories();

                foreach (var repo in repositories)
                {
                    DependencyInfoResource dependencyInfoResource      = repo.GetResource <DependencyInfoResource>();
                    IEnumerable <SourcePackageDependencyInfo> packages = await dependencyInfoResource.ResolvePackages(packageId, _nuGetFramework, cacheContext, _logger, CancellationToken.None);

                    if (packages != null && packages.Count() > 0)
                    {
                        SourcePackageDependencyInfo version = packages.Where(p => p.Listed && !p.Version.IsPrerelease).OrderByDescending(x => x.Version).First();
                        return(version.Version.ToNormalizedString());
                    }
                }
                return(null);
            }
        }
        public async Task DownloadResourceFromInvalidIdInUrl()
        {
            // Arrange
            var repo = Repository.Factory.GetCoreV3(TestServers.NuGetV2);

            var downloadResource = await repo.GetResourceAsync <DownloadResource>();

            var package = new SourcePackageDependencyInfo("not-found", new NuGetVersion("6.2.0"), null, true, repo, new Uri($@"{TestServers.NuGetV2}/package/not-found/6.2.0"), "");

            // Act
            var actual = await downloadResource.GetDownloadResourceResultAsync(
                package,
                NullSettings.Instance,
                NullLogger.Instance,
                CancellationToken.None);

            // Assert
            Assert.NotNull(actual);
            Assert.Equal(DownloadResourceResultStatus.NotFound, actual.Status);
        }
        public async Task DownloadResourceFromUrl()
        {
            // Arrange
            var repo = Repository.Factory.GetCoreV3(TestServers.NuGetV2);

            var downloadResource = await repo.GetResourceAsync <DownloadResource>();

            var package = new SourcePackageDependencyInfo("WindowsAzure.Storage", new NuGetVersion("6.2.0"), null, true, repo, new Uri($@"{TestServers.NuGetV2}/package/WindowsAzure.Storage/6.2.0"), "");

            // Act & Assert
            using (var downloadResult = await downloadResource.GetDownloadResourceResultAsync(package,
                                                                                              NullSettings.Instance,
                                                                                              NullLogger.Instance,
                                                                                              CancellationToken.None))
            {
                var packageReader = downloadResult.PackageReader;
                var files         = packageReader.GetFiles();

                Assert.Equal(11, files.Count());
            }
        }
        /// <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>
        public override Task <SourcePackageDependencyInfo> ResolvePackage(
            PackageIdentity package,
            NuGetFramework projectFramework,
            SourceCacheContext sourceCacheContext,
            ILogger log,
            CancellationToken token)
        {
            if (package == null)
            {
                throw new ArgumentNullException(null, nameof(package));
            }

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

            SourcePackageDependencyInfo result = null;

            try
            {
                // Retrieve all packages
                var repoPackage = _localResource.GetPackage(package, log, token);

                if (repoPackage != null)
                {
                    // convert to v3 type
                    result = CreateDependencyInfo(repoPackage, projectFramework);
                }
            }
            catch (Exception ex)
            {
                // Wrap exceptions coming from the server with a user friendly message
                var error = string.Format(CultureInfo.CurrentUICulture, Strings.Protocol_PackageMetadataError, package, _localResource.Root);

                throw new FatalProtocolException(error, ex);
            }

            return(Task.FromResult(result));
        }
Ejemplo n.º 27
0
        public async Task <(PackageReaderBase package, string installPath)> DownloadPackage(
            SourcePackageDependencyInfo packageToInstall)
        {
            var packagePathResolver      = new PackagePathResolver(Path.GetFullPath("packages"));
            var packageExtractionContext =
                new PackageExtractionContext(
                    PackageSaveMode.Defaultv3,
                    XmlDocFileSaveMode.None,
                    ClientPolicyContext.GetClientPolicy(_settings, _logger),
                    _logger);

            var installedPath = packagePathResolver.GetInstalledPath(packageToInstall);

            if (installedPath != null)
            {
                return(new PackageFolderReader(installedPath), installedPath);
            }

            var downloadResource =
                await packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None);

            var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                packageToInstall,
                new PackageDownloadContext(_sourceCacheContext),
                SettingsUtility.GetGlobalPackagesFolder(_settings),
                _logger,
                CancellationToken.None);

            await PackageExtractor.ExtractPackageAsync(
                downloadResult.PackageSource,
                downloadResult.PackageStream,
                packagePathResolver,
                packageExtractionContext,
                CancellationToken.None);

            installedPath = packagePathResolver.GetInstalledPath(packageToInstall);

            return(downloadResult.PackageReader, installedPath);
        }
Ejemplo n.º 28
0
        public async Task GetPackageDependencies(PackageIdentity package, SourceCacheContext cacheContext, ISet <SourcePackageDependencyInfo> availablePackages)
        {
            if (availablePackages.Contains(package))
            {
                return;
            }

            //var repositories = SourceRepositoryProvider.GetRepositories();
            var repositories = GetSortedRepositories();

            foreach (var sourceRepository in repositories)
            {
                SourcePackageDependencyInfo dependencyInfo = null;
                // #11 Tighten the try-catch scope due to localization probrem.
                try
                {
                    var dependencyInfoResource = await sourceRepository.GetResourceAsync <DependencyInfoResource>();

                    dependencyInfo = await dependencyInfoResource.ResolvePackage(
                        package, NuGetFramework, Logger, CancellationToken.None);

                    if (dependencyInfo == null)
                    {
                        continue;
                    }
                    availablePackages.Add(dependencyInfo);
                }
                catch (Exception err)
                {
                }
                foreach (var dependency in dependencyInfo.Dependencies)
                {
                    var identity = new PackageIdentity(dependency.Id, dependency.VersionRange.MinVersion);
                    await GetPackageDependencies(identity, cacheContext, availablePackages);
                }

                break;//只要有一个源能搜索到就不再往下搜索了
            }
        }
Ejemplo n.º 29
0
        private async Task<PackageReaderBase> ExtractPackage(
            SourcePackageDependencyInfo packageInfo,
            NuGetFramework projectFramework,
            SourceCacheContext cacheContext,
            PackageExtractionContext packageExtractionContext,
            ILogger logger,
            CancellationToken token)
        {
            logger.LogInformation($"Installing package '{packageInfo.Id} {packageInfo.Version}'.");
            var downloadResource = await packageInfo.Source.GetResourceAsync<DownloadResource>(token);
            var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                packageInfo,
                new PackageDownloadContext(cacheContext),
                SettingsUtility.GetGlobalPackagesFolder(Settings),
                logger, token);

            var installPath = PathResolver.GetInstallPath(packageInfo);
            foreach (var plugin in PackageManagerPlugins)
            {
                var accepted = await plugin.OnPackageInstallingAsync(packageInfo, projectFramework, downloadResult.PackageReader, installPath);
                if (!accepted) return downloadResult.PackageReader;
            }

            await PackageExtractor.ExtractPackageAsync(
                downloadResult.PackageSource,
                downloadResult.PackageStream,
                PathResolver,
                packageExtractionContext,
                token);

            installPath = PathResolver.GetInstalledPath(packageInfo);
            foreach (var plugin in PackageManagerPlugins)
            {
                await plugin.OnPackageInstalledAsync(packageInfo, projectFramework, downloadResult.PackageReader, installPath);
            }
            return downloadResult.PackageReader;
        }
        public static IEnumerable <SourcePackageDependencyInfo> PruneAllButHighest(IEnumerable <SourcePackageDependencyInfo> packages, string packageId)
        {
            SourcePackageDependencyInfo highest = null;

            foreach (var package in packages)
            {
                if (string.Equals(package.Id, packageId, StringComparison.OrdinalIgnoreCase))
                {
                    if (highest == null || highest.Version < package.Version)
                    {
                        highest = package;
                    }
                }
            }

            if (highest == null)
            {
                return(packages);
            }
            else
            {
                return(packages.Where(p => !p.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase) || p == highest));
            }
        }