public async Task BuildIntegratedNuGetProject_IsRestoreRequiredMissingPackage() { // Arrange var projectName = "testproj"; using (var solutionManager = new TestSolutionManager(false)) { var projectFolder = new DirectoryInfo(Path.Combine(solutionManager.SolutionDirectory, projectName)); projectFolder.Create(); var projectConfig = new FileInfo(Path.Combine(projectFolder.FullName, "project.json")); var msbuildProjectPath = new FileInfo(Path.Combine(projectFolder.FullName, $"{projectName}.csproj")); BuildIntegrationTestUtility.CreateConfigJson(projectConfig.FullName); var json = JObject.Parse(File.ReadAllText(projectConfig.FullName)); JsonConfigUtility.AddDependency(json, new NuGet.Packaging.Core.PackageDependency("nuget.versioning", VersionRange.Parse("1.0.7"))); using (var writer = new StreamWriter(projectConfig.FullName)) { writer.Write(json.ToString()); } var sources = new List <SourceRepository> { }; var projectTargetFramework = NuGetFramework.Parse("uap10.0"); var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext()); var project = new ProjectJsonNuGetProject(projectConfig.FullName, msbuildProjectPath.FullName); solutionManager.NuGetProjects.Add(project); var testLogger = new TestLogger(); var settings = Settings.LoadSpecificSettings(solutionManager.SolutionDirectory, "NuGet.Config"); var restoreContext = new DependencyGraphCacheContext(testLogger, settings); var providersCache = new RestoreCommandProvidersCache(); await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, providersCache, (c) => { }, sources, Guid.Empty, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), testLogger, CancellationToken.None); var noOpRestoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, providersCache, (c) => { }, sources, Guid.Empty, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), testLogger, CancellationToken.None); foreach (var restoreSummary in noOpRestoreSummaries) { Assert.True(restoreSummary.NoOpRestore); } var resolver = new VersionFolderPathResolver(solutionManager.GlobalPackagesFolder); var pathToDelete = resolver.GetInstallPath("nuget.versioning", NuGetVersion.Parse("1.0.7")); TestFileSystemUtility.DeleteRandomTestFolder(pathToDelete); var restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, new RestoreCommandProvidersCache(), (c) => { }, sources, Guid.Empty, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), testLogger, CancellationToken.None); foreach (var restoreSummary in restoreSummaries) { Assert.True(restoreSummary.Success); Assert.False(restoreSummary.NoOpRestore); } } }
private static void PopulateDependencies( string packageSpecPath, IList <LibraryDependency> results, JObject settings, string propertyName, bool isGacOrFrameworkReference) { var dependencies = settings[propertyName] as JObject; if (dependencies != null) { foreach (var dependency in dependencies) { if (string.IsNullOrEmpty(dependency.Key)) { throw FileFormatException.Create( "Unable to resolve dependency ''.", dependency.Value, packageSpecPath); } // Support // "dependencies" : { // "Name" : "1.0" // } var dependencyValue = dependency.Value; var dependencyTypeValue = LibraryDependencyType.Default; var dependencyIncludeFlagsValue = LibraryIncludeFlags.All; var dependencyExcludeFlagsValue = LibraryIncludeFlags.None; var suppressParentFlagsValue = LibraryIncludeFlagUtils.DefaultSuppressParent; var noWarn = new List <NuGetLogCode>(); // This method handles both the dependencies and framework assembly sections. // Framework references should be limited to references. // Dependencies should allow everything but framework references. var targetFlagsValue = isGacOrFrameworkReference ? LibraryDependencyTarget.Reference : LibraryDependencyTarget.All & ~LibraryDependencyTarget.Reference; var autoReferenced = false; var generatePathProperty = false; string dependencyVersionValue = null; var dependencyVersionToken = dependencyValue; if (dependencyValue.Type == JTokenType.String) { dependencyVersionValue = dependencyValue.Value <string>(); } else { if (dependencyValue.Type == JTokenType.Object) { dependencyVersionToken = dependencyValue["version"]; if (dependencyVersionToken != null && dependencyVersionToken.Type == JTokenType.String) { dependencyVersionValue = dependencyVersionToken.Value <string>(); } } IEnumerable <string> strings; if (TryGetStringEnumerable(dependencyValue["type"], out strings)) { dependencyTypeValue = LibraryDependencyType.Parse(strings); // Types are used at pack time, they should be translated to suppressParent to // provide a matching effect for project to project references. // This should be set before suppressParent is checked. if (!dependencyTypeValue.Contains(LibraryDependencyTypeFlag.BecomesNupkgDependency)) { suppressParentFlagsValue = LibraryIncludeFlags.All; } else if (dependencyTypeValue.Contains(LibraryDependencyTypeFlag.SharedFramework)) { dependencyIncludeFlagsValue = LibraryIncludeFlags.Build | LibraryIncludeFlags.Compile | LibraryIncludeFlags.Analyzers; } } if (TryGetStringEnumerable(dependencyValue["include"], out strings)) { dependencyIncludeFlagsValue = LibraryIncludeFlagUtils.GetFlags(strings); } if (TryGetStringEnumerable(dependencyValue["exclude"], out strings)) { dependencyExcludeFlagsValue = LibraryIncludeFlagUtils.GetFlags(strings); } if (TryGetStringEnumerable(dependencyValue["suppressParent"], out strings)) { // This overrides any settings that came from the type property. suppressParentFlagsValue = LibraryIncludeFlagUtils.GetFlags(strings); } noWarn = GetNuGetLogCodeEnumerableFromJArray(dependencyValue["noWarn"]) .ToList(); var targetToken = dependencyValue["target"]; if (targetToken != null) { var targetString = targetToken.Value <string>(); targetFlagsValue = LibraryDependencyTargetUtils.Parse(targetString); // Verify that the value specified is package, project, or external project if (!ValidateDependencyTarget(targetFlagsValue)) { var message = string.Format( CultureInfo.CurrentCulture, Strings.InvalidDependencyTarget, targetString); throw FileFormatException.Create(message, targetToken, packageSpecPath); } } autoReferenced = GetBoolOrFalse(dependencyValue, "autoReferenced", packageSpecPath); generatePathProperty = GetBoolOrFalse(dependencyValue, "generatePathProperty", packageSpecPath); } VersionRange dependencyVersionRange = null; if (!string.IsNullOrEmpty(dependencyVersionValue)) { try { dependencyVersionRange = VersionRange.Parse(dependencyVersionValue); } catch (Exception ex) { throw FileFormatException.Create( ex, dependencyVersionToken, packageSpecPath); } } // Projects and References may have empty version ranges, Packages may not if (dependencyVersionRange == null) { if ((targetFlagsValue & LibraryDependencyTarget.Package) == LibraryDependencyTarget.Package) { throw FileFormatException.Create( new ArgumentException(Strings.MissingVersionOnDependency), dependency.Value, packageSpecPath); } else { // Projects and references with no version property allow all versions dependencyVersionRange = VersionRange.All; } } // the dependency flags are: Include flags - Exclude flags var includeFlags = dependencyIncludeFlagsValue & ~dependencyExcludeFlagsValue; results.Add(new LibraryDependency() { LibraryRange = new LibraryRange() { Name = dependency.Key, TypeConstraint = targetFlagsValue, VersionRange = dependencyVersionRange, }, Type = dependencyTypeValue, IncludeType = includeFlags, SuppressParent = suppressParentFlagsValue, AutoReferenced = autoReferenced, NoWarn = noWarn.ToList(), GeneratePathProperty = generatePathProperty }); } } }
public async Task RestoreBuildTargetsAndProps_VerifyPropsAndTargetsGeneratedAsync() { // 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 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/_._"); await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageX); var project = projects[0]; // Act var summaries = await RunRestoreAsync(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("'$(TargetFramework)' == 'net462' AND '$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); Assert.Equal("'$(TargetFramework)' == 'netstandard1.6' AND '$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim()); Assert.Equal("'$(TargetFramework)' == 'net462' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); Assert.Equal("'$(TargetFramework)' == 'netstandard1.6' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim()); } }
public void VersionRangeFloatParsing_PrereleaseWithNumericOnlyLabelVerifyMinVersion(string rangeString, string expected) { var range = VersionRange.Parse(rangeString); Assert.Equal(expected, range.MinVersion.ToNormalizedString()); }
public void VersionRangeFloatParsing_VerifySatisfiesForFloatingRange(string rangeString, string version) { var range = VersionRange.Parse(rangeString); Assert.True(range.Satisfies(NuGetVersion.Parse(version))); }
void EmptyFormatThrows() => Assert.Throws <ArgumentException>(() => VersionRange.Parse(string.Empty));
/// <summary> /// Creates a net45 package containing lib, build, native, tools, and contentFiles /// </summary> public static FileInfo CreateFullPackage( string repositoryDir, SimpleTestPackageContext packageContext) { var id = packageContext.Id; var version = packageContext.Version; var runtimeJson = packageContext.RuntimeJson; var pathResolver = new VersionFolderPathResolver(null); var packagePath = Path.Combine(repositoryDir, $"{id}.{version.ToString()}.nupkg"); var file = new FileInfo(packagePath); file.Directory.Create(); using (var zip = new ZipArchive(File.Create(file.FullName), ZipArchiveMode.Create)) { if (packageContext.Files.Any()) { foreach (var entryFile in packageContext.Files) { zip.AddEntry(entryFile.Key, entryFile.Value); } } else { zip.AddEntry("contentFiles/any/any/config.xml", new byte[] { 0 }); zip.AddEntry("contentFiles/cs/net45/code.cs", new byte[] { 0 }); zip.AddEntry("lib/net45/a.dll", new byte[] { 0 }); zip.AddEntry("lib/netstandard1.0/a.dll", new byte[] { 0 }); zip.AddEntry($"build/net45/{id}.targets", @"<targets />", Encoding.UTF8); zip.AddEntry("runtimes/any/native/a.dll", new byte[] { 0 }); zip.AddEntry("tools/a.exe", new byte[] { 0 }); } if (!string.IsNullOrEmpty(runtimeJson)) { zip.AddEntry("runtime.json", runtimeJson, Encoding.UTF8); } var nuspecXml = packageContext.Nuspec?.ToString() ?? $@"<?xml version=""1.0"" encoding=""utf-8""?> <package> <metadata> <id>{id}</id> <version>{version.ToString()}</version> <title /> <frameworkAssemblies> <frameworkAssembly assemblyName=""System.Runtime"" /> </frameworkAssemblies> <contentFiles> <files include=""cs/net45/config/config.xml"" buildAction=""none"" /> <files include=""cs/net45/config/config.xml"" copyToOutput=""true"" flatten=""false"" /> <files include=""cs/net45/images/image.jpg"" buildAction=""embeddedresource"" /> </contentFiles> </metadata> </package>"; var xml = XDocument.Parse(nuspecXml); // Add the min client version if it exists if (!string.IsNullOrEmpty(packageContext.MinClientVersion)) { xml.Root.Element(XName.Get("metadata")) .Add(new XAttribute(XName.Get("minClientVersion"), packageContext.MinClientVersion)); } var dependencies = packageContext.Dependencies.Select(e => new PackageDependency( e.Id, VersionRange.Parse(e.Version), string.IsNullOrEmpty(e.Include) ? new List <string>() : e.Include.Split(',').ToList(), string.IsNullOrEmpty(e.Exclude) ? new List <string>() : e.Exclude.Split(',').ToList())); if (dependencies.Any()) { var metadata = xml.Element(XName.Get("package")).Element(XName.Get("metadata")); var dependenciesNode = new XElement(XName.Get("dependencies")); var groupNode = new XElement(XName.Get("group")); dependenciesNode.Add(groupNode); metadata.Add(dependenciesNode); foreach (var dependency in dependencies) { var node = new XElement(XName.Get("dependency")); groupNode.Add(node); node.Add(new XAttribute(XName.Get("id"), dependency.Id)); node.Add(new XAttribute(XName.Get("version"), dependency.VersionRange.ToNormalizedString())); if (dependency.Include.Count > 0) { node.Add(new XAttribute(XName.Get("include"), string.Join(",", dependency.Include))); } if (dependency.Exclude.Count > 0) { node.Add(new XAttribute(XName.Get("exclude"), string.Join(",", dependency.Exclude))); } } } if (packageContext.PackageTypes.Any()) { var metadata = xml.Element("package").Element("metadata"); var packageTypes = new XElement("packageTypes"); metadata.Add(packageTypes); foreach (var packageType in packageContext.PackageTypes) { var packageTypeElement = new XElement("packageType"); packageTypeElement.Add(new XAttribute("name", packageType.Name)); if (packageType.Version != PackageType.EmptyVersion) { packageTypeElement.Add(new XAttribute("version", packageType.Version)); } packageTypes.Add(packageTypeElement); } } zip.AddEntry($"{id}.nuspec", xml.ToString(), Encoding.UTF8); } return(file); }
public async Task ResolvesVersion_Correctly(string current, VersionLock versionLock, PrereleaseReporting prerelease, string latest) { // Arrange // Act var latestVersion = await _nuGetPackageResolutionService.ResolvePackageVersions(packageName, NuGetVersion.Parse(current), new List <Uri>(), VersionRange.Parse(current), versionLock, prerelease, null, null); // Assert Assert.Equal(NuGetVersion.Parse(latest), latestVersion); }
private static RuntimePackageDependency ReadRuntimePackageDependency(KeyValuePair <string, JToken> json) { return(new RuntimePackageDependency(json.Key, VersionRange.Parse(json.Value.Value <string>()))); }
private static PackageDependencyInfo CreatePackageDependencyInfo(PackageIdentity packageIdentity, params string[] dependencies) { if (dependencies != null && dependencies.Length % 2 != 0) { throw new ArgumentException("dependencies array length should be even"); } var dependencyList = new List <Packaging.Core.PackageDependency>(); if (dependencies != null) { for (var i = 0; i < dependencies.Length; i += 2) { var packageDependency = new Packaging.Core.PackageDependency(dependencies[i], VersionRange.Parse(dependencies[i + 1])); dependencyList.Add(packageDependency); } } return(new PackageDependencyInfo(packageIdentity, dependencyList)); }
public void ParseVersionRangeWithNullThrows() { // Act & Assert ExceptionAssert.ThrowsArgNull(() => VersionRange.Parse(null), "value"); }
public async Task BuildIntegratedNuGetProject_IsRestoreRequiredWithNoChangesFallbackFolder() { // Arrange var projectName = "testproj"; using (var globalFolder = TestDirectory.Create()) using (var fallbackFolder = TestDirectory.Create()) using (var rootFolder = TestDirectory.Create()) { var projectFolder = new DirectoryInfo(Path.Combine(rootFolder, projectName)); projectFolder.Create(); var projectConfig = new FileInfo(Path.Combine(projectFolder.FullName, "project.json")); var msbuildProjectPath = new FileInfo(Path.Combine(projectFolder.FullName, $"{projectName}.csproj")); BuildIntegrationTestUtility.CreateConfigJson(projectConfig.FullName); var json = JObject.Parse(File.ReadAllText(projectConfig.FullName)); JsonConfigUtility.AddDependency(json, new NuGet.Packaging.Core.PackageDependency("nuget.versioning", VersionRange.Parse("1.0.7"))); using (var writer = new StreamWriter(projectConfig.FullName)) { writer.Write(json.ToString()); } var sources = new List <SourceRepository> { Repository.Factory.GetVisualStudio("https://www.nuget.org/api/v2/") }; var projectTargetFramework = NuGetFramework.Parse("uap10.0"); var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext()); var project = new ProjectJsonNuGetProject(projectConfig.FullName, msbuildProjectPath.FullName); // Restore to the fallback folder var solutionManager = new TestSolutionManager(false); solutionManager.NuGetProjects.Add(project); var testLogger = new TestLogger(); var restoreContext = new DependencyGraphCacheContext(testLogger, NullSettings.Instance); await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, new RestoreCommandProvidersCache(), (c) => { }, sources, Guid.Empty, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), testLogger, CancellationToken.None); var packageFolders = new List <string> { globalFolder, fallbackFolder }; // Act //var actual = await project.IsRestoreRequired( // packageFolders.Select(p => new VersionFolderPathResolver(p)), // new HashSet<PackageIdentity>(), // restoreContext); // Assert //Assert.False(actual); } }
public async Task BuildIntegratedNuGetProject_IsRestoreRequiredWithNoChanges() { // Arrange var projectName = "testproj"; using (var packagesFolder = TestDirectory.Create()) using (var rootFolder = TestDirectory.Create()) { var projectFolder = new DirectoryInfo(Path.Combine(rootFolder, projectName)); projectFolder.Create(); var projectConfig = new FileInfo(Path.Combine(projectFolder.FullName, "project.json")); var msbuildProjectPath = new FileInfo(Path.Combine(projectFolder.FullName, $"{projectName}.csproj")); BuildIntegrationTestUtility.CreateConfigJson(projectConfig.FullName); var json = JObject.Parse(File.ReadAllText(projectConfig.FullName)); JsonConfigUtility.AddDependency(json, new NuGet.Packaging.Core.PackageDependency("nuget.versioning", VersionRange.Parse("1.0.7"))); using (var writer = new StreamWriter(projectConfig.FullName)) { writer.Write(json.ToString()); } var sources = new List <SourceRepository> { Repository.Factory.GetVisualStudio("https://www.nuget.org/api/v2/") }; var projectTargetFramework = NuGetFramework.Parse("uap10.0"); var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext()); var project = new ProjectJsonNuGetProject(projectConfig.FullName, msbuildProjectPath.FullName); var effectiveGlobalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(NullSettings.Instance); var solutionManager = new TestSolutionManager(false); solutionManager.NuGetProjects.Add(project); var testLogger = new TestLogger(); var settings = new Settings(rootFolder); settings.SetValue(SettingsUtility.ConfigSection, "globalPackagesFolder", packagesFolder); var providersCache = new RestoreCommandProvidersCache(); var restoreContext = new DependencyGraphCacheContext(testLogger, settings); await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, providersCache, (c) => { }, sources, Guid.Empty, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), testLogger, CancellationToken.None); var noOpRestoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, providersCache, (c) => { }, sources, Guid.Empty, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), testLogger, CancellationToken.None); foreach (var restoreSummary in noOpRestoreSummaries) { Assert.True(restoreSummary.NoOpRestore); } } }
public async Task BuildIntegratedNuGetProject_IsRestoreRequiredChangedSha512() { // Arrange var projectName = "testproj"; using (var solutionManager = new TestSolutionManager(false)) { var projectFolder = new DirectoryInfo(Path.Combine(solutionManager.SolutionDirectory, projectName)); projectFolder.Create(); var projectConfig = new FileInfo(Path.Combine(projectFolder.FullName, "project.json")); var msbuildProjectPath = new FileInfo(Path.Combine(projectFolder.FullName, $"{projectName}.csproj")); BuildIntegrationTestUtility.CreateConfigJson(projectConfig.FullName); var json = JObject.Parse(File.ReadAllText(projectConfig.FullName)); JsonConfigUtility.AddDependency(json, new PackageDependency("nuget.versioning", VersionRange.Parse("1.0.7"))); using (var writer = new StreamWriter(projectConfig.FullName)) { writer.Write(json.ToString()); } var sources = new List <SourceRepository> { }; var testLogger = new TestLogger(); var settings = Settings.LoadSpecificSettings(solutionManager.SolutionDirectory, "NuGet.Config"); var project = new ProjectJsonNuGetProject(projectConfig.FullName, msbuildProjectPath.FullName); solutionManager.NuGetProjects.Add(project); var restoreContext = new DependencyGraphCacheContext(testLogger, settings); var providersCache = new RestoreCommandProvidersCache(); var dgSpec1 = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext); await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, providersCache, (c) => { }, sources, Guid.Empty, false, dgSpec1, testLogger, CancellationToken.None); var dgSpec2 = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext); var noOpRestoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, providersCache, (c) => { }, sources, Guid.Empty, false, dgSpec2, testLogger, CancellationToken.None); foreach (var restoreSummary in noOpRestoreSummaries) { Assert.True(restoreSummary.NoOpRestore); } var resolver = new VersionFolderPathResolver(solutionManager.GlobalPackagesFolder); var hashPath = resolver.GetHashPath("nuget.versioning", NuGetVersion.Parse("1.0.7")); File.Delete(hashPath); var restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, new RestoreCommandProvidersCache(), (c) => { }, sources, Guid.Empty, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), testLogger, CancellationToken.None); foreach (var restoreSummary in restoreSummaries) { Assert.True(restoreSummary.Success); Assert.False(restoreSummary.NoOpRestore); } var filePath = Path.Combine( NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "nuget-dg", "nugetSpec.dg"); Assert.True(File.Exists(filePath)); } }
public void NuspecReaderTests_ValidVersionRangeInDependencyReturnsResultForStrictCheck(string versionRange) { // Arrange var formattedNuspec = string.Format(VersionRangeInDependency, versionRange); var nuspecReader = GetReader(formattedNuspec); var expectedVersionRange = string.IsNullOrEmpty(versionRange) ? VersionRange.All : VersionRange.Parse(versionRange); // Act var dependencyGroups = nuspecReader.GetDependencyGroups(useStrictVersionCheck: true).ToList(); // Assert Assert.Equal(1, dependencyGroups.Count); Assert.Equal(expectedVersionRange, dependencyGroups.First().Packages.First().VersionRange); }
public static List <LibraryDependency> GetPackageReferences(ProjectTestExtension project) { project.Save(); var doc = XDocument.Load(project.FullPath); return(doc.Root.Descendants() .Where(e => e.Name.LocalName.Equals("PackageReference", StringComparison.OrdinalIgnoreCase)) .Select(e => new LibraryDependency() { LibraryRange = new LibraryRange(e.Attribute(XName.Get("Include")).Value, VersionRange.Parse(e.Attribute(XName.Get("Version")).Value), LibraryDependencyTarget.Package), IncludeType = LibraryIncludeFlags.All, SuppressParent = LibraryIncludeFlags.None, NoWarn = new List <NuGetLogCode>(), AutoReferenced = false, GeneratePathProperty = false }) .ToList()); }
void InvalidFormatThrows(string input) => Assert.Throws <NotSupportedException>(() => VersionRange.Parse(input));
internal static TargetFrameworkInformation CreateTargetFrameworkInformation(string tfm = "net461", string alias = null) { var framework = NuGetFramework.Parse(tfm); var dependency = new LibraryDependency( libraryRange: new LibraryRange("Dependency", LibraryDependencyTarget.Package), includeType: LibraryIncludeFlags.None, suppressParent: LibraryIncludeFlags.ContentFiles, noWarn: new List <NuGetLogCode>() { NuGetLogCode.NU1000, NuGetLogCode.NU1001 }, autoReferenced: false, generatePathProperty: false, versionCentrallyManaged: false, LibraryDependencyReferenceType.Direct, aliases: "stuff"); var imports = NuGetFramework.Parse("net45"); // This makes no sense in the context of fallback, just for testing :) var originalTargetFrameworkInformation = new TargetFrameworkInformation(); originalTargetFrameworkInformation.TargetAlias = alias ?? Guid.NewGuid().ToString(); originalTargetFrameworkInformation.FrameworkName = framework; originalTargetFrameworkInformation.Dependencies = new List <LibraryDependency>() { dependency }; originalTargetFrameworkInformation.AssetTargetFallback = false; originalTargetFrameworkInformation.Imports = new List <NuGetFramework>() { imports }; originalTargetFrameworkInformation.DownloadDependencies.Add(new DownloadDependency("X", VersionRange.Parse("1.0.0"))); originalTargetFrameworkInformation.FrameworkReferences.Add(new FrameworkDependency("frameworkRef", FrameworkDependencyFlags.All)); originalTargetFrameworkInformation.FrameworkReferences.Add(new FrameworkDependency("FrameworkReference", FrameworkDependencyFlags.None)); originalTargetFrameworkInformation.RuntimeIdentifierGraphPath = @"path/to/dotnet/sdk/3.0.100/runtime.json"; originalTargetFrameworkInformation.CentralPackageVersions.Add("CVD", new CentralPackageVersion("CVD", VersionRange.Parse("1.0.0"))); return(originalTargetFrameworkInformation); }
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.CreateFolderFeedV3( 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> /// Write a zip file to a stream. /// </summary> public static async Task CreatePackageAsync(Stream stream, SimpleTestPackageContext packageContext) { var id = packageContext.Id; var version = packageContext.Version; var runtimeJson = packageContext.RuntimeJson; var pathResolver = new VersionFolderPathResolver(null); var testLogger = new TestLogger(); var tempStream = stream; var isUsingTempStream = false; if (packageContext.IsPrimarySigned) { tempStream = new MemoryStream(); isUsingTempStream = true; } using (var zip = new ZipArchive(tempStream, ZipArchiveMode.Create, leaveOpen: true)) { if (packageContext.Files.Any()) { foreach (var entryFile in packageContext.Files) { zip.AddEntry(entryFile.Key, entryFile.Value); } } else { zip.AddEntry("contentFiles/any/any/config.xml", new byte[] { 0 }); zip.AddEntry("contentFiles/cs/net45/code.cs", new byte[] { 0 }); zip.AddEntry("lib/net45/a.dll", new byte[] { 0 }); zip.AddEntry("lib/netstandard1.0/a.dll", new byte[] { 0 }); zip.AddEntry($"build/net45/{id}.targets", @"<targets />", Encoding.UTF8); zip.AddEntry("runtimes/any/native/a.dll", new byte[] { 0 }); zip.AddEntry("tools/a.exe", new byte[] { 0 }); } if (!string.IsNullOrEmpty(runtimeJson)) { zip.AddEntry("runtime.json", runtimeJson, Encoding.UTF8); } var frameworkAssembliesAndContentFiles = packageContext.UseDefaultRuntimeAssemblies ? $@"<frameworkAssemblies> <frameworkAssembly assemblyName=""System.Runtime""/> </frameworkAssemblies> <contentFiles> <files include=""cs/net45/config/config.xml"" buildAction=""none"" /> <files include=""cs/net45/config/config.xml"" copyToOutput=""true"" flatten=""false"" /> <files include=""cs/net45/images/image.jpg"" buildAction=""embeddedresource"" /> </contentFiles>" : string.Empty; var nuspecXml = packageContext.Nuspec?.ToString() ?? $@"<?xml version=""1.0"" encoding=""utf-8""?> <package> <metadata> <id>{id}</id> <version>{version.ToString()}</version> <title /> {frameworkAssembliesAndContentFiles} </metadata> </package>"; var xml = XDocument.Parse(nuspecXml); // Add the min client version if it exists if (!string.IsNullOrEmpty(packageContext.MinClientVersion)) { xml.Root.Element(XName.Get("metadata")) .Add(new XAttribute(XName.Get("minClientVersion"), packageContext.MinClientVersion)); } var dependencies = packageContext.Dependencies.Select(e => new PackageDependency( e.Id, VersionRange.Parse(e.Version), string.IsNullOrEmpty(e.Include) ? new List <string>() : e.Include.Split(',').ToList(), string.IsNullOrEmpty(e.Exclude) ? new List <string>() : e.Exclude.Split(',').ToList())); if (dependencies.Any()) { var metadata = xml.Element(XName.Get("package")).Element(XName.Get("metadata")); var dependenciesNode = new XElement(XName.Get("dependencies")); var groupNode = new XElement(XName.Get("group")); dependenciesNode.Add(groupNode); metadata.Add(dependenciesNode); foreach (var dependency in dependencies) { var node = new XElement(XName.Get("dependency")); groupNode.Add(node); node.Add(new XAttribute(XName.Get("id"), dependency.Id)); node.Add(new XAttribute(XName.Get("version"), dependency.VersionRange.ToNormalizedString())); if (dependency.Include.Count > 0) { node.Add(new XAttribute(XName.Get("include"), string.Join(",", dependency.Include))); } if (dependency.Exclude.Count > 0) { node.Add(new XAttribute(XName.Get("exclude"), string.Join(",", dependency.Exclude))); } } } if (packageContext.PackageTypes.Count > 0) { var metadata = xml.Element("package").Element("metadata"); var packageTypes = new XElement("packageTypes"); metadata.Add(packageTypes); foreach (var packageType in packageContext.PackageTypes) { var packageTypeElement = new XElement("packageType"); packageTypeElement.Add(new XAttribute("name", packageType.Name)); if (packageType.Version != PackageType.EmptyVersion) { packageTypeElement.Add(new XAttribute("version", packageType.Version)); } packageTypes.Add(packageTypeElement); } } zip.AddEntry($"{id}.nuspec", xml.ToString(), Encoding.UTF8); } if (isUsingTempStream) { #if IS_DESKTOP using (var signPackage = new SignedPackageArchive(tempStream, stream)) { using (var request = GetPrimarySignRequest(packageContext)) { await AddSignatureToPackageAsync(packageContext, signPackage, request, testLogger); } if (packageContext.IsRepositoryCounterSigned) { using (var request = new RepositorySignPackageRequest(new X509Certificate2(packageContext.RepositoryCountersignatureCertificate), HashAlgorithmName.SHA256, HashAlgorithmName.SHA256, packageContext.V3ServiceIndexUrl, packageContext.PackageOwners)) { await AddRepositoryCountersignatureToSignedPackageAsync(packageContext, signPackage, request, testLogger); } } } #endif tempStream.Dispose(); } // Reset position stream.Position = 0; }
public void VersionRangeFloatParsing_Prerelease() { var range = VersionRange.Parse("1.0.0-*"); Assert.True(range.MinVersion.IsPrerelease); }
public async Task LoadDependencies() { // TODO 添加正在加载依赖的显示 var json_cfg = ProcessProjectJsonConfig(); foreach (JProperty jp in (JToken)json_cfg.dependencies) { var ver_range = VersionRange.Parse((string)jp.Value); if (ver_range.IsMinInclusive) { var target_ver = NuGetVersion.Parse(ver_range.MinVersion.ToString()); await NuGetPackageController.Instance.DownloadAndInstall(new NuGet.Packaging.Core.PackageIdentity(jp.Name, target_ver)); } else { //TODO WJF 大于但不等于低版本时如何处理? } } //加载依赖的DLL var targetDir = NuGetPackageController.Instance.TargetFolder; string[] dll_files = Directory.GetFiles(targetDir, "*.dll", SearchOption.TopDirectoryOnly);//搜索TargetDir最外层目录下的dll文件 foreach (var dll_file in dll_files) { //判断dll_file对应的文件是否在主程序所在目录存在,若存在,则加载主程序所在目录下的DLL,避免加载不同路径下的相同DLL文件 var checkPath = System.Environment.CurrentDirectory + @"\" + Path.GetFileName(dll_file); if (System.IO.File.Exists(checkPath)) { Logger.Debug($"发现主程序所在目录下存在同名dll,忽略加载 {checkPath}", logger); continue;//避免加载重复的DLL } var asm = Assembly.LoadFrom(dll_file); var dll_file_name_without_ext = Path.GetFileNameWithoutExtension(dll_file); try { string activity_config_xml = null; var activity_config_info = Application.GetResourceStream(new Uri($"pack://application:,,,/{dll_file_name_without_ext};Component/activity.config.xml", UriKind.Absolute)); try { using (StreamReader reader = new StreamReader(activity_config_info.Stream)) { activity_config_xml = reader.ReadToEnd(); Logger.Debug($"开始挂载{dll_file}中的活动配置信息……", logger); ViewModelLocator.Instance.Activities.MountActivityConfig(activity_config_xml); } } catch (Exception err) { SharedObject.Instance.Output(SharedObject.enOutputType.Error, $"挂载{dll_file}中的activity.config.xml信息出错", err); } } catch (Exception) { //dll中找不到activity.config.xml时会报错走到这里,无须打印错误日志 } } }
public void VersionRangeFloatParsing_PrereleaseWithNumericOnlyLabelVerifySatisfies(string version) { var range = VersionRange.Parse("1.0.0-*"); Assert.True(range.Satisfies(NuGetVersion.Parse(version))); }
private static void PopulateDownloadDependencies(IList <DownloadDependency> downloadDependencies, JObject properties, string packageSpecPath) { var splitChars = new[] { ';' }; var seenIds = new HashSet <string>(); var downloadDependenciesProperty = properties["downloadDependencies"] as JArray; if (downloadDependenciesProperty != null) { foreach (var dependency in downloadDependenciesProperty.Values <JToken>()) { if (dependency["name"] == null) { throw FileFormatException.Create( "Unable to resolve downloadDependency ''.", dependency, packageSpecPath); } var name = dependency["name"].Value <string>(); if (!seenIds.Add(name)) { // package ID already seen, only use first definition. continue; } string versionValue = null; var dependencyVersionToken = dependency["version"]; if (dependencyVersionToken != null && dependencyVersionToken.Type == JTokenType.String) { versionValue = dependencyVersionToken.Value <string>(); } VersionRange version = null; if (!string.IsNullOrEmpty(versionValue)) { var versions = versionValue.Split(splitChars, StringSplitOptions.RemoveEmptyEntries); foreach (var singleVersionValue in versions) { try { version = VersionRange.Parse(singleVersionValue); downloadDependencies.Add(new DownloadDependency(name, version)); } catch (Exception ex) { throw FileFormatException.Create( ex, dependencyVersionToken, packageSpecPath); } } } else { throw FileFormatException.Create( "The version cannot be null or empty", dependencyVersionToken, packageSpecPath); } } } }
public void IsLockFileStillValid_TransitiveDependencyNotCentrallyManaged_DoesNotInvalidateLockFile() { // Arrange var framework = CommonFrameworks.NetStandard20; var projectName = "project"; var cpvm1 = new CentralPackageVersion("cpvm1", VersionRange.Parse("1.0.0")); var cpvm2 = new CentralPackageVersion("cpvm2", VersionRange.Parse("1.0.0")); var dependency1 = new LibraryDependency( new LibraryRange("cpvm1", versionRange: null, LibraryDependencyTarget.Package), LibraryDependencyType.Default, LibraryIncludeFlags.All, LibraryIncludeFlags.All, new List <Common.NuGetLogCode>(), autoReferenced: false, generatePathProperty: true); var tfm = new TargetFrameworkInformation(); tfm.FrameworkName = framework; tfm.CentralPackageVersions.Add("cpvm1", cpvm1); tfm.CentralPackageVersions.Add("cpvm2", cpvm2); tfm.Dependencies.Add(dependency1); var project = new PackageSpec(new List <TargetFrameworkInformation>() { tfm }); project.RestoreMetadata = new ProjectRestoreMetadata() { ProjectUniqueName = projectName, CentralPackageVersionsEnabled = true }; DependencyGraphSpec dgSpec = new DependencyGraphSpec(); dgSpec.AddRestore(projectName); dgSpec.AddProject(project); var lockFile1 = new PackagesLockFileBuilder() .WithTarget(target => target .WithFramework(CommonFrameworks.NetStandard20) .WithDependency(dep => dep .WithId("cpvm1") .WithRequestedVersion(VersionRange.Parse("1.0.0")) .WithType(PackageDependencyType.Direct)) .WithDependency(dep => dep .WithId("otherDep") .WithRequestedVersion(VersionRange.Parse("1.0.0")) .WithType(PackageDependencyType.Transitive))) .Build(); var lockFile2 = new PackagesLockFileBuilder() .WithVersion(PackagesLockFileFormat.PackagesLockFileVersion) .WithTarget(target => target .WithFramework(CommonFrameworks.NetStandard20) .WithDependency(dep => dep .WithId("cpvm1") .WithRequestedVersion(VersionRange.Parse("1.0.0")) .WithType(PackageDependencyType.Direct)) .WithDependency(dep => dep .WithId("otherDep") .WithRequestedVersion(VersionRange.Parse("1.0.0")) .WithType(PackageDependencyType.Transitive))) .Build(); // Nothing changed // different versions of lock file versions are handled Assert.True(PackagesLockFileUtilities.IsLockFileStillValid(dgSpec, lockFile1)); Assert.True(PackagesLockFileUtilities.IsLockFileStillValid(dgSpec, lockFile2)); }
public void AddProject_WhenDependencyVersionIsNull_CentralPackageVersionAppliesOnlyWhenAutoReferencedIsFalse() { // Arrange var dependencyFoo = new LibraryDependency( new LibraryRange("foo", versionRange: null, LibraryDependencyTarget.Package), LibraryIncludeFlags.All, LibraryIncludeFlags.All, new List <Common.NuGetLogCode>(), autoReferenced: false, generatePathProperty: true, versionCentrallyManaged: false, LibraryDependencyReferenceType.Direct, aliases: null); var dependencyBar = new LibraryDependency( new LibraryRange("bar", VersionRange.Parse("3.0.0"), LibraryDependencyTarget.Package), LibraryIncludeFlags.All, LibraryIncludeFlags.All, new List <Common.NuGetLogCode>(), autoReferenced: true, generatePathProperty: true, versionCentrallyManaged: false, LibraryDependencyReferenceType.Direct, aliases: null); var dependencyBoom = new LibraryDependency( new LibraryRange("boom", versionRange: null, LibraryDependencyTarget.Package), LibraryIncludeFlags.All, LibraryIncludeFlags.All, new List <Common.NuGetLogCode>(), autoReferenced: true, generatePathProperty: true, versionCentrallyManaged: false, LibraryDependencyReferenceType.Direct, aliases: null); var centralVersionFoo = new CentralPackageVersion("foo", VersionRange.Parse("1.0.0")); var centralVersionBar = new CentralPackageVersion("bar", VersionRange.Parse("2.0.0")); var centralVersionBoom = new CentralPackageVersion("boom", VersionRange.Parse("4.0.0")); var tfi = CreateTargetFrameworkInformation( new List <LibraryDependency>() { dependencyFoo, dependencyBar, dependencyBoom }, new List <CentralPackageVersion>() { centralVersionFoo, centralVersionBar, centralVersionBoom }); // Act DependencyGraphSpec dependencyGraphSpec = CreateDependencyGraphSpecWithCentralDependencies(tfi); // Assert Assert.Equal(1, dependencyGraphSpec.Projects.Count); PackageSpec packSpec = dependencyGraphSpec.Projects[0]; IList <TargetFrameworkInformation> tfms = packSpec.TargetFrameworks; IList <LibraryDependency> dependencies = tfms[0].Dependencies; Assert.Equal(1, tfms.Count); Assert.Equal(3, dependencies.Count); Assert.Equal("[1.0.0, )", dependencies.Where(d => d.Name == "foo").First().LibraryRange.VersionRange.ToNormalizedString()); Assert.True(dependencies.Where(d => d.Name == "foo").First().VersionCentrallyManaged); Assert.Equal("[3.0.0, )", dependencies.Where(d => d.Name == "bar").First().LibraryRange.VersionRange.ToNormalizedString()); Assert.False(dependencies.Where(d => d.Name == "bar").First().VersionCentrallyManaged); Assert.Null(dependencies.Where(d => d.Name == "boom").First().LibraryRange.VersionRange); }
/// <summary> /// Return the list of <see cref="PackageToPrepare"/> in the ordered form /// for which we want to run all the tasks sequentially /// </summary> /// <returns>Ordered list of tasks to run for <see cref="PackageToPrepare"/></returns> private async Task <List <PackageToPrepare> > InitializePackagesAsync(PackageType packageType, ITestOutputHelper logger) { var id = GetPackageId(packageType); PackageToPrepare packageToPrepare; List <PackageToPrepare> packagesToPrepare = new List <PackageToPrepare>(); switch (packageType) { case PackageType.SemVer2DueToSemVer2Dep: packageToPrepare = new PackageToPrepare(Package.Create(new PackageCreationContext { Id = id, NormalizedVersion = "1.0.0-beta", FullVersion = "1.0.0-beta", DependencyGroups = new[] { new PackageDependencyGroup( TestData.TargetFramework, new[] { new PackageDependency( GetPackageId(PackageType.SemVer2Prerel), VersionRange.Parse(SemVer2PrerelVersion)) }) } })); break; case PackageType.SemVer2StableMetadataUnlisted: packageToPrepare = new PackageToPrepare( Package.Create(id, "1.0.0", "1.0.0+metadata"), unlist: true); break; case PackageType.SemVer2StableMetadata: packageToPrepare = new PackageToPrepare(Package.Create(id, "1.0.0", "1.0.0+metadata")); break; case PackageType.SemVer2PrerelUnlisted: packageToPrepare = new PackageToPrepare( Package.Create(id, "1.0.0-alpha.1"), unlist: true); break; case PackageType.SemVer2Prerel: packageToPrepare = new PackageToPrepare(Package.Create(id, SemVer2PrerelVersion)); break; case PackageType.SemVer2PrerelRelisted: packageToPrepare = new PackageToPrepare(Package.Create(id, "1.0.0-alpha.1"), unlist: true); break; case PackageType.SemVer1StableUnlisted: packageToPrepare = new PackageToPrepare( Package.Create(id, "1.0.0"), unlist: true); break; case PackageType.Signed: packageToPrepare = new PackageToPrepare(Package.SignedPackage()); break; case PackageType.SymbolsPackage: return(await PrepareSymbolsPackageAsync(id, "1.0.0", logger)); case PackageType.SemVer1Stable: case PackageType.FullValidation: default: packageToPrepare = new PackageToPrepare(Package.Create(id, "1.0.0")); break; } packagesToPrepare.Add(packageToPrepare); return(packagesToPrepare); }
public void AddProject_DoesNotClone(bool cpvmEnabled) { // Arrange var dependencyFoo = new LibraryDependency() { LibraryRange = new LibraryRange("foo", versionRange: cpvmEnabled ? null : VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package), }; var centralVersions = cpvmEnabled ? new List <CentralPackageVersion>() { new CentralPackageVersion("foo", VersionRange.Parse("1.0.0")) } : new List <CentralPackageVersion>(); var tfi = CreateTargetFrameworkInformation( new List <LibraryDependency>() { dependencyFoo }, centralVersions); var packageSpec = new PackageSpec(new List <TargetFrameworkInformation>() { tfi }); packageSpec.RestoreMetadata = new ProjectRestoreMetadata() { ProjectUniqueName = "a", CentralPackageVersionsEnabled = cpvmEnabled }; var dgSpec = new DependencyGraphSpec(); dgSpec.AddRestore("a"); dgSpec.AddProject(packageSpec); // Act var packageSpecFromDGSpec = dgSpec.GetProjectSpec("a"); // Assert Assert.True(packageSpec.Equals(packageSpecFromDGSpec)); }
public async Task RestoreBuildTargetsAndProps_VerifyRestoreNoopAsync() { // 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 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/_._"); await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageX); var project = projects[0]; // First restore var summaries = await RunRestoreAsync(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 RunRestoreAsync(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 BuildIntegratedNuGetProject_RestoreFailed_PersistDGSpecFile() { // Arrange var projectName = "testproj"; using (var packagesFolder = TestDirectory.Create()) using (var rootFolder = TestDirectory.Create()) { var projectFolder = new DirectoryInfo(Path.Combine(rootFolder, projectName)); projectFolder.Create(); var projectConfig = new FileInfo(Path.Combine(projectFolder.FullName, "project.json")); var msbuildProjectPath = new FileInfo(Path.Combine(projectFolder.FullName, $"{projectName}.csproj")); BuildIntegrationTestUtility.CreateConfigJson(projectConfig.FullName); var json = JObject.Parse(File.ReadAllText(projectConfig.FullName)); // invalid version for nuget.versioning package which will make this restore fail. JsonConfigUtility.AddDependency(json, new PackageDependency("nuget.versioning", VersionRange.Parse("3000.0.0"))); using (var writer = new StreamWriter(projectConfig.FullName)) { writer.Write(json.ToString()); } var sources = new List <SourceRepository> { }; var testLogger = new TestLogger(); var settings = new Settings(rootFolder); settings.SetValue(SettingsUtility.ConfigSection, "globalPackagesFolder", packagesFolder); var project = new ProjectJsonNuGetProject(projectConfig.FullName, msbuildProjectPath.FullName); var solutionManager = new TestSolutionManager(false); solutionManager.NuGetProjects.Add(project); var restoreContext = new DependencyGraphCacheContext(testLogger, settings); var providersCache = new RestoreCommandProvidersCache(); var dgSpec = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext); var restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, providersCache, (c) => { }, sources, Guid.Empty, false, dgSpec, testLogger, CancellationToken.None); foreach (var restoreSummary in restoreSummaries) { Assert.False(restoreSummary.Success); } var filePath = Path.Combine( NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "nuget-dg", "nugetSpec.dg"); Assert.True(File.Exists(filePath)); } }