示例#1
0
        private static NuGetVersion GetNuGetVersion(PackageReference package, NuGetSourceRepositoryProvider sourceRepositoryProvider, NuGetFramework targetFramework, ILogger logger)
        {
            if (package.Parameters.ContainsKey("version"))
            {
                return(new NuGetVersion(package.Parameters["version"].First()));
            }

            var includePrerelease = package.IsPrerelease();

            foreach (var sourceRepository in sourceRepositoryProvider.GetRepositories())
            {
                var dependencyInfoResource = sourceRepository.GetResourceAsync <DependencyInfoResource>().Result;
                var dependencyInfo         = dependencyInfoResource.ResolvePackages(package.Package, targetFramework, logger, CancellationToken.None).Result;
                var version = dependencyInfo
                              .Where(p => p.Listed && (includePrerelease || !p.Version.IsPrerelease))
                              .OrderByDescending(p => p.Version, VersionComparer.Default)
                              .Select(p => p.Version)
                              .FirstOrDefault();

                if (version != null)
                {
                    return(version);
                }
            }
            return(null);
        }
示例#2
0
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            var packageRoot              = path.MakeAbsolute(_environment).FullPath;
            var targetFramework          = type == PackageType.Addin ? _currentFramework : NuGetFramework.AnyFramework;
            var sourceRepositoryProvider = new NuGetSourceRepositoryProvider(_nugetSettings, _config, package);
            var packageIdentity          = GetPackageId(package, sourceRepositoryProvider, targetFramework, _nugetLogger);

            if (packageIdentity == null)
            {
                return(Array.Empty <IFile>());
            }

            var pathResolver   = new PackagePathResolver(packageRoot);
            var project        = new NugetFolderProject(_fileSystem, _contentResolver, _config, _log, pathResolver, packageRoot, targetFramework);
            var packageManager = new NuGetPackageManager(sourceRepositoryProvider, _nugetSettings, project.Root)
            {
                PackagesFolderNuGetProject = project
            };
            var includePrerelease  = package.IsPrerelease();
            var dependencyBehavior = GetDependencyBehavior(type, package);
            var resolutionContext  = new ResolutionContext(dependencyBehavior, includePrerelease, false, VersionConstraints.None, _gatherCache);
            var projectContext     = new NuGetProjectContext(_log);

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var downloadContext = new PackageDownloadContext(sourceCacheContext);

                // First get the install actions.
                // This will give us the list of packages to install, and which feed should be used.
                var actions = packageManager.GetInstallProjectActionsAsync(
                    project,
                    packageIdentity,
                    resolutionContext,
                    projectContext,
                    sourceRepositoryProvider.GetRepositories(),
                    CancellationToken.None).Result;

                // Then install the packages.
                packageManager.ExecuteNuGetProjectActionsAsync(
                    project,
                    actions,
                    projectContext,
                    downloadContext,
                    CancellationToken.None).Wait();
            }

            return(project.GetFiles(path, package, type));
        }
示例#3
0
        private static NuGetVersion GetNuGetVersion(PackageReference package, NuGetPackageManager packageManager, NuGetSourceRepositoryProvider sourceRepositoryProvider, NuGetFramework targetFramework, SourceCacheContext sourceCacheContext, ILogger logger)
        {
            if (package.Parameters.ContainsKey("version"))
            {
                return(new NuGetVersion(package.Parameters["version"].First()));
            }

            // Only search for latest version in local and primary sources.
            var repositories = new HashSet <SourceRepository>(new SourceRepositoryComparer());

            repositories.Add(packageManager.PackagesFolderSourceRepository);
            repositories.AddRange(packageManager.GlobalPackageFolderRepositories);
            repositories.AddRange(sourceRepositoryProvider.GetPrimaryRepositories());

            var          includePrerelease = package.IsPrerelease();
            NuGetVersion version           = null;

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

                    // Find the highest possible version
                    version = version ?? foundVersion;
                    if (foundVersion != null &&
                        version != null &&
                        foundVersion > version)
                    {
                        version = foundVersion;
                    }
                }
                catch (AggregateException ae)
                {
                    ae.Handle(e =>
                    {
                        logger.LogWarning(e.Message);
                        return(true);
                    });
                }
            }
            return(version);
        }
示例#4
0
        private static NuGetVersion GetNuGetVersion(PackageReference package, IEnumerable <SourceRepository> repositories, NuGetFramework targetFramework, SourceCacheContext sourceCacheContext, ILogger logger)
        {
            NuGetVersion version      = null;
            VersionRange versionRange = null;

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

            var includePrerelease = package.IsPrerelease();

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

                    // Find the highest possible version
                    if (version == null || foundVersion > version)
                    {
                        version = foundVersion;
                    }
                }
                catch (AggregateException ae)
                {
                    ae.Handle(e =>
                    {
                        logger.LogWarning(e.Message);
                        return(true);
                    });
                }
            }
            return(version);
        }
示例#5
0
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            var packageRoot              = path.MakeAbsolute(_environment).FullPath;
            var targetFramework          = type == PackageType.Addin ? _currentFramework : NuGetFramework.AnyFramework;
            var sourceRepositoryProvider = new NuGetSourceRepositoryProvider(_nugetSettings, _config, package);

            sourceRepositoryProvider.CreateRepository(packageRoot);
            var packageIdentity = GetPackageId(package, sourceRepositoryProvider, targetFramework, _nugetLogger);

            if (packageIdentity == null)
            {
                return(Array.Empty <IFile>());
            }

            var pathResolver   = new PackagePathResolver(packageRoot);
            var project        = new NugetFolderProject(_fileSystem, _contentResolver, _config, _log, pathResolver, packageRoot, targetFramework);
            var packageManager = new NuGetPackageManager(sourceRepositoryProvider, _nugetSettings, project.Root)
            {
                PackagesFolderNuGetProject = project
            };
            var sourceRepositories = sourceRepositoryProvider.GetRepositories();
            var includePrerelease  = package.IsPrerelease();
            var dependencyBehavior = GetDependencyBehavior(type, package);
            var resolutionContext  = new ResolutionContext(dependencyBehavior, includePrerelease, false, VersionConstraints.None, _gatherCache);
            var projectContext     = new NuGetProjectContext(_log);

            packageManager.InstallPackageAsync(project, packageIdentity, resolutionContext, projectContext,
                                               sourceRepositories, Array.Empty <SourceRepository>(),
                                               CancellationToken.None).Wait();

            return(project.GetFiles(path, package, type));
        }
示例#6
0
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            var packageRoot              = path.MakeAbsolute(_environment).FullPath;
            var targetFramework          = type == PackageType.Addin ? _currentFramework : NuGetFramework.AnyFramework;
            var sourceRepositoryProvider = new NuGetSourceRepositoryProvider(_nugetSettings, _config, package, packageRoot);

            var localAndPrimaryRepositories = new HashSet <SourceRepository>(new NuGetSourceRepositoryComparer());

            localAndPrimaryRepositories.AddRange(sourceRepositoryProvider.LocalRepositories);
            localAndPrimaryRepositories.AddRange(sourceRepositoryProvider.PrimaryRepositories);

            var allRepositories = new HashSet <SourceRepository>(new NuGetSourceRepositoryComparer());

            allRepositories.AddRange(localAndPrimaryRepositories);
            allRepositories.AddRange(sourceRepositoryProvider.Repositories);

            var packageIdentity = GetPackageId(package, localAndPrimaryRepositories, targetFramework, _sourceCacheContext, _nugetLogger);

            if (packageIdentity == null)
            {
                _log.Debug("No package identity returned.");
                return(Array.Empty <IFile>());
            }

            if (packageIdentity.Version.IsPrerelease && !package.IsPrerelease())
            {
                // If a prerelease version is explicitly specified, we should install that with or without prerelease flag.
                _log.Debug("Prerelease version string explicitly specified. Installing prerelease package version.");
            }

            var pathResolver       = new PackagePathResolver(packageRoot);
            var dependencyBehavior = GetDependencyBehavior(type, package);
            var downloadContext    = new PackageDownloadContext(_sourceCacheContext);

            var availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default);

            GetPackageDependencies(packageIdentity,
                                   targetFramework,
                                   _sourceCacheContext,
                                   _nugetLogger,
                                   allRepositories,
                                   availablePackages,
                                   dependencyBehavior,
                                   localAndPrimaryRepositories);

            var resolverContext = new PackageResolverContext(
                dependencyBehavior,
                new[] { packageIdentity.Id },
                Enumerable.Empty <string>(),
                Enumerable.Empty <global::NuGet.Packaging.PackageReference>(),
                Enumerable.Empty <PackageIdentity>(),
                availablePackages,
                allRepositories.Select(s => s.PackageSource),
                NullLogger.Instance);

            var resolver          = new PackageResolver();
            var packagesToInstall = resolver.Resolve(resolverContext, CancellationToken.None)
                                    .Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p))).ToArray();

            if (packagesToInstall.Length == 0)
            {
                _log.Debug("No packages to install after running package resolver.");
            }

            var packageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Nuspec | PackageSaveMode.Files | PackageSaveMode.Nupkg,
                XmlDocFileSaveMode.None,
                ClientPolicyContext.GetClientPolicy(_nugetSettings, _nugetLogger),
                _nugetLogger);

            var installedFiles = new List <IFile>();

            foreach (var packageToInstall in packagesToInstall)
            {
                var isTargetPackage = packageToInstall.Id.Equals(package.Package, StringComparison.OrdinalIgnoreCase);
                var installPath     = new DirectoryPath(pathResolver.GetInstallPath(packageToInstall));
                if (!_fileSystem.Exist(installPath))
                {
                    var downloadResource = packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None).GetAwaiter().GetResult();
                    var downloadResult   = downloadResource.GetDownloadResourceResultAsync(
                        packageToInstall,
                        downloadContext,
                        SettingsUtility.GetGlobalPackagesFolder(_nugetSettings),
                        _nugetLogger, CancellationToken.None).GetAwaiter().GetResult();

                    PackageExtractor.ExtractPackageAsync(
                        downloadResult.PackageSource,
                        downloadResult.PackageStream,
                        pathResolver,
                        packageExtractionContext,
                        CancellationToken.None).GetAwaiter().GetResult();

                    // If this is the target package, to avoid problems with casing, get the actual install path from the nuspec
                    if (isTargetPackage)
                    {
                        installPath = new DirectoryPath(pathResolver.GetInstallPath(downloadResult.PackageReader.GetIdentity()));
                    }
                }

                if (_denyListPackages.Contains(packageToInstall.Id))
                {
                    const string format = "Package {0} depends on package {1}. This dependency won't be loaded.";
                    _log.Debug(format, package.Package, packageToInstall.ToString());
                    continue;
                }

                // If the installed package is not the target package, create a new PackageReference
                // which is passed to the content resolver. This makes logging make more sense.
                var installedPackageReference = isTargetPackage ? package : new PackageReference($"nuget:?package={packageToInstall.Id}");
                var assemblies = _contentResolver.GetFiles(installPath, installedPackageReference, type);
                if (assemblies.Count == 0)
                {
                    _log.Debug("No assemblies found after running content resolver.");
                }
                installedFiles.AddRange(assemblies);
            }

            return(installedFiles);
        }