Example #1
0
        /// <summary>
        /// Returns updates for packages from the repository
        /// </summary>
        /// <param name="packageName">Package to look for updates</param>
        /// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param>
        /// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns></returns>
        public async Task <IEnumerable <NugetPackage> > GetUpdates(PackageName packageName, bool includePrerelease, bool includeAllVersions, CancellationToken cancellationToken)
        {
            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrerelease,
                true,
                includeAllVersions ? VersionConstraints.None : VersionConstraints.ExactMajor | VersionConstraints.ExactMinor);

            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();

            var res          = new List <NugetPackage>();
            var foundPackage = await NuGetPackageManager.GetLatestVersionAsync(packageName.Id, NuGetFramework.AgnosticFramework, resolutionContext, repositories, NativeLogger, cancellationToken);

            if (packageName.Version.ToNuGetVersion() <= foundPackage.LatestVersion)
            {
                foreach (var repo in repositories)
                {
                    var metadataResource = await repo.GetResourceAsync <PackageMetadataResource>(cancellationToken);

                    var metadataList = await metadataResource.GetMetadataAsync(packageName.Id, includePrerelease, includeAllVersions, NativeLogger, cancellationToken);

                    foreach (var metadata in metadataList)
                    {
                        res.Add(new NugetServerPackage(metadata, repo.PackageSource.Source));
                    }
                }
            }
            return(res);
        }
        private static async Task <string> GetLatestPackageVersionAsync(string packageId, CancellationToken cancellationToken = default)
        {
            var providers = new List <Lazy <INuGetResourceProvider> >();

            providers.AddRange(Repository.Provider.GetCoreV3());  // Add v3 API support

            // We SHOULD use all the sources from the target's nuget.config file.
            // But I don't know what API to use to do that.
            var packageSource = new PackageSource("https://api.nuget.org/v3/index.json");

            var sourceRepository  = new SourceRepository(packageSource, providers);
            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Highest,
                includePrelease: false,
                includeUnlisted: false,
                VersionConstraints.None);

            // The target framework doesn't matter, since our package doesn't depend on this for its target projects.
            var framework = new NuGet.Frameworks.NuGetFramework("net45");

            var pkg = await NuGetPackageManager.GetLatestVersionAsync(
                packageId,
                framework,
                resolutionContext,
                sourceRepository,
                NullLogger.Instance,
                cancellationToken);

            return(pkg.LatestVersion.ToNormalizedString());
        }
 public Task <ResolvedPackage> GetLatestVersionAsync(
     string packageId,
     NuGetProject project,
     ResolutionContext resolutionContext,
     IEnumerable <SourceRepository> sources,
     ILogger log,
     CancellationToken token)
 {
     return(NuGetPackageManager.GetLatestVersionAsync(
                packageId,
                project,
                resolutionContext,
                sources,
                log,
                token
                ));
 }
Example #4
0
        private static async Task <string> GetLatestPackageVersionAsync(string packageId, string root, IReadOnlyList <string> sources, CancellationToken cancellationToken = default)
        {
            var settings = Settings.LoadDefaultSettings(root);

            var providers = new List <Lazy <INuGetResourceProvider> >();

            providers.AddRange(Repository.Provider.GetCoreV3());  // Add v3 API support

            var sourceRepositoryProvider = new SourceRepositoryProvider(settings, providers);

            // Select package sources based on NuGet.Config files or given options, as 'nuget.exe restore' command does
            // See also 'DownloadCommandBase.GetPackageSources(ISettings)' at https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Clients/NuGet.CommandLine/Commands/DownloadCommandBase.cs
            var availableSources = sourceRepositoryProvider.PackageSourceProvider.LoadPackageSources().Where(s => s.IsEnabled);
            var packageSources   = new List <PackageSource>();

            foreach (var source in sources)
            {
                var resolvedSource = availableSources.FirstOrDefault(s => s.Source.Equals(source, StringComparison.OrdinalIgnoreCase) || s.Name.Equals(source, StringComparison.OrdinalIgnoreCase));
                packageSources.Add(resolvedSource ?? new PackageSource(source));
            }

            if (sources.Count == 0)
            {
                packageSources.AddRange(availableSources);
            }

            var sourceRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();
            var resolutionContext  = new ResolutionContext(
                DependencyBehavior.Highest,
                includePrelease: false,
                includeUnlisted: false,
                VersionConstraints.None);

            // The target framework doesn't matter, since our package doesn't depend on this for its target projects.
            var framework = new NuGet.Frameworks.NuGetFramework("net45");

            var pkg = await NuGetPackageManager.GetLatestVersionAsync(
                packageId,
                framework,
                resolutionContext,
                sourceRepositories,
                NullLogger.Instance,
                cancellationToken);

            return(pkg.LatestVersion?.ToNormalizedString());
        }
Example #5
0
        public void InstallPackage(PackageInstaller installer, bool updatePackages, SourceRepository localSourceRepository, List <SourceRepository> sourceRepositories)
        {
            string versionString = _version == null ? string.Empty : " " + _version;

            Trace.Verbose($"Installing package {_packageId}{versionString} (with dependencies)");
            ResolutionContext resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest, _allowPrereleaseVersions, _allowUnlisted, VersionConstraints.None);

            // Get the installed version
            NuGetVersion installedVersion = NuGetPackageManager.GetLatestVersionAsync(_packageId, installer.CurrentFramework, resolutionContext,
                                                                                      localSourceRepository, installer.Logger, CancellationToken.None).Result;

            // Does the installed version match the requested version
            NuGetVersion matchingVersion = installedVersion;

            if (installedVersion != null &&
                (_version == null || installedVersion == _version) &&
                !updatePackages && !_getLatest)
            {
                Trace.Verbose($"Package {_packageId}{versionString} is satisfied by version {installedVersion}");
            }
            else if (_version != null)
            {
                matchingVersion = _version;
            }
            else
            {
                // Get the latest version
                matchingVersion = NuGetPackageManager.GetLatestVersionAsync(_packageId, installer.CurrentFramework, resolutionContext,
                                                                            sourceRepositories, installer.Logger, CancellationToken.None).Result;
            }

            // Install the requested version (do even if we're up to date to ensure dependencies are installed)
            installer.PackageManager.InstallPackageAsync(installer.PackageManager.PackagesFolderNuGetProject,
                                                         new PackageIdentity(_packageId, matchingVersion), resolutionContext, installer.ProjectContext, sourceRepositories,
                                                         Array.Empty <SourceRepository>(), CancellationToken.None).Wait();
            Trace.Verbose($"Installed package {_packageId} {matchingVersion}");
        }
Example #6
0
        /// <summary>
        /// Устанавливает пакет.
        /// </summary>
        /// <param name="packageId">ID пакета.</param>
        /// <param name="packageVersion">Версия пакета.</param>
        /// <param name="allowPrerelease">Разрешена ли установка предварительного релиза.</param>
        /// <returns>Содержимое установленного пакета.</returns>
        public async Task <PackageContent> InstallPackage(string packageId, string packageVersion = null, bool allowPrerelease = false)
        {
            NuGetVersion packageNuGetVersion = null;

            if (!string.IsNullOrWhiteSpace(packageVersion))
            {
                packageNuGetVersion = NuGetVersion.Parse(packageVersion);
            }

            // Конфигурационный файл NuGet.config по умолчанию
            var settings = new NuGet.Configuration.Settings(_packagesPath, "NuGet.config");

            // Фабрика источников пактов на основе конфигурационного файла
            var packageSourceProvider = new PackageSourceProvider(settings);

            // Добавление в фабрику источников пакетов дополнительных источников
            packageSourceProvider.SavePackageSources(_packageSources.Select(i => new PackageSource(i)));

            // Фабрика хранилищ пакетов на основе фабрики источников пакетов
            var packageRepositoryProvider = new CachingSourceProvider(packageSourceProvider);

            // Получение всех хранилищ пакетов на основе указанных источников
            var packageRepositories = packageRepositoryProvider.GetRepositories().ToList();

            // Определение возможности установки prerelease-версии пакетов
            allowPrerelease = allowPrerelease || (packageNuGetVersion != null && packageNuGetVersion.IsPrerelease);

            // Создание правил разрешения зависимостей при установке пакета
            var resolutionContext = new ResolutionContext(
                dependencyBehavior: DependencyBehavior.Lowest,
                includePrelease: allowPrerelease,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            // Если версия пакета не указана, поиск последней версии
            if (packageNuGetVersion == null)
            {
                packageNuGetVersion = await NuGetPackageManager.GetLatestVersionAsync(
                    packageId,
                    NuGetFramework.AnyFramework,
                    resolutionContext,
                    packageRepositories,
                    _logger,
                    CancellationToken.None);

                if (packageNuGetVersion == null)
                {
                    throw new InvalidOperationException(string.Format(Properties.Resources.PackageNotFound, packageId));
                }
            }

            // Уникальный идентификатор версии пакета для установки
            var packageIdentity = new PackageIdentity(packageId, packageNuGetVersion);

            // Каталог для установки пакетов (каталог packages)
            NuGetProject folderProject = new InfinniFolderNuGetProject(_packagesPath);

            // Менеджер для управления пакетами
            var packageManager = new NuGetPackageManager(packageRepositoryProvider, settings, _packagesPath);

            // Правила установки пакетов
            var projectContext = new NuGetLoggerProjectContext(_logger)
            {
                PackageExtractionContext = new PackageExtractionContext
                {
                    PackageSaveMode = PackageSaveMode.Defaultv3
                }
            };

            // Определение порядка действий при установке пакета
            var installActions = (await packageManager.PreviewInstallPackageAsync(
                                      folderProject,
                                      packageIdentity,
                                      resolutionContext,
                                      projectContext,
                                      packageRepositories,
                                      Enumerable.Empty <SourceRepository>(),
                                      CancellationToken.None)).ToList();

            // Применение действий по установке пакета
            await packageManager.ExecuteNuGetProjectActionsAsync(
                folderProject,
                installActions,
                projectContext,
                CancellationToken.None);

            return(GetPackageContent(packageIdentity, installActions.Select(i => i.PackageIdentity).ToList()));
        }
Example #7
0
        private async Task InstallPackage(
            string packageId,
            NuGetVersion version,
            string installPath)
        {
            if (version == null)
            {
                NoCache = true;
            }

            var folderProject = new FolderNuGetProject(
                installPath,
                new PackagePathResolver(installPath, !ExcludeVersion));

            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath);

            var packageSources = GetPackageSources(Settings);

            Console.PrintPackageSources(packageSources);

            var primaryRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);

            var allowPrerelease = Prerelease || (version != null && version.IsPrerelease);

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrelease: allowPrerelease,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            if (version == null)
            {
                // Find the latest version using NuGetPackageManager
                version = await NuGetPackageManager.GetLatestVersionAsync(
                    packageId,
                    folderProject,
                    resolutionContext,
                    primaryRepositories,
                    Console,
                    CancellationToken.None);

                if (version == null)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("InstallCommandUnableToFindPackage"),
                        packageId);

                    throw new CommandLineException(message);
                }
            }

            var packageIdentity = new PackageIdentity(packageId, version);

            if (folderProject.PackageExists(packageIdentity))
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandPackageAlreadyExists"),
                    packageIdentity);

                Console.LogMinimal(message);
            }
            else
            {
                var projectContext = new ConsoleProjectContext(Console)
                {
                    PackageExtractionContext = new PackageExtractionContext(Console)
                };

                if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
                {
                    projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
                }

                await packageManager.InstallPackageAsync(
                    folderProject,
                    packageIdentity,
                    resolutionContext,
                    projectContext,
                    primaryRepositories,
                    Enumerable.Empty <SourceRepository>(),
                    CancellationToken.None);
            }
        }
Example #8
0
        private async Task InstallPackageAsync(
            string packageId,
            NuGetVersion version,
            string installPath)
        {
            if (version == null)
            {
                // Avoid searching for the highest version in the global packages folder,
                // it needs to come from the feeds instead. Once found it may come from
                // the global packages folder unless NoCache is true.
                ExcludeCacheAsSource = true;
            }

            var framework = GetTargetFramework();

            // Create the project and set the framework if available.
            var project = new InstallCommandProject(
                root: installPath,
                packagePathResolver: new PackagePathResolver(installPath, !ExcludeVersion),
                targetFramework: framework);

            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath);

            var packageSources      = GetPackageSources(Settings);
            var primaryRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);

            Console.PrintPackageSources(packageSources);

            var allowPrerelease = Prerelease || (version != null && version.IsPrerelease);

            var dependencyBehavior = DependencyBehaviorHelper.GetDependencyBehavior(DependencyBehavior.Lowest, DependencyVersion, Settings);

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var resolutionContext = new ResolutionContext(
                    dependencyBehavior,
                    includePrelease: allowPrerelease,
                    includeUnlisted: false,
                    versionConstraints: VersionConstraints.None,
                    gatherCache: new GatherCache(),
                    sourceCacheContext: sourceCacheContext);

                if (version == null)
                {
                    // Write out a helpful message before the http messages are shown
                    Console.Log(LogLevel.Minimal, string.Format(
                                    CultureInfo.CurrentCulture,
                                    LocalizedResourceManager.GetString("InstallPackageMessage"), packageId, installPath));

                    // Find the latest version using NuGetPackageManager
                    var resolvePackage = await NuGetPackageManager.GetLatestVersionAsync(
                        packageId,
                        project,
                        resolutionContext,
                        primaryRepositories,
                        Console,
                        CancellationToken.None);

                    if (resolvePackage == null || resolvePackage.LatestVersion == null)
                    {
                        var message = string.Format(
                            CultureInfo.CurrentCulture,
                            LocalizedResourceManager.GetString("InstallCommandUnableToFindPackage"),
                            packageId);

                        throw new CommandException(message);
                    }

                    version = resolvePackage.LatestVersion;
                }

                // Get a list of packages already in the folder.
                var installedPackages = await project.GetFolderPackagesAsync(CancellationToken.None);

                // Find existing versions of the package
                var alreadyInstalledVersions = new HashSet <NuGetVersion>(installedPackages
                                                                          .Where(e => StringComparer.OrdinalIgnoreCase.Equals(packageId, e.PackageIdentity.Id))
                                                                          .Select(e => e.PackageIdentity.Version));

                var packageIdentity = new PackageIdentity(packageId, version);

                // Check if the package already exists or a higher version exists already.
                var skipInstall = project.PackageExists(packageIdentity);

                // For SxS allow other versions to install. For non-SxS skip if a higher version exists.
                skipInstall |= (ExcludeVersion && alreadyInstalledVersions.Any(e => e >= version));

                if (skipInstall)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("InstallCommandPackageAlreadyExists"),
                        packageIdentity);

                    Console.LogMinimal(message);
                }
                else
                {
                    var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, Console);

                    var projectContext = new ConsoleProjectContext(Console)
                    {
                        PackageExtractionContext = new PackageExtractionContext(
                            Packaging.PackageSaveMode.Defaultv2,
                            PackageExtractionBehavior.XmlDocFileSaveMode,
                            clientPolicyContext,
                            Console)
                    };

                    if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
                    {
                        projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
                    }

                    resolutionContext.SourceCacheContext.NoCache        = NoCache;
                    resolutionContext.SourceCacheContext.DirectDownload = DirectDownload;

                    var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext, installPath, DirectDownload)
                    {
                        ClientPolicyContext = clientPolicyContext
                    };

                    await packageManager.InstallPackageAsync(
                        project,
                        packageIdentity,
                        resolutionContext,
                        projectContext,
                        downloadContext,
                        primaryRepositories,
                        Enumerable.Empty <SourceRepository>(),
                        CancellationToken.None);

                    if (downloadContext.DirectDownload)
                    {
                        GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                    }
                }
            }
        }
Example #9
0
        public async Task <NuGetInstallResult> InstallPackage(
            string packageId,
            NuGetVersion version,
            bool prerelease)
        {
            var installPath = Path.Combine(Path.GetTempPath(), "testnuget");

            var projectContext = new EmptyNuGetProjectContext
            {
                PackageExtractionContext = new PackageExtractionContext()
            };

            var references          = new List <string>();
            var frameworkReferences = new List <string>();
            var projectSystem       = new DelegateNuGetProjectSystem(projectContext, (reference, isFrameworkReference) =>
            {
                if (isFrameworkReference)
                {
                    frameworkReferences.Add(reference);
                }
                else
                {
                    references.Add(reference);
                }
            });

            var project = new MSBuildNuGetProject(projectSystem, installPath, installPath);

            OverrideProject(project);

            var packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, installPath);

            var primaryRepositories = _packageSources.Select(_sourceRepositoryProvider.CreateRepository).ToArray();

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrelease: prerelease,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            if (version == null)
            {
                // Find the latest version using NuGetPackageManager
                version = await NuGetPackageManager.GetLatestVersionAsync(
                    packageId,
                    project,
                    resolutionContext,
                    primaryRepositories,
                    NullLogger.Instance,
                    CancellationToken.None).ConfigureAwait(false);

                if (version == null)
                {
                    throw new Exception("Unable to find package");
                }
            }

            var packageIdentity = new PackageIdentity(packageId, version);

            await packageManager.InstallPackageAsync(
                project,
                packageIdentity,
                resolutionContext,
                projectContext,
                primaryRepositories,
                Enumerable.Empty <SourceRepository>(),
                CancellationToken.None).ConfigureAwait(false);

            return(new NuGetInstallResult(references.AsReadOnly(), frameworkReferences.AsReadOnly()));
        }
Example #10
0
        public async Task <NuGetInstallResult> InstallPackage(
            string packageId,
            NuGetVersion version,
            bool prerelease)
        {
            _initializationException?.Throw();

            var installPath = Path.Combine(Path.GetTempPath(), "dummynuget");

            var projectContext = new EmptyNuGetProjectContext
            {
                PackageExtractionContext = new PackageExtractionContext(NullLogger.Instance)
            };

            PackageIdentity currentIdentity     = null;
            var             references          = new List <string>();
            var             frameworkReferences = new List <string>();
            var             projectSystem       = new DummyNuGetProjectSystem(projectContext,
                                                                              path => references.Add(GetPackagePath(currentIdentity, path)),
                                                                              path => frameworkReferences.Add(path));

            var project = new MSBuildNuGetProject(projectSystem, installPath, installPath);

            // this is a hack to get the identity of the package added in DummyNuGetProjectSystem.AddReference
            project.PackageInstalling += (sender, args) => currentIdentity = args.Identity;
            OverrideProject(project);

            var packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, installPath);

            var primaryRepositories = _packageSources.Select(_sourceRepositoryProvider.CreateRepository).ToArray();

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrelease: prerelease,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            if (version == null)
            {
                // Find the latest version using NuGetPackageManager
                var resolvedPackage = await NuGetPackageManager.GetLatestVersionAsync(
                    packageId,
                    project,
                    resolutionContext,
                    primaryRepositories,
                    NullLogger.Instance,
                    CancellationToken.None).ConfigureAwait(false);

                if (resolvedPackage == null)
                {
                    throw new Exception("Unable to find package");
                }

                version = resolvedPackage.LatestVersion;
            }

            var packageIdentity = new PackageIdentity(packageId, version);

            await packageManager.InstallPackageAsync(
                project,
                packageIdentity,
                resolutionContext,
                projectContext,
                primaryRepositories,
                Enumerable.Empty <SourceRepository>(),
                CancellationToken.None).ConfigureAwait(false);

            return(new NuGetInstallResult(references.AsReadOnly(), frameworkReferences.AsReadOnly()));
        }
Example #11
0
 public Task <NuGetVersion> GetLatestVersionAsync(string id, NuGetFramework targetFramework, bool isPrereleaseAllowed, CancellationToken cancellationToken) =>
 NuGetPackageManager.GetLatestVersionAsync(id, targetFramework, CreateResolutionContext(isPrereleaseAllowed), _sourceRepositoryProvider.GetDefaultRepositories(), this, cancellationToken);