public async Task TestPackageRestoredEvent()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
            {
                var projectA = testSolutionManager.AddNewMSBuildProject();
                var projectB = testSolutionManager.AddNewMSBuildProject();

                var packageIdentity          = Packages[0];
                var testNuGetProjectContext  = new TestNuGetProjectContext();
                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                var testSettings             = Configuration.NullSettings.Instance;
                var resolutionContext        = new ResolutionContext();
                var token = CancellationToken.None;

                var deleteOnRestartManager = new TestDeleteOnRestartManager();
                var nuGetPackageManager    = new NuGetPackageManager(
                    sourceRepositoryProvider,
                    testSettings,
                    testSolutionManager,
                    deleteOnRestartManager);

                await nuGetPackageManager.InstallPackageAsync(projectA, packageIdentity,
                                                              resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                await nuGetPackageManager.InstallPackageAsync(projectB, packageIdentity,
                                                              resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                var packageRestoreManager = new PackageRestoreManager(
                    sourceRepositoryProvider,
                    testSettings,
                    testSolutionManager);
                var restoredPackages = new List <PackageIdentity>();
                packageRestoreManager.PackageRestoredEvent += delegate(object sender, PackageRestoredEventArgs args)
                {
                    if (args.Restored)
                    {
                        restoredPackages.Add(args.Package);
                    }
                };

                Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(packageIdentity));

                // Delete packages folder
                TestFileSystemUtility.DeleteRandomTestFolder(Path.Combine(testSolutionManager.SolutionDirectory, "packages"));

                Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));

                // Act
                await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(testSolutionManager.SolutionDirectory,
                                                                                  testNuGetProjectContext,
                                                                                  new TestLogger(),
                                                                                  CancellationToken.None);

                Assert.Equal(1, restoredPackages.Count);
                Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));
            }
        }
Пример #2
0
        /// <summary>
        /// Downloads and extracts the specified dependency to the NuGet package folder.
        /// </summary>
        /// <param name="dependency">Dependency indicating the specific Id and Version of the package to download.</param>
        public async Task DownloadPackageAsync(Dependency dependency)
        {
            // Use V3 providers to get an instance of the NuGetPackageManager. We'll use
            // defaults for everything as we are doing a simple package download to a folder.
            var identity       = dependency.ToPackageIdentity();
            var settings       = NuGet.Configuration.Settings.LoadDefaultSettings(Settings.NugetPackageDirectory);
            var cores          = Repository.Provider.GetPageableCoreV3().Select(p => new Lazy <INuGetResourceProvider>(() => p));
            var provider       = new SourceRepositoryProvider(settings, cores);
            var packageManager = new NuGetPackageManager(provider, settings, Settings.NugetPackageDirectory)
            {
                PackagesFolderNuGetProject = _packageFolder
            };

            // When the package already exists in the package folder, there is nothing to do.
            if (packageManager.PackageExistsInPackagesFolder(identity))
            {
                return;
            }

            // We'll create an instance of ResolutionContext using the standard resolution behavior.
            var resolutionContext  = new ResolutionContext(NuGet.Resolver.DependencyBehavior.Lowest, true, true, VersionConstraints.None);
            var projectContext     = new NuGetProjectContext();
            var sourceRepositories = provider.GetRepositories();

            // Use the package manager to download an install the specified dependencies.
            await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                     identity, resolutionContext, projectContext, sourceRepositories,
                                                     Array.Empty <SourceRepository>(),
                                                     CancellationToken.None);
        }
Пример #3
0
        /// <summary>Verifies that the plugin package and all of its dependencies exist locally</summary>
        public virtual bool PackageAndDependenciesExist(NuGetPackageManager packageManager)
        {
            // Check this package
            if (!packageManager.PackageExistsInPackagesFolder(Identity))
            {
                LogTo.Warning(
                    $"Cached plugin package {Id} {Version} does not exist in packages folder");

                return(false);
            }

            // Check dependencies
            foreach (var package in Dependencies)
            {
                if (!package.PackageExists(packageManager))
                {
                    LogTo.Warning(
                        $"Cached package dependency {package.Id} {package.Version} "
                        + $"of plugin {Id} {Version} does not exist in packages folder");

                    return(false);
                }
            }

            return(true);
        }
Пример #4
0
        private async Task PerformV2Restore(string packagesConfigFilePath, string installPath)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath, ExcludeVersion);

            var installedPackageReferences = GetInstalledPackageReferences(
                packagesConfigFilePath,
                allowDuplicatePackageIds: true);

            var packageRestoreData = installedPackageReferences.Select(reference =>
                                                                       new PackageRestoreData(
                                                                           reference,
                                                                           new[] { packagesConfigFilePath },
                                                                           isMissing: true));

            var packageSources = GetPackageSources(Settings);

            Console.PrintPackageSources(packageSources);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: null,
                packageRestoreFailedEvent: null,
                sourceRepositories: packageSources.Select(sourceRepositoryProvider.CreateRepository),
                maxNumberOfParallelTasks: DisableParallelProcessing ? 1 : PackageManagementConstants.DefaultMaxDegreeOfParallelism);

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).Any();

            if (!missingPackageReferences)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    packagesConfigFilePath);

                Console.LogMinimal(message);
            }
            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var downloadContext = new PackageDownloadContext(cacheContext, installPath, DirectDownload);

                await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    new ConsoleProjectContext(Console),
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }
            }
        }
        /// <summary>
        /// Returns the grouped list of installed packages.
        /// </summary>
        /// <param name="latest">If true, the latest version is returned. Otherwise, the oldest
        /// version is returned.</param>
        /// <returns></returns>
        private async Task <IEnumerable <PackageIdentity> > GetInstalledPackages(bool latest, CancellationToken token)
        {
            Dictionary <string, PackageIdentity> installedPackages = new Dictionary <string, PackageIdentity>(
                StringComparer.OrdinalIgnoreCase);

            foreach (var project in _projects)
            {
                foreach (var package in (await project.GetInstalledPackagesAsync(token)))
                {
                    if (!(project is NuGet.ProjectManagement.Projects.ProjectKNuGetProjectBase) &&
                        !_packageManager.PackageExistsInPackagesFolder(package.PackageIdentity))
                    {
                        continue;
                    }

                    PackageIdentity p;
                    if (installedPackages.TryGetValue(package.PackageIdentity.Id, out p))
                    {
                        if (latest)
                        {
                            if (p.Version < package.PackageIdentity.Version)
                            {
                                installedPackages[package.PackageIdentity.Id] = package.PackageIdentity;
                            }
                        }
                        else
                        {
                            if (p.Version > package.PackageIdentity.Version)
                            {
                                installedPackages[package.PackageIdentity.Id] = package.PackageIdentity;
                            }
                        }
                    }
                    else
                    {
                        installedPackages[package.PackageIdentity.Id] = package.PackageIdentity;
                    }
                }
            }

            return(installedPackages.Values);
        }
Пример #6
0
 public static IEnumerable <PackageReference> GetMissingPackages(NuGetPackageManager nuGetPackageManager,
                                                                 IEnumerable <PackageReference> packageReferences)
 {
     try
     {
         return(new HashSet <PackageReference>(packageReferences.Where(pr => !nuGetPackageManager.PackageExistsInPackagesFolder(pr.PackageIdentity)),
                                               new PackageReferenceComparer()));
     }
     catch (Exception)
     {
         // if an exception happens during the check, assume no missing packages and move on.
         // TODO : Write to NuGetProjectContext
         return(Enumerable.Empty <PackageReference>());
     }
 }
Пример #7
0
        /// <summary>
        /// Verifies that the package and all of it's dependencies exist locally
        /// </summary>
        public bool VerifyPackage(NuGetPackageManager packageManager)
        {
            bool verified = true;

            // Check this package
            if (!packageManager.PackageExistsInPackagesFolder(PackageReference.PackageIdentity))
            {
                Trace.TraceWarning($"Cached package {PackageReference.PackageIdentity.Id} {PackageReference.PackageIdentity.Version.ToNormalizedString()} does not exist in packages folder");
                verified = false;
            }

            // Check dependencies
            foreach (PackageReference dependency in Dependencies)
            {
                if (!packageManager.PackageExistsInPackagesFolder(dependency.PackageIdentity))
                {
                    Trace.TraceWarning($"Cached package dependency {dependency.PackageIdentity.Id} {dependency.PackageIdentity.Version.ToNormalizedString()} "
                                       + $"of {PackageReference.PackageIdentity.Id} {PackageReference.PackageIdentity.Version.ToNormalizedString()} does not exist in packages folder");
                    verified = false;
                }
            }

            return(verified);
        }
Пример #8
0
        public async Task TestRestoreMissingPackages()
        {
            // Arrange
            var testSolutionManager = new TestSolutionManager();
            var projectA            = testSolutionManager.AddNewMSBuildProject();
            var projectB            = testSolutionManager.AddNewMSBuildProject();

            var packageIdentity          = Packages[0];
            var testNuGetProjectContext  = new TestNuGetProjectContext();
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSettings             = NullSettings.Instance;
            var resolutionContext        = new ResolutionContext();
            var token = CancellationToken.None;

            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);

            await nuGetPackageManager.InstallPackageAsync(projectA, packageIdentity,
                                                          resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            await nuGetPackageManager.InstallPackageAsync(projectB, packageIdentity,
                                                          resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            var packageRestoreManager = new PackageRestoreManager(sourceRepositoryProvider, testSettings, testSolutionManager);

            Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(packageIdentity));

            // Delete packages folder
            Directory.Delete(Path.Combine(testSolutionManager.SolutionDirectory, "packages"), recursive: true);

            Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));

            // Act
            await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(CancellationToken.None);

            Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));
        }
        private static IEnumerable <PackageRestoreData> GetPackages(NuGetPackageManager nuGetPackageManager,
                                                                    Dictionary <Packaging.PackageReference, List <string> > packageReferencesDictionary)
        {
            var packages = new List <PackageRestoreData>();

            foreach (var packageReference in packageReferencesDictionary.Keys)
            {
                var isMissing = false;
                if (!nuGetPackageManager.PackageExistsInPackagesFolder(packageReference.PackageIdentity))
                {
                    isMissing = true;
                }

                var projectNames = packageReferencesDictionary[packageReference];

                Debug.Assert(projectNames != null);
                packages.Add(new PackageRestoreData(packageReference, projectNames, isMissing));
            }

            return(packages);
        }
Пример #10
0
        private async Task PerformV2RestoreAsync(string packagesConfigFilePath, string installPath)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath, ExcludeVersion);

            var installedPackageReferences = GetInstalledPackageReferences(
                packagesConfigFilePath,
                allowDuplicatePackageIds: true);

            var packageRestoreData = installedPackageReferences.Select(reference =>
                                                                       new PackageRestoreData(
                                                                           reference,
                                                                           new[] { packagesConfigFilePath },
                                                                           isMissing: true));

            var packageSources = GetPackageSources(Settings);

            Console.PrintPackageSources(packageSources);

            var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>();

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: null,
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: packageSources.Select(sourceRepositoryProvider.CreateRepository),
                maxNumberOfParallelTasks: DisableParallelProcessing ? 1 : PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: Console);

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).Any();

            if (!missingPackageReferences)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    packagesConfigFilePath);

                Console.LogMinimal(message);
            }
            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, Console);

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

                var downloadContext = new PackageDownloadContext(cacheContext, installPath, DirectDownload)
                {
                    ClientPolicyContext = clientPolicyContext
                };

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    projectContext,
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }

                // Use failure count to determine errors. result.Restored will be false for noop restores.
                if (failedEvents.Count > 0)
                {
                    // Log errors if they exist
                    foreach (var message in failedEvents.Select(e => new RestoreLogMessage(LogLevel.Error, NuGetLogCode.Undefined, e.Exception.Message)))
                    {
                        await Console.LogAsync(message);
                    }

                    throw new ExitCodeException(1);
                }
            }
        }
        public async Task Test_PackageRestoreFailure_WithRaisedEvents()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
                using (var randomTestPackageSourcePath = TestFileSystemUtility.CreateRandomTestFolder())
                {
                    var projectA = testSolutionManager.AddNewMSBuildProject("projectA");
                    var projectB = testSolutionManager.AddNewMSBuildProject("projectB");
                    var projectC = testSolutionManager.AddNewMSBuildProject("projectC");

                    var jQuery144                = Packages[0];
                    var jQueryValidation         = Packages[2];
                    var testNuGetProjectContext  = new TestNuGetProjectContext();
                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                    var testSettings             = Configuration.NullSettings.Instance;
                    var resolutionContext        = new ResolutionContext();
                    var token = CancellationToken.None;

                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);

                    await nuGetPackageManager.InstallPackageAsync(projectA, jQueryValidation,
                                                                  resolutionContext, testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

                    await nuGetPackageManager.InstallPackageAsync(projectB, jQueryValidation,
                                                                  resolutionContext, testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

                    var testPackage1 = new PackageIdentity("package1A", new NuGetVersion("1.0.0"));
                    var testPackage2 = new PackageIdentity("package1B", new NuGetVersion("1.0.0"));

                    var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestPackageSourcePath,
                                                                                           testPackage1.Id, testPackage1.Version.ToNormalizedString());
                    using (var packageStream = GetDownloadResult(packageFileInfo))
                    {
                        // Act
                        await projectB.InstallPackageAsync(testPackage1, packageStream, testNuGetProjectContext, token);

                        await projectC.InstallPackageAsync(testPackage1, packageStream, testNuGetProjectContext, token);
                    }

                    packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestPackageSourcePath,
                                                                                       testPackage2.Id, testPackage2.Version.ToNormalizedString());
                    using (var packageStream = GetDownloadResult(packageFileInfo))
                    {
                        // Act
                        await projectA.InstallPackageAsync(testPackage2, packageStream, testNuGetProjectContext, token);

                        await projectC.InstallPackageAsync(testPackage2, packageStream, testNuGetProjectContext, token);
                    }

                    var packageRestoreManager = new PackageRestoreManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager);
                    var restoredPackages = new List <PackageIdentity>();
                    packageRestoreManager.PackageRestoredEvent += delegate(object sender, PackageRestoredEventArgs args) { restoredPackages.Add(args.Package); };

                    var restoreFailedPackages = new ConcurrentDictionary <Packaging.PackageReference, IEnumerable <string> >(new PackageReferenceComparer());
                    packageRestoreManager.PackageRestoreFailedEvent += delegate(object sender, PackageRestoreFailedEventArgs args)
                    {
                        restoreFailedPackages.AddOrUpdate(args.RestoreFailedPackageReference,
                                                          args.ProjectNames,
                                                          (Packaging.PackageReference packageReference, IEnumerable <string> oldValue) => { return(oldValue); });
                    };

                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));

                    // Delete packages folder
                    TestFileSystemUtility.DeleteRandomTestFolder(Path.Combine(testSolutionManager.SolutionDirectory, "packages"));

                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(jQuery144));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage1));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage2));

                    // Act
                    await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(testSolutionManager.SolutionDirectory,
                                                                                      testNuGetProjectContext,
                                                                                      CancellationToken.None);

                    // Assert
                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQuery144));
                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage1));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage2));

                    Assert.Equal(4, restoredPackages.Count);
                    // The ordering is not guaranteed and can vary. Do not assert based on that
                    Assert.True(restoredPackages.Contains(jQuery144));
                    Assert.True(restoredPackages.Contains(jQueryValidation));
                    Assert.True(restoredPackages.Contains(testPackage1));
                    Assert.True(restoredPackages.Contains(testPackage2));

                    Assert.Equal(2, restoreFailedPackages.Count);

                    // The ordering is not guaranteed and can vary. Do not assert based on that
                    var restoreFailedPackageKeys = restoreFailedPackages.Keys;
                    var testPackage1Key          = restoreFailedPackageKeys.Where(r => r.PackageIdentity.Equals(testPackage1)).First();
                    var testPackage1ProjectNames = restoreFailedPackages[testPackage1Key].ToList();

                    Assert.Equal(2, testPackage1ProjectNames.Count);
                    Assert.True(testPackage1ProjectNames.Contains("projectB", StringComparer.OrdinalIgnoreCase));
                    Assert.True(testPackage1ProjectNames.Contains("projectC", StringComparer.OrdinalIgnoreCase));

                    var testPackage2Key          = restoreFailedPackageKeys.Where(r => r.PackageIdentity.Equals(testPackage2)).First();
                    var testPackage2ProjectNames = restoreFailedPackages[testPackage2Key].ToList();

                    Assert.Equal(2, testPackage2ProjectNames.Count);
                    Assert.True(testPackage2ProjectNames.Contains("projectA", StringComparer.OrdinalIgnoreCase));
                    Assert.True(testPackage2ProjectNames.Contains("projectC", StringComparer.OrdinalIgnoreCase));
                }
        }
Пример #12
0
        private static async Task <RestoreSummary> PerformNuGetV2RestoreAsync(Common.ILogger log, DependencyGraphSpec dgFile, bool noCache, bool disableParallel, bool interactive)
        {
            string globalPackageFolder           = null;
            string repositoryPath                = null;
            string firstPackagesConfigPath       = null;
            IList <PackageSource> packageSources = null;

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            ISettings settings = null;

            foreach (PackageSpec packageSpec in dgFile.Projects.Where(i => i.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig))
            {
                var pcRestoreMetadata = (PackagesConfigProjectRestoreMetadata)packageSpec.RestoreMetadata;
                globalPackageFolder = globalPackageFolder ?? pcRestoreMetadata.PackagesPath;
                repositoryPath      = repositoryPath ?? pcRestoreMetadata.RepositoryPath;

                if (packageSources == null)
                {
                    packageSources = new List <PackageSource>();
                    if (!noCache)
                    {
                        if (!string.IsNullOrEmpty(globalPackageFolder) && Directory.Exists(globalPackageFolder))
                        {
                            packageSources.Add(new FeedTypePackageSource(globalPackageFolder, FeedType.FileSystemV3));
                        }
                    }

                    packageSources.AddRange(pcRestoreMetadata.Sources);
                }

                settings = settings ?? Settings.LoadSettingsGivenConfigPaths(pcRestoreMetadata.ConfigFilePaths);

                var packagesConfigPath = Path.Combine(Path.GetDirectoryName(pcRestoreMetadata.ProjectPath), NuGetConstants.PackageReferenceFile);

                firstPackagesConfigPath = firstPackagesConfigPath ?? packagesConfigPath;

                installedPackageReferences.AddRange(GetInstalledPackageReferences(packagesConfigPath, allowDuplicatePackageIds: true, log));
            }

            if (string.IsNullOrEmpty(repositoryPath))
            {
                throw new InvalidOperationException(Strings.RestoreNoSolutionFound);
            }

            PackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = new CachingSourceProvider(packageSourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, settings, repositoryPath);

            var effectivePackageSaveMode = CalculateEffectivePackageSaveMode(settings);

            var packageSaveMode = effectivePackageSaveMode == Packaging.PackageSaveMode.None ?
                                  Packaging.PackageSaveMode.Defaultv2 :
                                  effectivePackageSaveMode;

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity, packageSaveMode)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                return(new RestoreSummary(true));
            }
            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { firstPackagesConfigPath },
                                                                         isMissing: true));

            var repositories = sourceRepositoryProvider.GetRepositories().ToArray();

            var installCount    = 0;
            var failedEvents    = new ConcurrentQueue <PackageRestoreFailedEventArgs>();
            var collectorLogger = new RestoreCollectorLogger(log);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: disableParallel
                    ? 1
                    : PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: collectorLogger);

            // TODO: Check require consent?
            // NOTE: This feature is currently not working at all. See https://github.com/NuGet/Home/issues/4327
            // CheckRequireConsent();

            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, collectorLogger);
            var projectContext      = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    packageSaveMode,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    clientPolicyContext,
                    collectorLogger)
            };

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

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache = noCache;

                var downloadContext = new PackageDownloadContext(cacheContext, repositoryPath, directDownload: false)
                {
                    ClientPolicyContext = clientPolicyContext
                };

                DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !interactive);

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    projectContext,
                    downloadContext);

                return(new RestoreSummary(
                           result.Restored,
                           "packages.config projects",
                           settings.GetConfigFilePaths().ToArray(),
                           packageSources.Select(x => x.Source).ToArray(),
                           installCount,
                           collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents)).ToArray()
                           ));
            }
        }
Пример #13
0
        private async Task <IReadOnlyList <RestoreSummary> > PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
        {
            ReadSettings(packageRestoreInputs);
            var packagesFolderPath = Path.GetFullPath(GetPackagesFolder(packageRestoreInputs));

            var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                installedPackageReferences.AddRange(packageRestoreInputs
                                                    .PackagesConfigFiles
                                                    .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true)));
            }
            else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
            {
                // By default the PackageReferenceFile does not throw
                // if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
                             "Only one packages.config file is allowed to be specified " +
                             "at a time when not performing solution restore.");

                var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
                if (!File.Exists(packageReferenceFile))
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        packageReferenceFile);

                    throw new InvalidOperationException(message);
                }

                installedPackageReferences.AddRange(
                    GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true));
            }

            // EffectivePackageSaveMode is None when -PackageSaveMode is not provided by the user. None is treated as
            // Defaultv3 for V3 restore and should be treated as Defaultv2 for V2 restore. This is the case in the
            // actual V2 restore flow and should match in this preliminary missing packages check.
            var packageSaveMode = EffectivePackageSaveMode == Packaging.PackageSaveMode.None ?
                                  Packaging.PackageSaveMode.Defaultv2 :
                                  EffectivePackageSaveMode;

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity, packageSaveMode)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    "packages.config");

                Console.LogMinimal(message);

                var restoreSummaries = new List <RestoreSummary>();

                ValidatePackagesConfigLockFiles(
                    packageRestoreInputs.PackagesConfigFiles,
                    packageRestoreInputs.ProjectReferenceLookup.Projects,
                    packagesFolderPath,
                    restoreSummaries);

                if (restoreSummaries.Count == 0)
                {
                    restoreSummaries.Add(new RestoreSummary(success: true));
                }

                return(restoreSummaries);
            }

            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { packageRestoreInputs.RestoringWithSolutionFile
                                ? packageRestoreInputs.DirectoryOfSolutionFile
                                : packageRestoreInputs.PackagesConfigFiles[0] },
                                                                         isMissing: true));

            var packageSources = GetPackageSources(Settings);

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

            var installCount    = 0;
            var failedEvents    = new ConcurrentQueue <PackageRestoreFailedEventArgs>();
            var collectorLogger = new RestoreCollectorLogger(Console);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: DisableParallelProcessing
                        ? 1
                        : PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: collectorLogger);

            CheckRequireConsent();

            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, collectorLogger);
            var projectContext      = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    Packaging.PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    clientPolicyContext,
                    collectorLogger)
            };

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

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var packageSourceMapping = PackageSourceMapping.GetPackageSourceMapping(Settings);

                var downloadContext = new PackageDownloadContext(cacheContext, packagesFolderPath, DirectDownload, packageSourceMapping)
                {
                    ClientPolicyContext = clientPolicyContext
                };

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    projectContext,
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }

                IReadOnlyList <IRestoreLogMessage> errors = collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents)).ToList();
                var restoreSummaries = new List <RestoreSummary>()
                {
                    new RestoreSummary(
                        result.Restored,
                        "packages.config projects",
                        Settings.GetConfigFilePaths().ToList().AsReadOnly(),
                        packageSources.Select(x => x.Source).ToList().AsReadOnly(),
                        installCount,
                        errors)
                };

                if (result.Restored)
                {
                    ValidatePackagesConfigLockFiles(
                        packageRestoreInputs.PackagesConfigFiles,
                        packageRestoreInputs.ProjectReferenceLookup.Projects,
                        packagesFolderPath,
                        restoreSummaries);
                }

                return(restoreSummaries);
            }
        }
 public bool PackageExistsInPackagesFolder(PackageIdentity packageIdentity)
 {
     return(packageManager.PackageExistsInPackagesFolder(packageIdentity));
 }
Пример #15
0
        public async Task DownloadPackage(PackageWrapper packageWrapper)
        {
            try
            {
                //this will prevent install to look in all repos
                _sourceRepos = new List <SourceRepository>();
                _sourceRepos.Add(packageWrapper.sourceRepository);

                var packageIdentity = packageWrapper.rootPackageIdentity;
                var providers       = new List <Lazy <INuGetResourceProvider> >();
                providers.AddRange(Repository.Provider.GetCoreV3()); // Add v3 API s

                var rootPath = NugetHelper.Instance.GetNugetSettings()
                               .NugetFolder;

                //var settings = Settings.LoadDefaultSettings(@"C:\Program Files (x86)\NuGet\Config", "Microsoft.VisualStudio.Offline.config", new MachineWideSettings());
                var machineWideSettings      = new MachineWideSettings();
                var settings                 = new Settings(rootPath);
                var packageSourceProvider    = new PackageSourceProvider(settings);
                var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);
                var project = new FolderNuGetProject(rootPath);

                var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, rootPath)
                {
                    PackagesFolderNuGetProject = project
                };

                var allowPrereleaseVersions         = true;
                var allowUnlisted                   = false;
                INuGetProjectContext projectContext = new ProjectContext();

                var resolutionContext = new ResolutionContext(DependencyBehavior.Lowest, allowPrereleaseVersions, allowUnlisted, VersionConstraints.None);

                if (NugetHelper.Instance.GetNugetSettings()
                    .DisableCache)
                {
                    resolutionContext.SourceCacheContext.NoCache        = true;
                    resolutionContext.SourceCacheContext.DirectDownload = true;
                }

                var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext, rootPath, resolutionContext.SourceCacheContext.DirectDownload);

                var packageAlreadyExists = packageManager.PackageExistsInPackagesFolder(packageIdentity, PackageSaveMode.None);

                if (!packageAlreadyExists)
                {
                    await packageManager.InstallPackageAsync(project, packageIdentity, resolutionContext, projectContext, downloadContext, _sourceRepos, new List <SourceRepository>(), CancellationToken.None);

                    var packageDeps = packageManager.GetInstalledPackagesDependencyInfo(project, CancellationToken.None, true);
                    _logger.LogDebug($"Package {packageIdentity.Id} is got Installed at 【 {project.GetInstalledPath(packageIdentity)}】 ");
                }
                else
                {
                    var packageDeps = packageManager.GetInstalledPackagesDependencyInfo(project, CancellationToken.None, true);
                    _logger.LogDebug($"Package {packageIdentity.Id} is Already Installed at 【 {project.GetInstalledPath(packageIdentity)} 】" + " | skipping instalation !!");
                }

                #region GetDll paths

                var dllstoAdd = NugetHelper.Instance.GetInstallPackagesDllPath(packageWrapper, ref project);

                if (dllstoAdd.Count > 0)
                {
                    downloadedDllPaths.AddRange(dllstoAdd);
                }

                #endregion

                _logger.LogDebug($"done for package {packageIdentity.Id} , with total Dlls {downloadedDllPaths.Count}");
            }
            catch (Exception e)
            {
                NugetHelper.Instance.logger.LogDebug(e.Message);

                throw;
            }
        }
Пример #16
0
 /// <summary>Verifies that the package exist locally</summary>
 public static bool PackageExists(this NuGetPackage pkg, NuGetPackageManager packageManager)
 {
     return(packageManager.PackageExistsInPackagesFolder(pkg.Identity));
 }
        private async Task <RestoreSummary> PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
        {
            ReadSettings(packageRestoreInputs);
            var packagesFolderPath = GetPackagesFolder(packageRestoreInputs);

            var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                installedPackageReferences.AddRange(packageRestoreInputs
                                                    .PackagesConfigFiles
                                                    .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true)));
            }
            else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
            {
                // By default the PackageReferenceFile does not throw
                // if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
                             "Only one packages.config file is allowed to be specified " +
                             "at a time when not performing solution restore.");

                var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
                if (!File.Exists(packageReferenceFile))
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        packageReferenceFile);

                    throw new InvalidOperationException(message);
                }

                installedPackageReferences.AddRange(
                    GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true));
            }

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    "packages.config");

                Console.LogMinimal(message);
                return(new RestoreSummary(true));
            }

            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { packageRestoreInputs.RestoringWithSolutionFile
                                ? packageRestoreInputs.DirectoryOfSolutionFile
                                : packageRestoreInputs.PackagesConfigFiles[0] },
                                                                         isMissing: true));

            var packageSources = GetPackageSources(Settings);

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

            var installCount = 0;
            var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>();

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: DisableParallelProcessing
                        ? 1
                        : PackageManagementConstants.DefaultMaxDegreeOfParallelism);

            CheckRequireConsent();

            var collectorLogger = new CollectorLogger(Console);
            var projectContext  = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(collectorLogger)
            };

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

            var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                packageRestoreContext,
                projectContext);

            return(new RestoreSummary(
                       result.Restored,
                       "packages.config projects",
                       Settings.Priority.Select(x => Path.Combine(x.Root, x.FileName)),
                       packageSources.Select(x => x.Source),
                       installCount,
                       collectorLogger.Errors.Concat(failedEvents.Select(e => e.Exception.Message))));
        }
Пример #18
0
 /// <summary>Verifies that the package exist locally</summary>
 public bool PackageExists(NuGetPackageManager packageManager)
 {
     return(packageManager.PackageExistsInPackagesFolder(Identity));
 }