/// <summary>
        /// Restore many projects without writing the lock file
        /// SourceRepositories(sources) is only used for the CachingSourceProvider, the project-specific sources will still be resolved in RestoreRunner.
        /// </summary>
        internal static async Task <IEnumerable <RestoreResultPair> > PreviewRestoreProjectsAsync(
            ISolutionManager solutionManager,
            IEnumerable <BuildIntegratedNuGetProject> projects,
            IEnumerable <PackageSpec> updatedNugetPackageSpecs,
            DependencyGraphCacheContext context,
            RestoreCommandProvidersCache providerCache,
            Action <SourceCacheContext> cacheContextModifier,
            IEnumerable <SourceRepository> sources,
            Guid parentId,
            ILogger log,
            CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            // Add the new spec to the dg file and fill in the rest.
            var dgFile = await GetSolutionRestoreSpec(solutionManager, context);

            dgFile = dgFile.WithoutRestores()
                     .WithPackageSpecs(updatedNugetPackageSpecs);

            foreach (var project in projects)
            {
                dgFile.AddRestore(project.MSBuildProjectPath);
            }

            using (var sourceCacheContext = new SourceCacheContext())
            {
                // Update cache context
                cacheContextModifier(sourceCacheContext);

                // Settings passed here will be used to populate the restore requests.
                var restoreContext = GetRestoreArgs(
                    context,
                    providerCache,
                    sourceCacheContext,
                    sources,
                    dgFile,
                    parentId,
                    forceRestore: true,
                    isRestoreOriginalAction: false,
                    restoreForceEvaluate: true,
                    additionalMessasges: null,
                    progressReporter: null);

                var requests = await RestoreRunner.GetRequests(restoreContext);

                var results = await RestoreRunner.RunWithoutCommit(requests, restoreContext);

                return(results);
            }
        }
        /// <summary>
        /// Restore without writing the lock file
        /// </summary>
        internal static async Task <RestoreResultPair> PreviewRestoreAsync(
            ISolutionManager solutionManager,
            BuildIntegratedNuGetProject project,
            PackageSpec packageSpec,
            DependencyGraphCacheContext context,
            RestoreCommandProvidersCache providerCache,
            Action <SourceCacheContext> cacheContextModifier,
            IEnumerable <SourceRepository> sources,
            Guid parentId,
            ILogger log,
            CancellationToken token)
        {
            // Restoring packages
            var logger = context.Logger;

            // Add the new spec to the dg file and fill in the rest.
            var dgFile = await GetSolutionRestoreSpec(solutionManager, context);

            dgFile = dgFile.WithoutRestores()
                     .WithReplacedSpec(packageSpec);

            dgFile.AddRestore(project.MSBuildProjectPath);

            using (var sourceCacheContext = new SourceCacheContext())
            {
                // Update cache context
                cacheContextModifier(sourceCacheContext);

                // Settings passed here will be used to populate the restore requests.
                var restoreContext = GetRestoreContext(
                    context,
                    providerCache,
                    sourceCacheContext,
                    sources,
                    dgFile,
                    parentId,
                    forceRestore: true,
                    isRestoreOriginalAction: false,
                    restoreForceEvaluate: true,
                    additionalMessasges: null);

                var requests = await RestoreRunner.GetRequests(restoreContext);

                var results = await RestoreRunner.RunWithoutCommit(requests, restoreContext);

                return(results.Single());
            }
        }
Beispiel #3
0
        static async Task Main(string[] args)
        {
            using var cacheContext = new SourceCacheContext();
            using var pathContext  = new SimpleTestPathContext();
            var providerCache = new RestoreCommandProvidersCache();
            var dgFile        = new DependencyGraphSpec();
            var sources       = new List <string>()
            {
                pathContext.PackageSource
            };
            var restoreContext = new RestoreArgs()
            {
                CacheContext         = cacheContext,
                DisableParallel      = true,
                GlobalPackagesFolder = pathContext.UserPackagesFolder,
                Sources = sources,
                Log     = new NullLogger(),
                CachingSourceProvider =
                    new CachingSourceProvider(new TestPackageSourceProvider(
                                                  new List <PackageSource>()
                {
                    new PackageSource(pathContext.PackageSource)
                })),
                PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                {
                    new DependencyGraphSpecRequestProvider(providerCache, dgFile)
                }
            };

            var request   = (await RestoreRunner.GetRequests(restoreContext)).Single();
            var providers = providerCache.GetOrCreate(pathContext.UserPackagesFolder, sources,
                                                      new List <SourceRepository>(), cacheContext, new NullLogger());
            var command = new RestoreCommand(request.Request);

            // Add to cache before install on all providers
            var globalPackages = providers.GlobalPackages;
            var packages       = globalPackages.FindPackagesById("a");

            foreach (var local in providers.LocalProviders)
            {
                await local.GetDependenciesAsync(
                    new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package),
                    NuGetFramework.Parse("net46"), cacheContext, new NullLogger(), CancellationToken.None);
            }

            // Run restore using an incorrect cache
            var result = await command.ExecuteAsync();
        }
        private static async Task <RestoreResultPair> PreviewAddPackageReference(PackageReferenceArgs packageReferenceArgs,
                                                                                 DependencyGraphSpec dgSpec,
                                                                                 PackageSpec originalPackageSpec)
        {
            // Set user agent and connection settings.
            XPlatUtility.ConfigureProtocol();

            var providerCache = new RestoreCommandProvidersCache();

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

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>();

                // Create a copy to avoid modifying the original spec which may be shared.
                var updatedPackageSpec = originalPackageSpec.Clone();

                PackageSpecOperations.AddOrUpdateDependency(updatedPackageSpec, packageReferenceArgs.PackageDependency);

                providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgSpec));

                var restoreContext = new RestoreArgs()
                {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    Log                       = packageReferenceArgs.Logger,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    GlobalPackagesFolder      = packageReferenceArgs.PackageDirectory,
                    PreLoadedRequestProviders = providers,
                    Sources                   = packageReferenceArgs.Sources?.ToList()
                };

                // Generate Restore Requests. There will always be 1 request here since we are restoring for 1 project.
                var restoreRequests = await RestoreRunner.GetRequests(restoreContext);

                // Run restore without commit. This will always return 1 Result pair since we are restoring for 1 request.
                var restoreResult = await RestoreRunner.RunWithoutCommit(restoreRequests, restoreContext);

                return(restoreResult.Single());
            }
        }
Beispiel #5
0
        private static async Task <RestoreResultPair> PreviewAddPackageReferenceAsync(PackageReferenceArgs packageReferenceArgs,
                                                                                      DependencyGraphSpec dgSpec)
        {
            // Set user agent and connection settings.
            XPlatUtility.ConfigureProtocol();

            var providerCache = new RestoreCommandProvidersCache();

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

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>
                {
                    new DependencyGraphSpecRequestProvider(providerCache, dgSpec)
                };

                var restoreContext = new RestoreArgs()
                {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    Log                       = packageReferenceArgs.Logger,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    GlobalPackagesFolder      = packageReferenceArgs.PackageDirectory,
                    PreLoadedRequestProviders = providers,
                    Sources                   = packageReferenceArgs.Sources?.ToList()
                };

                // Generate Restore Requests. There will always be 1 request here since we are restoring for 1 project.
                var restoreRequests = await RestoreRunner.GetRequests(restoreContext);

                //Setup the Credential Service
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(restoreContext.Log, !packageReferenceArgs.Interactive);

                // Run restore without commit. This will always return 1 Result pair since we are restoring for 1 request.
                var restoreResult = await RestoreRunner.RunWithoutCommit(restoreRequests, restoreContext);

                return(restoreResult.Single());
            }
        }
Beispiel #6
0
        public async Task InstallPackageFromAnotherProcessVerifyCacheIsClearedAsync()
        {
            // Arrange
            var logger = new TestLogger();

            using (var cacheContext = new SourceCacheContext())
                using (var pathContext = new SimpleTestPathContext())
                {
                    var tfi = new List <TargetFrameworkInformation>
                    {
                        new TargetFrameworkInformation()
                        {
                            FrameworkName = NuGetFramework.Parse("net462")
                        }
                    };

                    var spec = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "net46");
                    spec.Dependencies.Add(new LibraryDependency()
                    {
                        LibraryRange = new LibraryRange("a", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package)
                    });

                    var project = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, spec).Single();

                    var packageA = new SimpleTestPackageContext("a");
                    await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageA);

                    // Create dg file
                    var dgFile = new DependencyGraphSpec();
                    dgFile.AddProject(spec);
                    dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName);

                    dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg"));

                    var providerCache = new RestoreCommandProvidersCache();
                    var sources       = new List <string>()
                    {
                        pathContext.PackageSource
                    };

                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = pathContext.UserPackagesFolder,
                        Sources = sources,
                        Log     = logger,
                        CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(new List <PackageSource>()
                        {
                            new PackageSource(pathContext.PackageSource)
                        })),
                        PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                        {
                            new DependencyGraphSpecRequestProvider(providerCache, dgFile)
                        }
                    };

                    var request   = (await RestoreRunner.GetRequests(restoreContext)).Single();
                    var providers = providerCache.GetOrCreate(pathContext.UserPackagesFolder, sources, new List <SourceRepository>(), cacheContext, logger, false);
                    var command   = new RestoreCommand(request.Request);

                    // Add to cache before install on all providers
                    var globalPackages = providers.GlobalPackages;
                    var packages       = globalPackages.FindPackagesById("a");
                    packages.Should().BeEmpty("has not been installed yet");

                    foreach (var local in providers.LocalProviders)
                    {
                        await local.GetDependenciesAsync(new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), NuGetFramework.Parse("net46"), cacheContext, logger, CancellationToken.None);
                    }

                    // Install the package without updating the cache
                    await SimpleTestPackageUtility.CreateFolderFeedV3Async(pathContext.UserPackagesFolder, PackageSaveMode.Defaultv3, packageA);

                    // Run restore using an incorrect cache
                    var result = await command.ExecuteAsync();

                    // Verify a is in the output assets file
                    result.Success.Should().BeTrue();
                    result.LockFile.GetLibrary("a", new NuGetVersion(1, 0, 0)).Should().NotBeNull();
                }
        }