Esempio n. 1
0
        private List <string> GetRestoreArguments()
        {
            List <string> args = new List <string>()
            {
                "-nologo"
            };

            // --interactive need to output guide for auth. It cannot be
            // completely "quiet"
            if (!RestoreArgs.Any(a => a.StartsWith("-verbosity:")))
            {
                var defaultVerbosity = Interactive ? "minimal" : "quiet";
                args.Add($"-verbosity:{defaultVerbosity}");
            }

            args.AddRange(RestoreArgs);

            return(args);
        }
Esempio n. 2
0
        internal static async Task <RestoreResult> RestoreAsync(RestoreParams restoreParameters, ILogger logger, CancellationToken cancellationToken = default)
        {
            var providerCache = new RestoreCommandProvidersCache();

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

                var providers = new List <IPreLoadedRestoreRequestProvider>();

                var dgSpec = new DependencyGraphSpec();
                dgSpec.AddRestore(restoreParameters.ProjectName);
                var projectSpec = new PackageSpec {
                    Name             = restoreParameters.ProjectName,
                    FilePath         = restoreParameters.ProjectName,
                    RestoreMetadata  = CreateRestoreMetadata(restoreParameters),
                    TargetFrameworks = { CreateTargetFramework(restoreParameters) }
                };
                dgSpec.AddProject(projectSpec);

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

                var restoreContext = new RestoreArgs {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    DisableParallel           = false,
                    Log                       = logger,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    AllowNoOp                 = true,
                    HideWarningsAndErrors     = true
                };

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, cancellationToken).ConfigureAwait(false);

                var result = new RestoreResult(
                    success: restoreSummaries.All(x => x.Success),
                    noOp: restoreSummaries.All(x => x.NoOpRestore),
                    errors: restoreSummaries.SelectMany(x => x.Errors).Select(x => x.Message).ToImmutableArray());

                return(result);
            }
        }
Esempio n. 3
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());
            }
        }
        /// <summary>
        /// Create a restore args.
        /// </summary>
        private static RestoreArgs GetRestoreArgs(
            DependencyGraphCacheContext context,
            RestoreCommandProvidersCache providerCache,
            SourceCacheContext sourceCacheContext,
            IEnumerable <SourceRepository> sources,
            DependencyGraphSpec dgFile,
            Guid parentId,
            bool forceRestore,
            bool isRestoreOriginalAction,
            bool restoreForceEvaluate,
            IReadOnlyList <IAssetsLogMessage> additionalMessasges,
            IRestoreProgressReporter progressReporter)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var caching = new CachingSourceProvider(new PackageSourceProvider(context.Settings, enablePackageSourcesChangedEvent: false));
#pragma warning restore CS0618 // Type or member is obsolete
            foreach (var source in sources)
            {
                caching.AddSourceRepository(source);
            }

            var dgProvider = new DependencyGraphSpecRequestProvider(providerCache, dgFile);

            var restoreContext = new RestoreArgs()
            {
                CacheContext = sourceCacheContext,
                PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                {
                    dgProvider
                },
                Log                     = context.Logger,
                AllowNoOp               = !forceRestore,
                CachingSourceProvider   = caching,
                ParentId                = parentId,
                IsRestoreOriginalAction = isRestoreOriginalAction,
                RestoreForceEvaluate    = restoreForceEvaluate,
                AdditionalMessages      = additionalMessasges,
                ProgressReporter        = progressReporter,
            };

            return(restoreContext);
        }
        public override bool Execute()
        {
            var args = new RestoreArgs
            {
                Inputs               = Inputs.Select(item => item.ItemSpec).ToList(),
                ConfigFile           = ConfigFile,
                GlobalPackagesFolder = PackagesDir,

                Sources          = new List <string>(),
                CacheContext     = new SourceCacheContext(),
                RequestProviders = new List <IRestoreRequestProvider>
                {
                    new WorkaroundProjectJsonRestoreRequestProvider(new RestoreCommandProvidersCache())
                },
                Log = new NugetMsBuildLogger(new TaskLoggingHelper(this))
            };

            RestoreRunner.RunAsync(args).Wait();

            return(!Log.HasLoggedErrors);
        }
Esempio n. 6
0
        public void RequestFactory_RestorePackagesArgRelativeToCwd()
        {
            // If a packages argument is provided, GetEffectiveGlobalPackagesFolder() should ignore
            // the provided root path and any configuration information and resolve relative to the
            // current working directory.

            // Arrange
            var globalPackagesFolder = "MyPackages";
            var restoreArgs          = new RestoreArgs()
            {
                GlobalPackagesFolder = globalPackagesFolder
            };

            // Act
            var resolvedGlobalPackagesFolder = restoreArgs.GetEffectiveGlobalPackagesFolder("C:\\Dummy", null);

            // Assert
            var expectedResolvedGlobalPackagesFolder = Path.GetFullPath(globalPackagesFolder);

            Assert.Equal(expectedResolvedGlobalPackagesFolder, resolvedGlobalPackagesFolder);
        }
Esempio n. 7
0
        /// <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,
            string userPackagesPath,
            ISettings settings,
            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.
                RestoreArgs restoreContext = GetRestoreContext(context, providerCache, settings, sourceCacheContext, sources, dgFile, userPackagesPath);

                var requests = await RestoreRunner.GetRequests(restoreContext);

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

                return(results.Single());
            }
        }
Esempio n. 8
0
        public async Task RestoreRunner_WarnIfNoProject()
        {
            // If an input folder is provided to RestoreRunner that doesn't contain a project,
            // it should report an error.

            using (var workingDir = TestDirectory.Create())
            {
                // Arrange
                var logger        = new TestLogger();
                var providerCache = new RestoreCommandProvidersCache();
                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext    = cacheContext,
                        DisableParallel = true,
                        Inputs          = new List <string>()
                        {
                            workingDir
                        },
                        Log = logger,
                        RequestProviders = new List <IRestoreRequestProvider>()
                        {
                            new ProjectJsonRestoreRequestProvider(providerCache)
                        }
                    };

                    // Act
                    var summaries = await RestoreRunner.Run(restoreContext);

                    // Assert
                    Assert.Equal(0, summaries.Count);
                    var matchingError = logger.Messages.ToList().Find(error => error.Contains(workingDir));
                    Assert.NotNull(matchingError);
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Create a restore context.
        /// </summary>
        private static RestoreArgs GetRestoreContext(
            DependencyGraphCacheContext context,
            RestoreCommandProvidersCache providerCache,
            SourceCacheContext sourceCacheContext,
            IEnumerable <SourceRepository> sources,
            DependencyGraphSpec dgFile,
            Guid parentId,
            bool forceRestore,
            bool isRestoreOriginalAction,
            bool restoreForceEvaluate)
        {
            var caching = new CachingSourceProvider(new PackageSourceProvider(context.Settings));

            foreach (var source in sources)
            {
                caching.AddSourceRepository(source);
            }

            var dgProvider = new DependencyGraphSpecRequestProvider(providerCache, dgFile);

            var restoreContext = new RestoreArgs()
            {
                CacheContext = sourceCacheContext,
                PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                {
                    dgProvider
                },
                Log                     = context.Logger,
                AllowNoOp               = !forceRestore,
                CachingSourceProvider   = caching,
                ParentId                = parentId,
                IsRestoreOriginalAction = isRestoreOriginalAction,
                RestoreForceEvaluate    = restoreForceEvaluate
            };

            return(restoreContext);
        }
            Task <IReadOnlyList <RestoreSummaryRequest> > IRestoreRequestProvider.CreateRequests(
                string inputPath,
                RestoreArgs restoreContext)
            {
                var paths = new List <string>();

                if (Directory.Exists(inputPath))
                {
                    paths.AddRange(GetProjectJsonFilesInDirectory(inputPath));
                }
                else
                {
                    paths.Add(inputPath);
                }

                var requests = new List <RestoreSummaryRequest>(paths.Count);

                foreach (var path in paths)
                {
                    requests.Add(Create(path, restoreContext));
                }

                return(System.Threading.Tasks.Task.FromResult <IReadOnlyList <RestoreSummaryRequest> >(requests));
            }
Esempio n. 11
0
        public async Task RequestFactory_FindProjectJsonFilesInDirectory()
        {
            // Arrange
            var cache    = new RestoreCommandProvidersCache();
            var provider = new ProjectJsonRestoreRequestProvider(cache);

            using (var workingDir = TestDirectory.Create())
            {
                var p1 = Path.Combine(workingDir, "project.json");
                var p2 = Path.Combine(workingDir, "sub", "project.json");
                var p3 = Path.Combine(workingDir, "myproj.project.json");

                Directory.CreateDirectory(Path.GetDirectoryName(p1));
                Directory.CreateDirectory(Path.GetDirectoryName(p2));

                File.WriteAllText(p1, EmptyProjectJson);
                File.WriteAllText(p2, EmptyProjectJson);
                File.WriteAllText(p3, EmptyProjectJson);

                var context = new RestoreArgs();
                using (var cacheContext = new SourceCacheContext())
                {
                    context.CacheContext = cacheContext;
                    context.Log          = new TestLogger();

                    // Act
                    var supports = await provider.Supports(workingDir);

                    var requests = await provider.CreateRequests(workingDir, context);

                    // Assert
                    Assert.Equal(true, supports);
                    Assert.Equal(3, requests.Count);
                }
            }
        }
Esempio n. 12
0
        public async Task RestoreRunner_RestoreWithRuntime()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger    = new TestLogger();
                var lockPath1 = Path.Combine(project1.FullName, "project.lock.json");

                var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList();

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = packagesDir.FullName,
                        Sources = new List <string>()
                        {
                            packageSource.FullName
                        },
                        Inputs = new List <string>()
                        {
                            specPath1
                        },
                        Log = logger,
                        CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(sources)),
                        RequestProviders      = new List <IRestoreRequestProvider>()
                        {
                            new ProjectJsonRestoreRequestProvider(providerCache)
                        }
                    };

                    restoreContext.Runtimes.Add("linux-x86");

                    // Act
                    var summaries = await RestoreRunner.Run(restoreContext);

                    var success = summaries.All(s => s.Success);

                    var lockFormat = new LockFileFormat();
                    var lockFile   = lockFormat.Read(lockPath1);

                    // Assert
                    Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                    Assert.True(lockFile.Targets.Any(graph => graph.RuntimeIdentifier == "linux-x86"));
                }
            }
        }
Esempio n. 13
0
        public async Task RestoreRunner_RestoreWithExternalFile_NetCoreOutput()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var targetFrameworkInfo1 = new TargetFrameworkInformation();

            targetFrameworkInfo1.FrameworkName = NuGetFramework.Parse("net45");
            var frameworks1 = new[] { targetFrameworkInfo1 };

            var targetFrameworkInfo2 = new TargetFrameworkInformation();

            targetFrameworkInfo2.FrameworkName = NuGetFramework.Parse("net45");
            var frameworks2 = new[] { targetFrameworkInfo2 };

            // Create two net45 projects
            var spec1 = new PackageSpec(frameworks1);

            spec1.RestoreMetadata = new ProjectRestoreMetadata();
            spec1.RestoreMetadata.ProjectUniqueName = "project1";
            spec1.RestoreMetadata.ProjectName       = "project1";
            spec1.RestoreMetadata.ProjectStyle      = ProjectStyle.PackageReference;
            spec1.RestoreMetadata.OriginalTargetFrameworks.Add("net45");

            var spec2 = new PackageSpec(frameworks2);

            spec2.RestoreMetadata = new ProjectRestoreMetadata();
            spec2.RestoreMetadata.ProjectUniqueName = "project2";
            spec2.RestoreMetadata.ProjectName       = "project2";
            spec2.RestoreMetadata.ProjectStyle      = ProjectStyle.PackageReference;
            spec2.RestoreMetadata.OriginalTargetFrameworks.Add("net45");

            var specs = new[] { spec1, spec2 };

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                var projPath1 = Path.Combine(project1.FullName, "project1.csproj");
                var projPath2 = Path.Combine(project2.FullName, "project2.csproj");
                File.WriteAllText(projPath1, string.Empty);
                File.WriteAllText(projPath2, string.Empty);

                spec1.RestoreMetadata.ProjectPath = projPath1;
                spec1.FilePath = projPath1;
                spec1.Name     = "project1";
                spec2.RestoreMetadata.ProjectPath = projPath2;
                spec2.FilePath = projPath1;
                spec2.Name     = "project2";

                var logger   = new TestLogger();
                var objPath1 = Path.Combine(project1.FullName, "obj");
                var objPath2 = Path.Combine(project2.FullName, "obj");

                spec1.RestoreMetadata.OutputPath = objPath1;
                spec2.RestoreMetadata.OutputPath = objPath2;

                spec1.RestoreMetadata.OriginalTargetFrameworks.Add("net45");
                spec2.RestoreMetadata.OriginalTargetFrameworks.Add("net45");

                var lockPath1 = Path.Combine(objPath1, "project.assets.json");
                var lockPath2 = Path.Combine(objPath2, "project.assets.json");

                // Link projects
                spec1.TargetFrameworks.Single().Dependencies.Add(new LibraryDependency()
                {
                    LibraryRange = new LibraryRange()
                    {
                        Name           = "project2",
                        TypeConstraint = LibraryDependencyTarget.ExternalProject
                    }
                });

                spec1.RestoreMetadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45")));
                spec1.RestoreMetadata.TargetFrameworks
                .Single()
                .ProjectReferences
                .Add(new ProjectRestoreReference()
                {
                    ProjectPath       = projPath2,
                    ProjectUniqueName = "project2"
                });

                // Create dg file
                var dgFile = new DependencyGraphSpec();

                foreach (var spec in specs)
                {
                    dgFile.AddRestore(spec.RestoreMetadata.ProjectName);
                    dgFile.AddProject(spec);
                }

                var dgPath = Path.Combine(workingDir, "input.dg");
                dgFile.Save(dgPath);

                var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList();

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = packagesDir.FullName,
                        Sources = new List <string>()
                        {
                            packageSource.FullName
                        },
                        Inputs = new List <string>()
                        {
                            dgPath
                        },
                        Log = logger,
                        CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(sources)),
                        RequestProviders      = new List <IRestoreRequestProvider>()
                        {
                            new DependencyGraphFileRequestProvider(providerCache)
                        }
                    };

                    // Act
                    var summaries = await RestoreRunner.Run(restoreContext);

                    var success = summaries.All(s => s.Success);

                    var lockFormat  = new LockFileFormat();
                    var lockFile1   = lockFormat.Read(lockPath1);
                    var project2Lib = lockFile1.Libraries.First();

                    // Assert
                    Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                    Assert.True(File.Exists(lockPath1), lockPath1);
                    Assert.True(File.Exists(lockPath2), lockPath2);
                    Assert.Equal("project2", project2Lib.Name);
                }
            }
        }
        public async Task ProjectResolution_HigherVersionForProjectReferences()
        {
            // Arrange
            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project2Json = @"
            {
              ""version"": ""2.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(project2.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);

                var logger = new TestLogger();

                var restoreContext = new RestoreArgs()
                {
                    Sources = new List <string>()
                    {
                        packageSource.FullName
                    },
                    GlobalPackagesFolder = packagesDir.FullName,
                    Log          = logger,
                    CacheContext = new SourceCacheContext()
                };

                // Modify specs for netcore
                spec2 = spec2.WithTestRestoreMetadata();
                spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2);

                var request = await ProjectJsonTestHelpers.GetRequestAsync(restoreContext, spec1, spec2);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                // Act
                var command = new RestoreCommand(request);
                var result  = await command.ExecuteAsync();

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success);
                Assert.Equal(0, result.GetAllUnresolved().Count);
                Assert.Equal(0, logger.Messages.Where(s => s.IndexOf("Dependency specified was") > -1).Count());
            }
        }
        public async Task ProjectResolution_ProjectFrameworkAssemblyReferences()
        {
            // Arrange
            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project2Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                   ""frameworkAssemblies"": {
                     ""ReferenceA"": """",
                     ""ReferenceB"": """",
                   },
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(project2.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);

                var logger = new TestLogger();

                var restoreContext = new RestoreArgs()
                {
                    Sources = new List <string>()
                    {
                        packageSource.FullName
                    },
                    GlobalPackagesFolder = packagesDir.FullName,
                    Log          = logger,
                    CacheContext = new SourceCacheContext()
                };

                // Modify specs for netcore
                spec2 = spec2.WithTestRestoreMetadata();
                spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2);

                var request = await ProjectJsonTestHelpers.GetRequestAsync(restoreContext, spec1, spec2);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                // Act
                var command = new RestoreCommand(request);
                var result  = await command.ExecuteAsync();

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var target              = result.LockFile.GetTarget(NuGetFramework.Parse("net45"), null);
                var project2Lib         = target.Libraries.Where(lib => lib.Name == "project2").Single();
                var frameworkReferences = project2Lib.FrameworkAssemblies;

                // Assert
                Assert.True(result.Success);
                Assert.Equal(2, frameworkReferences.Count);
                Assert.Equal("ReferenceA", frameworkReferences[0]);
                Assert.Equal("ReferenceB", frameworkReferences[1]);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Fetch, if not already downloaded, and install the package represented by
        /// (<paramref name="packageId"/>, <paramref name="version"/>).
        /// </summary>
        /// <remarks>It is safe to call it concurrently be cause we operations are done using the FileLock.</remarks>
        /// <param name="packageId">Name of package to install.</param>
        /// <param name="version">Version of package to install.</param>
        public async Task <NugetLocalPackage> InstallPackage(string packageId, PackageVersion version, IEnumerable <string> targetFrameworks, ProgressReport progress)
        {
            using (GetLocalRepositoryLock())
            {
                currentProgressReport = progress;
                try
                {
                    var identity = new PackageIdentity(packageId, version.ToNuGetVersion());

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

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

                    var projectContext = new EmptyNuGetProjectContext()
                    {
                        ActionType = NuGetActionType.Install,
                        PackageExtractionContext = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.Skip, null, NativeLogger),
                    };

                    ActivityCorrelationId.StartNew();

                    {
                        var installPath = SettingsUtility.GetGlobalPackagesFolder(settings);

                        // In case it's a package without any TFM (i.e. Visual Studio plugin), we still need to specify one
                        if (!targetFrameworks.Any())
                        {
                            targetFrameworks = new string[] { "net6.0" }
                        }
                        ;

                        // Old version expects to be installed in GamePackages
                        if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0) && oldRootDirectory != null)
                        {
                            installPath = oldRootDirectory;
                        }

                        var projectPath = Path.Combine("StrideLauncher.json");
                        var spec        = new PackageSpec()
                        {
                            Name         = Path.GetFileNameWithoutExtension(projectPath), // make sure this package never collides with a dependency
                            FilePath     = projectPath,
                            Dependencies = new List <LibraryDependency>()
                            {
                                new LibraryDependency
                                {
                                    LibraryRange = new LibraryRange(packageId, new VersionRange(version.ToNuGetVersion()), LibraryDependencyTarget.Package),
                                }
                            },
                            RestoreMetadata = new ProjectRestoreMetadata
                            {
                                ProjectPath              = projectPath,
                                ProjectName              = Path.GetFileNameWithoutExtension(projectPath),
                                ProjectStyle             = ProjectStyle.PackageReference,
                                ProjectUniqueName        = projectPath,
                                OutputPath               = Path.Combine(Path.GetTempPath(), $"StrideLauncher-{packageId}-{version.ToString()}"),
                                OriginalTargetFrameworks = targetFrameworks.ToList(),
                                ConfigFilePaths          = settings.GetConfigFilePaths(),
                                PackagesPath             = installPath,
                                Sources         = SettingsUtility.GetEnabledSources(settings).ToList(),
                                FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList()
                            },
                        };
                        foreach (var targetFramework in targetFrameworks)
                        {
                            spec.TargetFrameworks.Add(new TargetFrameworkInformation {
                                FrameworkName = NuGetFramework.Parse(targetFramework)
                            });
                        }

                        using (var context = new SourceCacheContext {
                            MaxAge = DateTimeOffset.UtcNow
                        })
                        {
                            context.IgnoreFailedSources = true;

                            var dependencyGraphSpec = new DependencyGraphSpec();

                            dependencyGraphSpec.AddProject(spec);

                            dependencyGraphSpec.AddRestore(spec.RestoreMetadata.ProjectUniqueName);

                            IPreLoadedRestoreRequestProvider requestProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dependencyGraphSpec);

                            var restoreArgs = new RestoreArgs
                            {
                                AllowNoOp             = true,
                                CacheContext          = context,
                                CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(settings)),
                                Log = NativeLogger,
                            };

                            // Create requests from the arguments
                            var requests = requestProvider.CreateRequests(restoreArgs).Result;

                            foreach (var request in requests)
                            {
                                // Limit concurrency to avoid timeout
                                request.Request.MaxDegreeOfConcurrency = 4;

                                var command = new RestoreCommand(request.Request);

                                // Act
                                var result = await command.ExecuteAsync();

                                if (!result.Success)
                                {
                                    throw new InvalidOperationException($"Could not restore package {packageId}");
                                }
                                foreach (var install in result.RestoreGraphs.Last().Install)
                                {
                                    var package = result.LockFile.Libraries.FirstOrDefault(x => x.Name == install.Library.Name && x.Version == install.Library.Version);
                                    if (package != null)
                                    {
                                        var packagePath = Path.Combine(installPath, package.Path);
                                        OnPackageInstalled(this, new PackageOperationEventArgs(new PackageName(install.Library.Name, install.Library.Version.ToPackageVersion()), packagePath));
                                    }
                                }
                            }
                        }

                        if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0))
                        {
                            UpdateTargetsHelper();
                        }
                    }

                    // Load the recently installed package
                    var installedPackages = GetPackagesInstalled(new[] { packageId });
                    return(installedPackages.FirstOrDefault(p => p.Version == version));
                }
                finally
                {
                    currentProgressReport = null;
                }
            }
        }
        async Task RestorePackagesAsync(
            IEnumerable <InteractivePackage> packages,
            SourceCacheContext cacheContext,
            CancellationToken cancellationToken)
        {
            var restoreContext = new RestoreArgs {
                CacheContext = cacheContext,
                Log          = Logger,
            };

            // NOTE: This path is typically empty. It could in theory contain nuget.config settings
            //       files, but really we just use it to satisfy nuget API that requires paths,
            //       even when they are never used.
            var rootPath      = packageConfigDirectory;
            var globalPath    = restoreContext.GetEffectiveGlobalPackagesFolder(rootPath, settings);
            var fallbackPaths = restoreContext.GetEffectiveFallbackPackageFolders(settings);

            var providerCache    = new RestoreCommandProvidersCache();
            var restoreProviders = providerCache.GetOrCreate(
                globalPath,
                fallbackPaths,
                SourceRepositories,
                cacheContext,
                Logger);

            // Set up a project spec similar to what you would see in a project.json.
            // This is sufficient for the dependency graph work done within RestoreCommand.
            // TODO: XF version pinning during restore?
            var targetFrameworkInformation = new TargetFrameworkInformation {
                FrameworkName = TargetFramework,
                Dependencies  = packages.Select(ToLibraryDependency).ToList(),
            };
            var projectSpec = new PackageSpec(new [] { targetFrameworkInformation })
            {
                Name     = project.Name,
                FilePath = rootPath,
            };

            var restoreRequest = new RestoreRequest(projectSpec, restoreProviders, cacheContext, Logger);
            var restoreCommand = new RestoreCommand(restoreRequest);
            var result         = await restoreCommand.ExecuteAsync(cancellationToken);

            if (!result.Success)
            {
                return;
            }

            project.ResetInstallationContext();

            // As with installation, restore simply ensures that packages are present in the user's
            // global package cache. We reference them out of there just like .NET core projects do.
            //
            // All resolved packages, including the explicit inputs and their dependencies, are
            // available as LockFileLibrary instances.
            foreach (var library in result.LockFile.Libraries)
            {
                project.InstallationContext.AddInstalledPackage(
                    GetInteractivePackageFromLibrary(library, project, packages));
            }

            installedPackages = project.InstallationContext.InstalledPackages;
            UpdateInstalledPackages();
        }
Esempio n. 18
0
        private RestoreTargetGraph GetRestoreTargetGraph(List <PackageReference> packages, string projectPath, List <NuGetFramework> targetFrameworks, SourceCacheContext sourceCacheContext)
        {
            // The package spec details what packages to restore
            PackageSpec packageSpec = new PackageSpec(targetFrameworks.Select(i => new TargetFrameworkInformation
            {
                FrameworkName = i
            }).ToList())
            {
                //Dependencies = new List<LibraryDependency>
                //{
                //    new LibraryDependency
                //    {
                //        LibraryRange = new LibraryRange(id, new VersionRange(NuGetVersion.Parse(version)), LibraryDependencyTarget.Package),
                //        SuppressParent = LibraryIncludeFlags.All,
                //        AutoReferenced = true,
                //        IncludeType = LibraryIncludeFlags.None,
                //        Type = LibraryDependencyType.Build
                //    }
                //},
                Dependencies = packages.Select(i => new LibraryDependency
                {
                    LibraryRange = new LibraryRange(i.PackageId, new VersionRange(i.PackageVersion), LibraryDependencyTarget.Package),
                    //SuppressParent = LibraryIncludeFlags.All,
                    //AutoReferenced = true,
                    //IncludeType = LibraryIncludeFlags.None,
                    //Type = LibraryDependencyType.
                }).ToList(),
                RestoreMetadata = new ProjectRestoreMetadata
                {
                    ProjectPath              = projectPath,
                    ProjectName              = Path.GetFileNameWithoutExtension(projectPath),
                    ProjectStyle             = ProjectStyle.PackageReference,
                    ProjectUniqueName        = projectPath,
                    OutputPath               = Path.GetTempPath(),
                    OriginalTargetFrameworks = targetFrameworks.Select(i => i.ToString()).ToList(),
                    ConfigFilePaths          = SettingsUtility.GetConfigFilePaths(_nugetSettings).ToList(),
                    PackagesPath             = SettingsUtility.GetGlobalPackagesFolder(_nugetSettings),
                    Sources         = SettingsUtility.GetEnabledSources(_nugetSettings).ToList(),
                    FallbackFolders = SettingsUtility.GetFallbackPackageFolders(_nugetSettings).ToList()
                },
                FilePath = projectPath,
                Name     = Path.GetFileNameWithoutExtension(projectPath),
            };

            DependencyGraphSpec dependencyGraphSpec = new DependencyGraphSpec();

            dependencyGraphSpec.AddProject(packageSpec);

            dependencyGraphSpec.AddRestore(packageSpec.RestoreMetadata.ProjectUniqueName);

            IPreLoadedRestoreRequestProvider requestProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dependencyGraphSpec);

            RestoreArgs restoreArgs = new RestoreArgs
            {
                AllowNoOp             = true,
                CacheContext          = sourceCacheContext,
                CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(_nugetSettings)),
                Log = NullLogger.Instance,
            };

            // Create requests from the arguments
            IReadOnlyList <RestoreSummaryRequest> requests = requestProvider.CreateRequests(restoreArgs).Result;

            // Restore the package without generating extra files
            RestoreResultPair restoreResult = RestoreRunner.RunWithoutCommit(requests, restoreArgs).Result.FirstOrDefault();

            RestoreTargetGraph restoreTargetGraph = restoreResult?.Result.RestoreGraphs.FirstOrDefault();

            return(restoreTargetGraph);
        }
Esempio n. 19
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Set user agent and connection settings.
            ConfigureProtocol();

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            //var graphLines = RestoreGraphItems;
            var providerCache = new RestoreCommandProvidersCache();

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

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

                var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

                if (dgFile.Restore.Count < 1)
                {
                    // Restore will fail if given no inputs, but here we should skip it and provide a friendly message.
                    log.LogMinimal(Strings.NoProjectsToRestore);
                    return(true);
                }

                // Add all child projects
                if (RestoreRecursive)
                {
                    BuildTasksUtility.AddAllProjectsForRestore(dgFile);
                }

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

                var defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null);
                var sourceProvider  = new CachingSourceProvider(new PackageSourceProvider(defaultSettings));

                var restoreContext = new RestoreArgs()
                {
                    CacheContext         = cacheContext,
                    LockFileVersion      = LockFileFormat.Version,
                    ConfigFile           = MSBuildStringUtility.TrimAndGetNullForEmpty(RestoreConfigFile),
                    DisableParallel      = RestoreDisableParallel,
                    GlobalPackagesFolder = RestorePackagesPath,
                    Log = log,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    CachingSourceProvider     = sourceProvider,
                    AllowNoOp             = !RestoreForce,
                    HideWarningsAndErrors = HideWarningsAndErrors
                };

                if (!string.IsNullOrEmpty(RestoreSources))
                {
                    var sources = MSBuildStringUtility.Split(RestoreSources);
                    restoreContext.Sources.AddRange(sources);
                }

                if (restoreContext.DisableParallel)
                {
                    HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                }

                _cts.Token.ThrowIfCancellationRequested();

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, _cts.Token);

                // Summary
                RestoreSummary.Log(log, restoreSummaries);

                return(restoreSummaries.All(x => x.Success));
            }
        }
Esempio n. 20
0
        public static async Task <bool> RestoreAsync(
            DependencyGraphSpec dependencyGraphSpec,
            bool interactive,
            bool recursive,
            bool noCache,
            bool ignoreFailedSources,
            bool disableParallel,
            bool force,
            bool forceEvaluate,
            bool hideWarningsAndErrors,
            bool restorePC,
            bool cleanupAssetsForUnsupportedProjects,
            Common.ILogger log,
            CancellationToken cancellationToken)
        {
            if (dependencyGraphSpec == null)
            {
                throw new ArgumentNullException(nameof(dependencyGraphSpec));
            }

            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            try
            {
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !interactive);

                // Set connection limit
                NetworkProtocolUtility.SetConnectionLimit();

                // Set user agent string used for network calls
#if IS_CORECLR
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet .NET Core MSBuild Task")
                                             .WithOSDescription(RuntimeInformation.OSDescription));
#else
                // OS description is set by default on Desktop
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet Desktop MSBuild Task"));
#endif

                X509TrustStore.InitializeForDotNetSdk(log);

                var restoreSummaries = new List <RestoreSummary>();
                var providerCache    = new RestoreCommandProvidersCache();

#if IS_DESKTOP
                if (restorePC && dependencyGraphSpec.Projects.Any(i => i.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig))
                {
                    var v2RestoreResult = await PerformNuGetV2RestoreAsync(log, dependencyGraphSpec, noCache, disableParallel, interactive);

                    restoreSummaries.Add(v2RestoreResult);

                    if (restoreSummaries.Count < 1)
                    {
                        var message = string.Format(
                            Strings.InstallCommandNothingToInstall,
                            "packages.config"
                            );

                        log.LogMinimal(message);
                    }

                    if (!v2RestoreResult.Success)
                    {
                        v2RestoreResult
                        .Errors
                        .Where(l => l.Level == LogLevel.Warning)
                        .ForEach(message =>
                        {
                            log.LogWarning(message.Message);
                        });
                    }
                }
#endif

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

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

                    if (dependencyGraphSpec.Restore.Count > 0)
                    {
                        // Add all child projects
                        if (recursive)
                        {
                            AddAllProjectsForRestore(dependencyGraphSpec);
                        }

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

                        var restoreContext = new RestoreArgs()
                        {
                            CacheContext    = cacheContext,
                            LockFileVersion = LockFileFormat.Version,
                            // 'dotnet restore' fails on slow machines (https://github.com/NuGet/Home/issues/6742)
                            // The workaround is to pass the '--disable-parallel' option.
                            // We apply the workaround by default when the system has 1 cpu.
                            // This will fix restore failures on VMs with 1 CPU and containers with less or equal to 1 CPU assigned.
                            DisableParallel           = Environment.ProcessorCount == 1 ? true : disableParallel,
                            Log                       = log,
                            MachineWideSettings       = new XPlatMachineWideSetting(),
                            PreLoadedRequestProviders = providers,
                            AllowNoOp                 = !force,
                            HideWarningsAndErrors     = hideWarningsAndErrors,
                            RestoreForceEvaluate      = forceEvaluate
                        };

                        if (restoreContext.DisableParallel)
                        {
                            HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        restoreSummaries.AddRange(await RestoreRunner.RunAsync(restoreContext, cancellationToken));
                    }

                    if (cleanupAssetsForUnsupportedProjects)
                    {
                        // Restore assets are normally left on disk between restores for all projects.  This can cause a condition where a project that supports PackageReference was restored
                        // but then a user changes a branch or some other condition and now the project does not use PackageReference. Since the restore assets are left on disk, the build
                        // consumes them which can cause build errors. The code below cleans up all of the files that we write so that they are not used during build
                        Parallel.ForEach(dependencyGraphSpec.Projects.Where(i => !DoesProjectSupportRestore(i)), project =>
                        {
                            if (project.RestoreMetadata == null || string.IsNullOrWhiteSpace(project.RestoreMetadata.OutputPath) || string.IsNullOrWhiteSpace(project.RestoreMetadata.ProjectPath))
                            {
                                return;
                            }

                            // project.assets.json
                            FileUtility.Delete(Path.Combine(project.RestoreMetadata.OutputPath, LockFileFormat.AssetsFileName));

                            // project.csproj.nuget.cache
                            FileUtility.Delete(project.RestoreMetadata.CacheFilePath);

                            // project.csproj.nuget.g.props
                            FileUtility.Delete(BuildAssetsUtils.GetMSBuildFilePathForPackageReferenceStyleProject(project, BuildAssetsUtils.PropsExtension));

                            // project..csproj.nuget.g.targets
                            FileUtility.Delete(BuildAssetsUtils.GetMSBuildFilePathForPackageReferenceStyleProject(project, BuildAssetsUtils.TargetsExtension));

                            // project.csproj.nuget.dgspec.json
                            FileUtility.Delete(Path.Combine(project.RestoreMetadata.OutputPath, DependencyGraphSpec.GetDGSpecFileName(Path.GetFileName(project.RestoreMetadata.ProjectPath))));
                        });
                    }
                }

                if (restoreSummaries.Count < 1)
                {
                    log.LogMinimal(Strings.NoProjectsToRestore);
                }
                else
                {
                    RestoreSummary.Log(log, restoreSummaries);
                }
                return(restoreSummaries.All(x => x.Success));
            }
            finally
            {
                // The CredentialService lifetime is for the duration of the process. We should not leave a potentially unavailable logger.
                // We need to update the delegating logger with a null instance
                // because the tear downs of the plugins and similar rely on idleness and process exit.
                DefaultCredentialServiceUtility.UpdateCredentialServiceDelegatingLogger(NullLogger.Instance);
            }
        }
Esempio n. 21
0
        public static void Register(
            CommandLineApplication cmdApp,
            CommandOutputLogger log)
        {
            cmdApp.Command("restore", (Action<CommandLineApplication>)(restore =>
            {
                restore.Description = "Restores packages for a project and writes a lock file.";
                restore.HelpOption(XPlatUtility.HelpOption);

                var sources = restore.Option(
                    "-s|--source <source>",
                    "Specifies a NuGet package source to use during the restore.",
                    CommandOptionType.MultipleValue);

                var packagesDirectory = restore.Option(
                    "--packages <packagesDirectory>",
                    "Directory to install packages in.",
                    CommandOptionType.SingleValue);

                var disableParallel = restore.Option(
                    "--disable-parallel",
                   "Disables restoring multiple projects in parallel.",
                    CommandOptionType.NoValue);

                var fallBack = restore.Option(
                    "-f|--fallbacksource <FEED>",
                    "A list of packages sources to use as a fallback.",
                    CommandOptionType.MultipleValue);

                var runtime = restore.Option(
                    "--runtime <RID>",
                    "List of runtime identifiers to restore for.",
                    CommandOptionType.MultipleValue);

                var configFile = restore.Option(
                    "--configfile <file>",
                   "The NuGet configuration file to use.",
                    CommandOptionType.SingleValue);

                var noCache = restore.Option(
                    "--no-cache",
                    "Do not cache packages and http requests.",
                    CommandOptionType.NoValue);

                var verbosity = restore.Option(
                    XPlatUtility.VerbosityOption,
                    "The verbosity of logging to use. Allowed values: Debug, Verbose, Information, Minimal, Warning, Error.",
                    CommandOptionType.SingleValue);

                var argRoot = restore.Argument(
                    "[root]",
                    "List of projects and project folders to restore. Each value can be: a path to a project.json or global.json file, or a folder to recursively search for project.json files.",
                    multipleValues: true);

                restore.OnExecute(async () =>
                {
                    var logLevel = XPlatUtility.GetLogLevel(verbosity);
                    log.SetLogLevel(logLevel);

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

                        // Ordered request providers
                        var providers = new List<IRestoreRequestProvider>();
                        providers.Add(new MSBuildP2PRestoreRequestProvider(providerCache));
                        providers.Add(new ProjectJsonRestoreRequestProvider(providerCache));

                        var restoreContext = new RestoreArgs()
                        {
                            CacheContext = cacheContext,
                            LockFileVersion = LockFileFormat.Version,
                            ConfigFileName = configFile.HasValue() ? configFile.Value() : null,
                            DisableParallel = true,
                            GlobalPackagesFolder = packagesDirectory.HasValue() ? packagesDirectory.Value() : null,
                            Inputs = new List<string>(argRoot.Values),
                            Log = log,
                            MachineWideSettings = new CommandLineXPlatMachineWideSetting(),
                            RequestProviders = providers,
                            Sources = sources.Values,
                            FallbackSources = fallBack.Values,
                            CachingSourceProvider = _sourceProvider
                        };

                        restoreContext.Runtimes.UnionWith(runtime.Values);

                        var restoreSummaries = await RestoreRunner.Run(restoreContext);

                        // Summary
                        RestoreSummary.Log(log, restoreSummaries, logLevel < LogLevel.Minimal);

                        return restoreSummaries.All(x => x.Success) ? 0 : 1;
                    }
                });
            }));
        }
Esempio n. 22
0
        public static async Task <(RestoreRequest, RestoreResult)> Restore(ILogger logger, string packageName, VersionRange versionRange)
        {
            var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var installPath           = SettingsUtility.GetGlobalPackagesFolder(settings);
            var assemblies            = new List <string>();

            var projectPath = Path.Combine("XenkoNugetResolver.json");
            var spec        = new PackageSpec()
            {
                Name         = Path.GetFileNameWithoutExtension(projectPath), // make sure this package never collides with a dependency
                FilePath     = projectPath,
                Dependencies = new List <LibraryDependency>()
                {
                    new LibraryDependency
                    {
                        LibraryRange = new LibraryRange(packageName, versionRange, LibraryDependencyTarget.Package),
                    }
                },
                TargetFrameworks =
                {
                    new TargetFrameworkInformation
                    {
                        FrameworkName = NuGetFramework.Parse("net48"),
                    }
                },
                RestoreMetadata = new ProjectRestoreMetadata
                {
                    ProjectPath              = projectPath,
                    ProjectName              = Path.GetFileNameWithoutExtension(projectPath),
                    ProjectStyle             = ProjectStyle.PackageReference,
                    ProjectUniqueName        = projectPath,
                    OutputPath               = Path.Combine(Path.GetTempPath(), $"XenkoNugetResolver-{packageName}-{versionRange.MinVersion.ToString()}"),
                    OriginalTargetFrameworks = new[] { "net48" },
                    ConfigFilePaths          = settings.GetConfigFilePaths(),
                    PackagesPath             = SettingsUtility.GetGlobalPackagesFolder(settings),
                    Sources         = SettingsUtility.GetEnabledSources(settings).ToList(),
                    FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList()
                },
            };

            // remove all remote sources, so we don't have to worry about connectivity issues
            // we are only restoring local dev packages anyway
            for (int i = 0; i < spec.RestoreMetadata.Sources.Count; i++)
            {
                var s = spec.RestoreMetadata.Sources[i];
                if (s.IsLocal == false)
                {
                    spec.RestoreMetadata.Sources.RemoveAt(i);
                    i--;
                }
            }

            using (var context = new SourceCacheContext())
            {
                context.IgnoreFailedSources = true;

                var dependencyGraphSpec = new DependencyGraphSpec();

                dependencyGraphSpec.AddProject(spec);

                dependencyGraphSpec.AddRestore(spec.RestoreMetadata.ProjectUniqueName);

                IPreLoadedRestoreRequestProvider requestProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dependencyGraphSpec);

                var restoreArgs = new RestoreArgs
                {
                    AllowNoOp             = true,
                    CacheContext          = context,
                    CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(settings)),
                    Log = logger,
                };

                // Create requests from the arguments
                var requests = requestProvider.CreateRequests(restoreArgs).Result;

                // Restore the packages
                for (int tryCount = 0; tryCount < 2; ++tryCount)
                {
                    try
                    {
                        var results = await RestoreRunner.RunWithoutCommit(requests, restoreArgs);

                        // Commit results so that noop cache works next time
                        foreach (var result in results)
                        {
                            await result.Result.CommitAsync(logger, CancellationToken.None);
                        }
                        var mainResult = results.First();
                        return(mainResult.SummaryRequest.Request, mainResult.Result);
                    }
                    catch (Exception e) when(e is UnauthorizedAccessException || e is IOException)
                    {
                        // If we have an unauthorized access exception, it means assemblies are locked by running Xenko process
                        // During first try, kill some known harmless processes, and try again
                        if (tryCount == 1)
                        {
                            throw;
                        }

                        foreach (var process in new[] { "Xenko.ConnectionRouter" }.SelectMany(Process.GetProcessesByName))
                        {
                            try
                            {
                                if (process.Id != Process.GetCurrentProcess().Id)
                                {
                                    process.Kill();
                                    process.WaitForExit();
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }

                throw new InvalidOperationException("Unreachable code");
            }
        }
Esempio n. 23
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1 && !HideWarningsAndErrors)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Set user agent and connection settings.
            ConfigureProtocol();

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            //var graphLines = RestoreGraphItems;
            var providerCache = new RestoreCommandProvidersCache();

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

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

                var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

                if (dgFile.Restore.Count < 1)
                {
                    // Restore will fail if given no inputs, but here we should skip it and provide a friendly message.
                    log.LogMinimal(Strings.NoProjectsToRestore);
                    return(true);
                }

                // Add all child projects
                if (RestoreRecursive)
                {
                    BuildTasksUtility.AddAllProjectsForRestore(dgFile);
                }

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

                var restoreContext = new RestoreArgs()
                {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    DisableParallel           = RestoreDisableParallel,
                    Log                       = log,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    AllowNoOp                 = !RestoreForce,
                    HideWarningsAndErrors     = HideWarningsAndErrors,
                    RestoreForceEvaluate      = RestoreForceEvaluate
                };

                // 'dotnet restore' fails on slow machines (https://github.com/NuGet/Home/issues/6742)
                // The workaround is to pass the '--disable-parallel' option.
                // We apply the workaround by default when the system has 1 cpu.
                // This will fix restore failures on VMs with 1 CPU and containers with less or equal to 1 CPU assigned.
                if (Environment.ProcessorCount == 1)
                {
                    restoreContext.DisableParallel = true;
                }

                if (restoreContext.DisableParallel)
                {
                    HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                }

                _cts.Token.ThrowIfCancellationRequested();

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, _cts.Token);

                // Summary
                RestoreSummary.Log(log, restoreSummaries);

                return(restoreSummaries.All(x => x.Success));
            }
        }
Esempio n. 24
0
        public static async Task <bool> RestoreAsync(
            DependencyGraphSpec dependencyGraphSpec,
            bool interactive,
            bool recursive,
            bool noCache,
            bool ignoreFailedSources,
            bool disableParallel,
            bool force,
            bool forceEvaluate,
            bool hideWarningsAndErrors,
            bool restorePC,
            Common.ILogger log,
            CancellationToken cancellationToken)
        {
            if (dependencyGraphSpec == null)
            {
                throw new ArgumentNullException(nameof(dependencyGraphSpec));
            }

            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            try
            {
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !interactive);

                // Set connection limit
                NetworkProtocolUtility.SetConnectionLimit();

                // Set user agent string used for network calls
#if IS_CORECLR
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet .NET Core MSBuild Task")
                                             .WithOSDescription(RuntimeInformation.OSDescription));
#else
                // OS description is set by default on Desktop
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet Desktop MSBuild Task"));
#endif

                // This method has no effect on .NET Core.
                NetworkProtocolUtility.ConfigureSupportedSslProtocols();

                var restoreSummaries = new List <RestoreSummary>();
                var providerCache    = new RestoreCommandProvidersCache();

#if IS_DESKTOP
                if (restorePC && dependencyGraphSpec.Projects.Any(i => i.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig))
                {
                    var v2RestoreResult = await PerformNuGetV2RestoreAsync(log, dependencyGraphSpec, noCache, disableParallel, interactive);

                    restoreSummaries.Add(v2RestoreResult);

                    if (restoreSummaries.Count < 1)
                    {
                        var message = string.Format(
                            Strings.InstallCommandNothingToInstall,
                            "packages.config"
                            );

                        log.LogMinimal(message);
                    }

                    if (!v2RestoreResult.Success)
                    {
                        v2RestoreResult
                        .Errors
                        .Where(l => l.Level == LogLevel.Warning)
                        .ForEach(message =>
                        {
                            log.LogWarning(message.Message);
                        });
                    }
                }
#endif

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

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

                    if (dependencyGraphSpec.Restore.Count > 0)
                    {
                        // Add all child projects
                        if (recursive)
                        {
                            AddAllProjectsForRestore(dependencyGraphSpec);
                        }

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

                        var restoreContext = new RestoreArgs()
                        {
                            CacheContext    = cacheContext,
                            LockFileVersion = LockFileFormat.Version,
                            // 'dotnet restore' fails on slow machines (https://github.com/NuGet/Home/issues/6742)
                            // The workaround is to pass the '--disable-parallel' option.
                            // We apply the workaround by default when the system has 1 cpu.
                            // This will fix restore failures on VMs with 1 CPU and containers with less or equal to 1 CPU assigned.
                            DisableParallel           = Environment.ProcessorCount == 1 ? true : disableParallel,
                            Log                       = log,
                            MachineWideSettings       = new XPlatMachineWideSetting(),
                            PreLoadedRequestProviders = providers,
                            AllowNoOp                 = !force,
                            HideWarningsAndErrors     = hideWarningsAndErrors,
                            RestoreForceEvaluate      = forceEvaluate
                        };

                        if (restoreContext.DisableParallel)
                        {
                            HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        restoreSummaries.AddRange(await RestoreRunner.RunAsync(restoreContext, cancellationToken));
                    }
                }

                if (restoreSummaries.Count < 1)
                {
                    log.LogMinimal(Strings.NoProjectsToRestore);
                }
                else
                {
                    RestoreSummary.Log(log, restoreSummaries);
                }
                return(restoreSummaries.All(x => x.Success));
            }
            finally
            {
                // The CredentialService lifetime is for the duration of the process. We should not leave a potentially unavailable logger.
                // We need to update the delegating logger with a null instance
                // because the tear downs of the plugins and similar rely on idleness and process exit.
                DefaultCredentialServiceUtility.UpdateCredentialServiceDelegatingLogger(NullLogger.Instance);
            }
        }
        public async Task DependencyTypeConstraint_PackagesDependOnProject()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""dependencies"": {
                ""packageA"": ""1.0.0""
              },
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var packageBProjectJson = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir     = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource   = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1        = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                var packageBProject = new DirectoryInfo(Path.Combine(workingDir, "projects", "packageB"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                packageBProject.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(packageBProject.FullName, "project.json"), packageBProjectJson);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(packageBProject.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(packageBProjectJson, "packageB", specPath2);

                var packageAPath = SimpleTestPackageUtility.CreateFullPackage(
                    packageSource.FullName,
                    "packageA",
                    "1.0.0",
                    new Packaging.Core.PackageDependency[]
                {
                    new Packaging.Core.PackageDependency("packageB", VersionRange.Parse("1.0.0"))
                });

                await GlobalFolderUtility.AddPackageToGlobalFolderAsync(packageAPath, packagesDir);

                var logger = new TestLogger();

                var restoreContext = new RestoreArgs()
                {
                    Sources = new List <string>()
                    {
                        packageSource.FullName
                    },
                    GlobalPackagesFolder = packagesDir.FullName,
                    Log          = logger,
                    CacheContext = new SourceCacheContext()
                };

                // Modify specs for netcore
                spec2 = spec2.WithTestRestoreMetadata();
                spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2);

                var request = await ProjectJsonTestHelpers.GetRequestAsync(restoreContext, spec1, spec2);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                // Act
                var command = new RestoreCommand(request);
                var result  = await command.ExecuteAsync();

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success);
                var packageBLib = lockFile.GetLibrary("packageB", NuGetVersion.Parse("1.0.0"));
                Assert.NotNull(packageBLib);
                Assert.Equal(LibraryType.Project, packageBLib.Type);
            }
        }
        public async Task Project2ProjectInLockFile_VerifyProjectsReferencesInLibAndTargets()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
                ""version"": ""1.0.0"",
                ""frameworks"": {
                    ""net45"": {}
                }
            }";

            var project2Json = @"
            {
                ""version"": ""1.0.0"",
                ""frameworks"": {
                    ""net45"": {}
                }
            }";

            var project3Json = @"
            {
                ""version"": ""1.0.0"",
                ""dependencies"": {
                },
                ""frameworks"": {
                    ""net45"": {}
                }
            }";

            using (var packagesDir = TestDirectory.Create())
                using (var workingDir = TestDirectory.Create())
                {
                    var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                    var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                    var project3 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project3"));
                    project1.Create();
                    project2.Create();
                    project3.Create();

                    File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                    File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);
                    File.WriteAllText(Path.Combine(project3.FullName, "project.json"), project3Json);

                    var project1Path = Path.Combine(project1.FullName, "project1.csproj");
                    var project2Path = Path.Combine(project2.FullName, "project2.csproj");
                    var project3Path = Path.Combine(project3.FullName, "project3.csproj");

                    File.WriteAllText(project1Path, string.Empty);
                    File.WriteAllText(project2Path, string.Empty);
                    File.WriteAllText(project3Path, string.Empty);

                    var specPath1 = Path.Combine(project1.FullName, "project.json");
                    var specPath2 = Path.Combine(project2.FullName, "project.json");
                    var specPath3 = Path.Combine(project3.FullName, "project.json");

                    var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                    var spec2 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project2", specPath2);
                    var spec3 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project3", specPath3);

                    var logger = new TestLogger();

                    var restoreContext = new RestoreArgs()
                    {
                        GlobalPackagesFolder = packagesDir,
                        Log          = logger,
                        CacheContext = new SourceCacheContext()
                    };

                    // Modify specs for netcore
                    spec3          = spec3.WithTestRestoreMetadata();
                    spec3.FilePath = project3Path;
                    spec3.RestoreMetadata.ProjectPath       = project3Path;
                    spec3.RestoreMetadata.ProjectUniqueName = project3Path;

                    spec2          = spec2.WithTestRestoreMetadata().WithTestProjectReference(spec3);
                    spec2.FilePath = project2Path;
                    spec2.RestoreMetadata.ProjectPath       = project2Path;
                    spec2.RestoreMetadata.ProjectUniqueName = project2Path;

                    spec1          = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2);
                    spec1.FilePath = project1Path;
                    spec1.RestoreMetadata.ProjectPath       = project1Path;
                    spec1.RestoreMetadata.ProjectUniqueName = project1Path;

                    var request = await ProjectJsonTestHelpers.GetRequestAsync(restoreContext, spec1, spec2, spec3);

                    request.LockFilePath = Path.Combine(project1.FullName, "project.assets.json");
                    var format = new LockFileFormat();

                    // Act
                    var command = new RestoreCommand(request);
                    var result  = await command.ExecuteAsync();

                    await result.CommitAsync(logger, CancellationToken.None);

                    Assert.True(result.Success, logger.ShowMessages());

                    var lockFile = format.Read(request.LockFilePath, logger);

                    var project1Lib = lockFile.GetLibrary("project1", NuGetVersion.Parse("1.0.0"));
                    var project2Lib = lockFile.GetLibrary("project2", NuGetVersion.Parse("1.0.0"));
                    var project3Lib = lockFile.GetLibrary("project3", NuGetVersion.Parse("1.0.0"));

                    var project2Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null)
                                         .Libraries
                                         .Where(lib => lib.Name == "project2")
                                         .Single();

                    var project3Target = lockFile.GetTarget(FrameworkConstants.CommonFrameworks.Net45, runtimeIdentifier: null)
                                         .Libraries
                                         .Where(lib => lib.Name == "project3")
                                         .Single();

                    // Assert
                    Assert.True(result.Success);
                    Assert.Equal(2, lockFile.Libraries.Count);

                    Assert.Equal("project", project2Lib.Type);
                    Assert.Equal("project", project3Lib.Type);

                    Assert.Equal("../project2/project2.csproj", project2Lib.Path);
                    Assert.Equal("../project3/project3.csproj", project3Lib.Path);

                    Assert.Equal("../project2/project2.csproj", project2Lib.MSBuildProject);
                    Assert.Equal("../project3/project3.csproj", project3Lib.MSBuildProject);

                    Assert.Equal(1, project2Target.Dependencies.Count);
                    Assert.Equal("project3", project2Target.Dependencies.Single().Id);
                    Assert.Equal("1.0.0", project2Target.Dependencies.Single().VersionRange.ToLegacyShortString());

                    Assert.Equal(0, project3Target.Dependencies.Count);

                    Assert.Equal(".NETFramework,Version=v4.5", project2Target.Framework);
                    Assert.Equal(".NETFramework,Version=v4.5", project3Target.Framework);
                }
        }
Esempio n. 27
0
        public async Task RestoreRunner_BasicRestore_VerifyFailureWritesFiles()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                    ""dependencies"": {
                        ""x"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger   = new TestLogger();
                var lockPath = Path.Combine(project1.FullName, "project.lock.json");

                var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList();

                var packageX = new SimpleTestPackageContext()
                {
                    Id      = "x",
                    Version = "1.0.0"
                };

                packageX.AddFile("build/net45/x.targets");

                var packageY = new SimpleTestPackageContext("y");
                packageX.Dependencies.Add(packageY);

                var yPath = SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageY);
                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageX);

                // y does not exist
                yPath.Delete();

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = packagesDir.FullName,
                        Sources = new List <string>()
                        {
                            packageSource.FullName
                        },
                        Inputs = new List <string>()
                        {
                            specPath1
                        },
                        Log = logger,
                        CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(sources)),
                        RequestProviders      = new List <IRestoreRequestProvider>()
                        {
                            new ProjectJsonRestoreRequestProvider(providerCache)
                        }
                    };

                    var targetsPath = Path.Combine(project1.FullName, "project1.nuget.targets");
                    var propsPath   = Path.Combine(project1.FullName, "project1.nuget.props");

                    // Act
                    var summaries = await RestoreRunner.Run(restoreContext);

                    var summary = summaries.Single();

                    var targets = TargetsUtility.GetMSBuildPackageImports(targetsPath);

                    // Assert
                    Assert.False(summary.Success);
                    Assert.True(File.Exists(lockPath), lockPath);
                    Assert.True(File.Exists(targetsPath));
                    Assert.False(File.Exists(propsPath));
                    Assert.Equal(1, targets.Count);
                }
            }
        }
        public async Task ProjectResolution_ProjectReferenceWithInCompatibleTFMNoRange()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project2Json = @"
            {
              ""version"": ""2.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net46"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(project2.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);

                var logger = new TestLogger();

                var restoreContext = new RestoreArgs()
                {
                    Sources = new List <string>()
                    {
                        packageSource.FullName
                    },
                    GlobalPackagesFolder = packagesDir.FullName,
                    Log          = logger,
                    CacheContext = new SourceCacheContext()
                };

                // Modify specs for netcore
                spec2 = spec2.WithTestRestoreMetadata();
                spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2);

                var request = await ProjectJsonTestHelpers.GetRequestAsync(restoreContext, spec1, spec2);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                // Act
                var command = new RestoreCommand(request);
                var result  = await command.ExecuteAsync();

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var issue = result.CompatibilityCheckResults.SelectMany(ccr => ccr.Issues).Single();

                // Assert
                Assert.False(result.Success);
                Assert.Equal(0, result.GetAllUnresolved().Count);
                Assert.Equal("Project project2 is not compatible with net45 (.NETFramework,Version=v4.5). Project project2 supports: net46 (.NETFramework,Version=v4.6)", issue.Format());
                Assert.Equal(1, logger.ErrorMessages.Count());

                Assert.Contains("Project project2 is not compatible with net45 (.NETFramework,Version=v4.5). Project project2 supports: net46 (.NETFramework,Version=v4.6)", logger.ErrorMessages.Last());
            }
        }
Esempio n. 29
0
        public async Task RestoreRunner_BasicRestore_VerifyFailureWritesFiles_NETCore()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                    ""dependencies"": {
                        ""x"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                spec1.RestoreMetadata                   = new ProjectRestoreMetadata();
                spec1.RestoreMetadata.OutputPath        = Path.Combine(project1.FullName, "obj");
                spec1.RestoreMetadata.ProjectStyle      = ProjectStyle.PackageReference;
                spec1.RestoreMetadata.ProjectName       = "project1";
                spec1.RestoreMetadata.ProjectPath       = Path.Combine(project1.FullName, "project1.csproj");
                spec1.RestoreMetadata.ProjectUniqueName = spec1.RestoreMetadata.ProjectPath;
                spec1.RestoreMetadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45")));
                spec1.RestoreMetadata.OriginalTargetFrameworks.Add("net45");
                spec1.FilePath = spec1.RestoreMetadata.ProjectPath;

                var dgSpec = new DependencyGraphSpec();
                dgSpec.AddProject(spec1);
                dgSpec.AddRestore(spec1.RestoreMetadata.ProjectUniqueName);

                var logger     = new TestLogger();
                var assetsPath = Path.Combine(project1.FullName, "obj", "project.assets.json");

                var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList();

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = packagesDir.FullName,
                        Sources = new List <string>()
                        {
                            packageSource.FullName
                        },
                        Log = logger,
                        CachingSourceProvider     = new CachingSourceProvider(new TestPackageSourceProvider(sources)),
                        PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                        {
                            new DependencyGraphSpecRequestProvider(providerCache, dgSpec)
                        }
                    };

                    // Act
                    var summaries = await RestoreRunner.Run(restoreContext);

                    var summary = summaries.Single();

                    // Assert
                    Assert.False(summary.Success);
                    Assert.True(File.Exists(assetsPath), assetsPath);
                    Assert.True(File.Exists(Path.Combine(project1.FullName, "obj", "project1.csproj.nuget.g.props")));
                    Assert.True(File.Exists(Path.Combine(project1.FullName, "obj", "project1.csproj.nuget.g.targets")));
                }
            }
        }
Esempio n. 30
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();
                }
        }
Esempio n. 31
0
        public async Task RestoreRunner_BasicRestoreWithConfigFile()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var configFile = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <packageSources>
        <add key=""nuget.org"" value=""{0}"" />
    </packageSources>
</configuration>
";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(workingDir, "NuGet.Config"), String.Format(configFile, packageSource.FullName));

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var configPath = Path.Combine(workingDir, "NuGet.Config");

                var logger   = new TestLogger();
                var lockPath = Path.Combine(project1.FullName, "project.lock.json");

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = packagesDir.FullName,
                        ConfigFile           = configPath,
                        Inputs = new List <string>()
                        {
                            specPath1
                        },
                        Log = logger,
                        CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(new List <PackageSource>())),
                        RequestProviders      = new List <IRestoreRequestProvider>()
                        {
                            new ProjectJsonRestoreRequestProvider(providerCache)
                        }
                    };

                    // Act
                    var summaries = await RestoreRunner.Run(restoreContext);

                    var summary = summaries.Single();

                    // Assert
                    Assert.True(summary.Success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                    Assert.Equal(1, summary.FeedsUsed.Count);
                    Assert.True(File.Exists(lockPath), lockPath);
                }
            }
        }