示例#1
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);
                    }
                }
            }
        }
示例#2
0
        private async Task UpdatePackagesAsync(MSBuildProjectSystem project, string packagesDirectory)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesDirectory);
            var nugetProject             = new MSBuildNuGetProject(project, packagesDirectory, project.ProjectFullPath);

            if (!nugetProject.PackagesConfigNuGetProject.PackagesConfigExists())
            {
                throw new CommandException(LocalizedResourceManager.GetString("NoPackagesConfig"));
            }

            var versionConstraints = Safe ?
                                     VersionConstraints.ExactMajor | VersionConstraints.ExactMinor :
                                     VersionConstraints.None;

            var projectActions = new List <NuGetProjectAction>();

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var dependencyBehavior = DependencyBehaviorHelper.GetDependencyBehavior(DependencyBehavior.Highest, DependencyVersion, Settings);
                var resolutionContext  = new ResolutionContext(
                    dependencyBehavior,
                    Prerelease,
                    includeUnlisted: false,
                    versionConstraints: versionConstraints,
                    gatherCache: new GatherCache(),
                    sourceCacheContext: sourceCacheContext);

                var packageSources = GetPackageSources();

                Console.PrintPackageSources(packageSources);

                var sourceRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);
                if (Id.Count > 0)
                {
                    var targetIds = new HashSet <string>(Id, StringComparer.OrdinalIgnoreCase);

                    var installed = await nugetProject.GetInstalledPackagesAsync(CancellationToken.None);

                    // If -Id has been specified and has exactly one package, use the explicit version requested
                    var targetVersion = Version != null && Id != null && Id.Count == 1 ? new NuGetVersion(Version) : null;

                    var targetIdentities = installed
                                           .Select(pr => pr.PackageIdentity.Id)
                                           .Where(id => targetIds.Contains(id))
                                           .Select(id => new PackageIdentity(id, targetVersion))
                                           .ToList();

                    if (targetIdentities.Any())
                    {
                        var actions = await packageManager.PreviewUpdatePackagesAsync(
                            targetIdentities,
                            new[] { nugetProject },
                            resolutionContext,
                            project.NuGetProjectContext,
                            sourceRepositories,
                            Enumerable.Empty <SourceRepository>(),
                            CancellationToken.None);

                        projectActions.AddRange(actions);
                    }
                }
                else
                {
                    var actions = await packageManager.PreviewUpdatePackagesAsync(
                        new[] { nugetProject },
                        resolutionContext,
                        project.NuGetProjectContext,
                        sourceRepositories,
                        Enumerable.Empty <SourceRepository>(),
                        CancellationToken.None);

                    projectActions.AddRange(actions);
                }

                await packageManager.ExecuteNuGetProjectActionsAsync(
                    nugetProject,
                    projectActions,
                    project.NuGetProjectContext,
                    sourceCacheContext,
                    CancellationToken.None);
            }

            project.Save();
        }