/// <summary> /// Write the dg file to a temp location if NUGET_PERSIST_DG. /// </summary> /// <remarks>This is a noop if NUGET_PERSIST_DG is not set to true.</remarks> public static void PersistDGFileIfDebugging(DependencyGraphSpec spec, ILogger log) { if (_isPersistDGSet.Value) { string path; var envPath = Environment.GetEnvironmentVariable("NUGET_PERSIST_DG_PATH"); if (!string.IsNullOrEmpty(envPath)) { path = envPath; Directory.CreateDirectory(Path.GetDirectoryName(path)); } else { path = Path.Combine( NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "nuget-dg", $"{Guid.NewGuid()}.dg"); DirectoryUtility.CreateSharedDirectory(Path.GetDirectoryName(path)); } log.LogMinimal( string.Format( CultureInfo.CurrentCulture, Strings.PersistDGFile, path)); spec.Save(path); } }
/// <summary> /// Write the dg file to a temp location if NUGET_PERSIST_NOOP_DG. /// </summary> /// <remarks>This is a noop if NUGET_PERSIST_NOOP_DG is not set to true.</remarks> private static void PersistHashedDGFileIfDebugging(DependencyGraphSpec spec, ILogger log) { if (_isPersistDGSet.Value) { string path; var envPath = Environment.GetEnvironmentVariable("NUGET_PERSIST_NOOP_DG_PATH"); if (!string.IsNullOrEmpty(envPath)) { path = envPath; Directory.CreateDirectory(Path.GetDirectoryName(path)); } else { path = Path.Combine( NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "nuget-dg", $"{spec.GetProjectSpec(spec.Restore.FirstOrDefault()).RestoreMetadata.ProjectName}-{DateTime.Now.ToString("yyyyMMddHHmmss")}.dg"); DirectoryUtility.CreateSharedDirectory(Path.GetDirectoryName(path)); } log.LogMinimal($"Persisting no-op dg to {path}"); spec.Save(path); } }
public async Task RestoreBuildTargetsAndProps_VerifyRestoreNoop() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec = GetProject("projectA", "net462", "netstandard1.6"); spec.RestoreMetadata.CrossTargeting = true; spec.Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("x", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); // Create fake projects, the real data is in the specs var projects = CreateProjectsFromSpecs(pathContext, spec); // Create dg file var dgFile = new DependencyGraphSpec(); dgFile.AddProject(spec); dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.AddFile("build/x.targets"); packageX.AddFile("build/x.props"); packageX.AddFile("contentFiles/any/any/_._"); SimpleTestPackageUtility.CreatePackages(pathContext.PackageSource, packageX); var project = projects[0]; // First restore var summaries = await RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); // Act var secondLogger = new TestLogger(); summaries = await RunRestore(pathContext, secondLogger, sources, dgFile, cacheContext); success = summaries.All(s => s.Success); var messages = string.Join(Environment.NewLine, secondLogger.Messages); Assert.True(success, "Failed: " + messages); // Verify the file was not rewritten Assert.DoesNotContain("Generating MSBuild file", messages); } }
public async Task RestoreBuildTargetsAndProps_VerifyPropsAndTargetsGeneratedWithNoTFMConditions() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec = GetProject("projectA", "net462"); spec.RestoreMetadata.CrossTargeting = false; spec.Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("x", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); // Create fake projects, the real data is in the specs var projects = CreateProjectsFromSpecs(pathContext, spec); // Create dg file var dgFile = new DependencyGraphSpec(); dgFile.AddProject(spec); dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.AddFile("build/x.targets"); packageX.AddFile("build/x.props"); packageX.AddFile("contentFiles/any/any/_._"); SimpleTestPackageUtility.CreatePackages(pathContext.PackageSource, packageX); var project = projects[0]; // Act var summaries = await RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); var targetsXML = XDocument.Parse(File.ReadAllText(project.TargetsOutput)); var targetItemGroups = targetsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList(); var propsXML = XDocument.Parse(File.ReadAllText(project.PropsOutput)); var propsItemGroups = propsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList(); Assert.Equal("'$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); Assert.Equal("'$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); } }
public async Task ContentFilesMSBuild_VerifyConditionForContentItemGroupWithoutCrossTargeting(string file, string expected) { // 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"); packageA.AddFile(file); SimpleTestPackageUtility.CreatePackages(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")); // Act var result = (await NETCoreRestoreTestUtility.RunRestore( pathContext, logger, new List <PackageSource>() { new PackageSource(pathContext.PackageSource) }, dgFile, cacheContext)).Single(); var props = XDocument.Load(project.PropsOutput); var itemGroups = props.Root.Elements(XName.Get("ItemGroup", "http://schemas.microsoft.com/developer/msbuild/2003")).ToArray(); // Assert Assert.True(result.Success, logger.ShowErrors()); Assert.Equal(1, itemGroups.Length); Assert.EndsWith("x.txt", Path.GetFileName(itemGroups[0].Elements().Single().Attribute(XName.Get("Include")).Value)); Assert.Equal(expected.Trim(), itemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); } }
public async Task NETCoreProject2Project_VerifyLibFilesUnderCompile(string path, string expected) { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6"); var spec2 = NETCoreRestoreTestUtility.GetProject(projectName: "projectB", framework: "netstandard1.3"); var specs = new[] { spec1, spec2 }; // Create fake projects, the real data is in the specs var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs); // Link projects spec1.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[1].ProjectPath, ProjectUniqueName = spec2.RestoreMetadata.ProjectUniqueName, }); var projectDir = Path.GetDirectoryName(spec2.RestoreMetadata.ProjectPath); var absolutePath = Path.Combine(projectDir, "bin", "debug", "b.dll"); spec2.RestoreMetadata.Files.Add(new ProjectRestoreMetadataFile(path, Path.Combine(projectDir, absolutePath))); // Create dg file var dgFile = new DependencyGraphSpec(); dgFile.AddProject(spec1); dgFile.AddProject(spec2); dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); var lockFormat = new LockFileFormat(); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); var assetsFile = lockFormat.Read(Path.Combine(spec1.RestoreMetadata.OutputPath, LockFileFormat.AssetsFileName)); var projectBTarget = assetsFile.Targets.Single().Libraries.Single(e => e.Type == "project"); // Verify compile and runtime Assert.Equal(expected, string.Join("|", projectBTarget.CompileTimeAssemblies.Select(e => e.Path))); Assert.Equal(expected, string.Join("|", projectBTarget.RuntimeAssemblies.Select(e => e.Path))); } }
public async Task ContentFilesMSBuild_VerifyNoContentItemsForEmptyFolderAsync() { // 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"); packageA.AddFile("contentFiles/any/any/_._"); packageA.AddFile("contentFiles/cs/net45/_._"); packageA.AddFile("contentFiles/cs/any/_._"); 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")); // Act var result = (await NETCoreRestoreTestUtility.RunRestore( pathContext, logger, new List <PackageSource>() { new PackageSource(pathContext.PackageSource) }, dgFile, cacheContext)).Single(); var props = XDocument.Load(project.PropsOutput); var itemGroups = props.Root.Elements(XName.Get("ItemGroup", "http://schemas.microsoft.com/developer/msbuild/2003")).ToArray(); // Assert Assert.True(result.Success, logger.ShowErrors()); Assert.Equal(1, itemGroups.Length); // The SourceRoot is the only expected item group. } }
public static string CreateDGFileForProject(SimpleTestProjectContext project) { var dgSpec = new DependencyGraphSpec(); var dgFilePath = Path.Combine(Directory.GetParent(project.ProjectPath).FullName, "temp.dg"); dgSpec.AddRestore(project.ProjectName); dgSpec.AddProject(project.PackageSpec); dgSpec.Save(dgFilePath); return(dgFilePath); }
public async Task Cycle_TransitiveProjectWithSameNameAsPackageVerifyCycleDetectedAsync(string packageId) { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource> { new PackageSource(pathContext.PackageSource) }; var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6"); var spec2 = NETCoreRestoreTestUtility.GetProject(projectName: "projectB", framework: "netstandard1.6"); spec2.TargetFrameworks[0].Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange(packageId, VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); var specs = new[] { spec1, spec2 }; var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs); // Link projects spec1.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[1].ProjectPath, ProjectUniqueName = spec2.RestoreMetadata.ProjectUniqueName, }); await SimpleTestPackageUtility.CreateFolderFeedV2Async(pathContext.PackageSource, new PackageIdentity("projectA", NuGetVersion.Parse("1.0.0"))); await SimpleTestPackageUtility.CreateFolderFeedV2Async(pathContext.PackageSource, new PackageIdentity("projectB", NuGetVersion.Parse("1.0.0"))); // Create dg file var dgFile = new DependencyGraphSpec(); // Only add projectA dgFile.AddProject(spec1); dgFile.AddProject(spec2); dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.False(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); Assert.Contains("Cycle detected", string.Join(Environment.NewLine, logger.ErrorMessages)); } }
private async Task CommitDgSpecFileAsync(ILogger log, bool toolCommit) { if (!toolCommit && _dependencyGraphSpecFilePath != null && _dependencyGraphSpec != null) { log.LogVerbose($"Persisting dg to {_dependencyGraphSpecFilePath}"); await FileUtility.ReplaceWithLock( (outputPath) => _dependencyGraphSpec.Save(outputPath), _dependencyGraphSpecFilePath); } }
private static string GetJson(DependencyGraphSpec dgSpec) { using (TestDirectory testDirectory = TestDirectory.Create()) { string filePath = Path.Combine(testDirectory.Path, "out.json"); dgSpec.Save(filePath); return(File.ReadAllText(filePath)); } }
public async Task Cycle_PackageCircularDependencyVerifyCycleDetected() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource> { new PackageSource(pathContext.PackageSource) }; var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6"); spec1.TargetFrameworks[0].Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("X", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); var specs = new[] { spec1 }; // Create fake projects, the real data is in the specs var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs); var packageX = new SimpleTestPackageContext("x", "1.0.0"); var packageY = new SimpleTestPackageContext("y", "1.0.0"); var packageZ = new SimpleTestPackageContext("z", "1.0.0"); // X -> Y -> Z -> X packageX.Dependencies.Add(packageY); packageY.Dependencies.Add(packageZ); packageZ.Dependencies.Add(packageX); await SimpleTestPackageUtility.CreateFolderFeedV3(pathContext.PackageSource, packageX, packageY, packageZ); // Create dg file var dgFile = new DependencyGraphSpec(); // Only add projectA dgFile.AddProject(spec1); dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.False(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); Assert.Contains("Cycle detected", string.Join(Environment.NewLine, logger.ErrorMessages)); } }
private static void PersistDGSpecFile(DependencyGraphSpec spec, RestoreRequest request, ILogger log) { var dgPath = GetPersistedDGSpecFilePath(request); if (dgPath == null) { return; } DirectoryUtility.CreateSharedDirectory(Path.GetDirectoryName(dgPath)); log.LogMinimal($"Persisting no-op dg to {dgPath}"); spec.Save(dgPath); }
public async Task NETCoreProject2Project_ProjectReference_IgnoredForTFM() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6"); var spec2 = NETCoreRestoreTestUtility.GetProject(projectName: "projectB", framework: "netstandard1.3"); var specs = new[] { spec1, spec2 }; // Create fake projects, the real data is in the specs var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs); // Remove valid link spec1.RestoreMetadata.TargetFrameworks.Clear(); // Add invalid link, net45 is not a project tfm spec1.RestoreMetadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45"))); spec1.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[1].ProjectPath, ProjectUniqueName = spec2.RestoreMetadata.ProjectUniqueName }); // Create dg file var dgFile = new DependencyGraphSpec(); foreach (var spec in specs) { dgFile.AddProject(spec); } // Restore only the first one dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); Assert.Equal(0, projects[0].AssetsFile.Libraries.Count); } }
public async Task NETCoreProject2Project_ProjectMissing() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6"); var spec2 = NETCoreRestoreTestUtility.GetProject(projectName: "projectB", framework: "netstandard1.3"); var specs = new[] { spec1, spec2 }; // Create fake projects, the real data is in the specs var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs); // Link projects spec1.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[1].ProjectPath, ProjectUniqueName = spec2.RestoreMetadata.ProjectUniqueName, }); // Create dg file var dgFile = new DependencyGraphSpec(); // Only add projectA dgFile.AddProject(spec1); dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.False(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); Assert.Contains("Unable to find project", string.Join(Environment.NewLine, logger.Messages)); Assert.Contains(projects[1].ProjectPath, string.Join(Environment.NewLine, logger.Messages)); } }
private static async Task PersistDGSpec(DependencyGraphSpec dgSpec) { try { var filePath = GetDefaultDGSpecFileName(); // create nuget temp folder if not exists DirectoryUtility.CreateSharedDirectory(Path.GetDirectoryName(filePath)); // delete existing dg spec file (if exists) then replace it with new file. await FileUtility.ReplaceWithLock( (tempFile) => dgSpec.Save(tempFile), filePath); } catch (Exception) { //ignore any failure if it fails to write or replace dg spec file. } }
private void DumpProjectRestoreInfo(string projectUniqueName, DependencyGraphSpec projectRestoreInfo) { try { var packageSpec = projectRestoreInfo.GetProjectSpec(projectUniqueName); var outputPath = packageSpec.RestoreMetadata.OutputPath; if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } var dgPath = Path.Combine(outputPath, $"{Guid.NewGuid()}.dg"); projectRestoreInfo.Save(dgPath); } catch (Exception e) { _logger.LogError(e.ToString()); } }
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 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(); } }
public async Task NETCoreProject2Project_VerifyCompileForTransitiveSettings(string expected, bool ab, bool bc, bool cd, bool ax, bool xy, bool yd) { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "A", framework: "netstandard1.6"); var spec2 = NETCoreRestoreTestUtility.GetProject(projectName: "B", framework: "netstandard1.6"); var spec3 = NETCoreRestoreTestUtility.GetProject(projectName: "C", framework: "netstandard1.6"); var spec4 = NETCoreRestoreTestUtility.GetProject(projectName: "D", framework: "netstandard1.6"); var spec5 = NETCoreRestoreTestUtility.GetProject(projectName: "X", framework: "netstandard1.6"); var spec6 = NETCoreRestoreTestUtility.GetProject(projectName: "Y", framework: "netstandard1.6"); var specs = new[] { spec1, spec2, spec3, spec4, spec5, spec6, }; // Create fake projects, the real data is in the specs var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs); // Link projects // A -> B spec1.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[1].ProjectPath, ProjectUniqueName = spec2.RestoreMetadata.ProjectUniqueName, PrivateAssets = ab ? LibraryIncludeFlags.None : LibraryIncludeFlags.Compile }); // B -> C spec2.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[2].ProjectPath, ProjectUniqueName = spec3.RestoreMetadata.ProjectUniqueName, PrivateAssets = bc ? LibraryIncludeFlags.None : LibraryIncludeFlags.Compile }); // C -> D spec3.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[3].ProjectPath, ProjectUniqueName = spec4.RestoreMetadata.ProjectUniqueName, PrivateAssets = cd ? LibraryIncludeFlags.None : LibraryIncludeFlags.Compile }); // A -> X spec1.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[4].ProjectPath, ProjectUniqueName = spec5.RestoreMetadata.ProjectUniqueName, PrivateAssets = ax ? LibraryIncludeFlags.None : LibraryIncludeFlags.Compile }); // X -> Y spec5.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[5].ProjectPath, ProjectUniqueName = spec6.RestoreMetadata.ProjectUniqueName, PrivateAssets = xy ? LibraryIncludeFlags.None : LibraryIncludeFlags.Compile }); // Y -> D spec6.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[3].ProjectPath, ProjectUniqueName = spec4.RestoreMetadata.ProjectUniqueName, PrivateAssets = yd ? LibraryIncludeFlags.None : LibraryIncludeFlags.Compile }); // Create dg file var dgFile = new DependencyGraphSpec(); foreach (var spec in specs) { dgFile.AddProject(spec); var projectDir = Path.GetDirectoryName(spec.RestoreMetadata.ProjectPath); var absolutePath = Path.Combine(projectDir, "bin", "debug", "a.dll"); spec.RestoreMetadata.Files.Add(new ProjectRestoreMetadataFile("lib/netstandard1.6/a.dll", Path.Combine(projectDir, absolutePath))); } dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); var lockFormat = new LockFileFormat(); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); var assetsFile = lockFormat.Read(Path.Combine(spec1.RestoreMetadata.OutputPath, LockFileFormat.AssetsFileName)); // Find all non _._ compile assets var flowingCompile = assetsFile.Targets.Single().Libraries .Where(e => e.Type == "project") .Where(e => e.CompileTimeAssemblies.Where(f => !f.Path.EndsWith("_._")).Any()) .Select(e => e.Name) .OrderBy(s => s, StringComparer.OrdinalIgnoreCase); Assert.Equal(expected, string.Join("", flowingCompile)); // Runtime should always flow var flowingRuntime = assetsFile.Targets.Single().Libraries .Where(e => e.Type == "project") .Where(e => e.RuntimeAssemblies.Where(f => !f.Path.EndsWith("_._")).Any()) .Select(e => e.Name) .OrderBy(s => s, StringComparer.OrdinalIgnoreCase); Assert.Equal("BCDXY", string.Join("", flowingRuntime)); } }
public async Task NETCoreProject2Project_IgnoreXproj() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6"); var specs = new[] { spec }; spec.TargetFrameworks.Single().Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("x", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); // Create fake projects, the real data is in the specs var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, spec); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageX.Dependencies.Add(packageY); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); // Create dg file var dgFile = new DependencyGraphSpec(); // Only add projectA dgFile.AddProject(spec); dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); var projectYRoot = Path.Combine(pathContext.SolutionRoot, "y"); Directory.CreateDirectory(projectYRoot); var projectYJson = Path.Combine(projectYRoot, "project.json"); var projectJsonContent = JObject.Parse(@"{ 'dependencies': { }, 'frameworks': { 'netstandard1.0': { } } }"); File.WriteAllText(projectYJson, projectJsonContent.ToString()); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); // Verify only packages Assert.Empty(projects[0].AssetsFile.Libraries.Where(e => e.Type != "package")); } }
/// <summary> /// Persists the dg file for the given restore request. /// This does not do a dirty check! /// </summary> /// <param name="spec">spec</param> /// <param name="dgPath">the dg path</param> /// <param name="log">logger</param> internal static void PersistDGSpecFile(DependencyGraphSpec spec, string dgPath, ILogger log) { Directory.CreateDirectory(Path.GetDirectoryName(dgPath)); log.LogVerbose($"Persisting no-op dg to {dgPath}"); spec.Save(dgPath); }
public async Task NETCoreProject2Project_ProjectReferenceOnlyUnderRestoreMetadata() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6"); var spec2 = NETCoreRestoreTestUtility.GetProject(projectName: "projectB", framework: "netstandard1.3"); var specs = new[] { spec1, spec2 }; // Create fake projects, the real data is in the specs var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs); // Link projects spec1.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[1].ProjectPath, ProjectUniqueName = spec2.RestoreMetadata.ProjectUniqueName, }); // Create dg file var dgFile = new DependencyGraphSpec(); foreach (var spec in specs) { dgFile.AddProject(spec); } // Restore only the first one dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); var targetLib = projects[0].AssetsFile .Targets .Single(e => e.TargetFramework.Equals(NuGetFramework.Parse("netstandard1.6"))) .Libraries .Single(e => e.Name == "projectB"); var libraryLib = projects[0].AssetsFile .Libraries .Single(e => e.Name == "projectB"); Assert.Equal("projectB", targetLib.Name); Assert.Equal(NuGetFramework.Parse("netstandard1.3"), NuGetFramework.Parse(targetLib.Framework)); Assert.Equal("1.0.0", targetLib.Version.ToNormalizedString()); Assert.Equal("project", targetLib.Type); Assert.Equal("projectB", libraryLib.Name); Assert.Equal("project", libraryLib.Type); Assert.Equal("../projectB/projectB.csproj", libraryLib.MSBuildProject); Assert.Equal("../projectB/projectB.csproj", libraryLib.Path); Assert.Equal("1.0.0", libraryLib.Version.ToNormalizedString()); } }
public async Task NETCoreProject2Project_ProjectFileDependencyGroupsForNETCore() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6"); var spec2 = NETCoreRestoreTestUtility.GetProject(projectName: "projectB", framework: "netstandard1.3"); var spec3 = NETCoreRestoreTestUtility.GetProject(projectName: "projectC", framework: "netstandard1.0"); var specs = new[] { spec1, spec2, spec3 }; // Create fake projects, the real data is in the specs var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs); // Link projects spec1.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[1].ProjectPath, ProjectUniqueName = spec2.RestoreMetadata.ProjectUniqueName, }); spec2.RestoreMetadata.TargetFrameworks.Single().ProjectReferences.Add(new ProjectRestoreReference() { ProjectPath = projects[2].ProjectPath, ProjectUniqueName = spec3.RestoreMetadata.ProjectUniqueName, }); // Create dg file var dgFile = new DependencyGraphSpec(); foreach (var spec in specs) { dgFile.AddProject(spec); } // Restore only the first one dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); // Act var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); var dependencies = projects[0].AssetsFile.ProjectFileDependencyGroups.SelectMany(e => e.Dependencies).ToArray(); // Ensure ProjectC does not show up Assert.Equal(1, dependencies.Length); // Ensure ProjectC is in the libraries Assert.Equal(2, projects[0].AssetsFile.Libraries.Count); // Verify the project name is used not the path or unique name Assert.Equal("projectB >= 1.0.0", dependencies[0]); } }