/// <summary> /// Initializes a new <see cref="FolderNuGetProject" /> class. /// </summary> /// <param name="root">The folder project root path.</param> /// <param name="packagePathResolver">A package path resolver.</param> /// <param name="targetFramework">Project target framework.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="root" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="packagePathResolver" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="targetFramework" /> is <c>null</c>.</exception> public FolderNuGetProject(string root, PackagePathResolver packagePathResolver, NuGetFramework targetFramework) { if (targetFramework == null) { throw new ArgumentNullException(nameof(targetFramework)); } Root = root ?? throw new ArgumentNullException(nameof(root)); PackagePathResolver = packagePathResolver ?? throw new ArgumentNullException(nameof(packagePathResolver)); InternalMetadata.Add(NuGetProjectMetadataKeys.Name, root); InternalMetadata.Add(NuGetProjectMetadataKeys.TargetFramework, targetFramework); _framework = targetFramework; }
/// <summary> /// Creates a new Package Reference Set /// </summary> /// <param name="targetFramework">The target framework to use, pass Any for AnyFramework. Does not allow null.</param> /// <param name="references">IEnumerable set of string references</param> public PackageReferenceSet(string targetFramework, IEnumerable <string> references) : this(targetFramework != null ? NuGetFramework.Parse(targetFramework) : null, references) { }
public void LockFile_ConsidersEquivalentLockFilesWithFullLogsAsSame() { // Arrange Func <LockFile> getLockFile = () => { var lockFile = new LockFile { Version = 3, PackageSpec = new PackageSpec(new[] { new TargetFrameworkInformation { FrameworkName = FrameworkConstants.CommonFrameworks.NetCoreApp10, Dependencies = new[] { new LibraryDependency { LibraryRange = new LibraryRange( "Microsoft.NETCore.App", new VersionRange( minVersion: new NuGetVersion("1.0.1"), originalString: "1.0.1"), LibraryDependencyTarget.Package) }, new LibraryDependency { LibraryRange = new LibraryRange( "Microsoft.NET.Sdk", new VersionRange( minVersion: new NuGetVersion("1.0.0-alpha-20161104-2"), originalString: "1.0.0-alpha-20161104-2"), LibraryDependencyTarget.Package), SuppressParent = LibraryIncludeFlags.All } } } }) { Version = new NuGetVersion("1.0.0"), RestoreMetadata = new ProjectRestoreMetadata { ProjectUniqueName = @"X:\ProjectPath\ProjectPath.csproj", ProjectName = "ProjectPath", ProjectPath = @"X:\ProjectPath\ProjectPath.csproj", OutputPath = @"X:\ProjectPath\obj\", ProjectStyle = ProjectStyle.PackageReference, OriginalTargetFrameworks = new[] { "netcoreapp1.0" }, TargetFrameworks = new List <ProjectRestoreMetadataFrameworkInfo> { new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("netcoreapp1.0")) } } } }; return(lockFile); }; var self = getLockFile(); var other = getLockFile(); self.LogMessages = new List <IAssetsLogMessage> { new AssetsLogMessage(LogLevel.Error, NuGetLogCode.NU1000, "test log message") { FilePath = @"kung\fu\fighting.targets", ProjectPath = @"kung\fu\fighting.csproj", TargetGraphs = new List <string> { "net46", "netcoreapp1.0", "netstandard1.6" }, StartLineNumber = 11, StartColumnNumber = 2, EndLineNumber = 11, EndColumnNumber = 10, LibraryId = "nuget.versioning" }, new AssetsLogMessage(LogLevel.Warning, NuGetLogCode.NU1500, "test warning message") { FilePath = @"kung\fu\fighting.targets", ProjectPath = @"kung\fu\fighting.csproj", TargetGraphs = new List <string> { "net46", "netcoreapp1.0", "netstandard1.6" }, StartLineNumber = 11, StartColumnNumber = 2, EndLineNumber = 11, EndColumnNumber = 10, LibraryId = "nuget.versioning", WarningLevel = WarningLevel.Severe } }; other.LogMessages = new List <IAssetsLogMessage> { new AssetsLogMessage(LogLevel.Error, NuGetLogCode.NU1000, "test log message") { FilePath = @"kung\fu\fighting.targets", ProjectPath = @"kung\fu\fighting.csproj", TargetGraphs = new List <string> { "net46", "netcoreapp1.0", "netstandard1.6" }, StartLineNumber = 11, StartColumnNumber = 2, EndLineNumber = 11, EndColumnNumber = 10, LibraryId = "nuget.versioning" }, new AssetsLogMessage(LogLevel.Warning, NuGetLogCode.NU1500, "test warning message") { FilePath = @"kung\fu\fighting.targets", ProjectPath = @"kung\fu\fighting.csproj", TargetGraphs = new List <string> { "net46", "netcoreapp1.0", "netstandard1.6" }, StartLineNumber = 11, StartColumnNumber = 2, EndLineNumber = 11, EndColumnNumber = 10, LibraryId = "nuget.versioning", WarningLevel = WarningLevel.Severe } }; // Act & Assert Assert.NotSame(self, other); Assert.Equal(self, other); }
/// <summary> /// Dependency walk /// </summary> public override async Task <IEnumerable <PackageDependencyInfo> > ResolvePackages(IEnumerable <PackageIdentity> packages, NuGetFramework projectFramework, bool includePrerelease, CancellationToken token) { if (projectFramework == null) { throw new ArgumentNullException("projectFramework"); } if (packages == null) { throw new ArgumentNullException("packages"); } HashSet <PackageDependencyInfo> results = new HashSet <PackageDependencyInfo>(PackageIdentityComparer.Default); foreach (PackageIdentity package in packages) { VersionRange range = package.HasVersion ? new VersionRange(package.Version, true, package.Version, true) : VersionRange.All; var target = new NuGet.Packaging.Core.PackageDependency(package.Id, range); results.UnionWith(await Seek(target, projectFramework, includePrerelease, Enumerable.Empty <string>(), token)); } // pre-release should not be in the final set, but filter again just to be sure return(results.Where(e => includePrerelease || !e.Version.IsPrerelease)); }
public void Create_IfProjectMetadataValuesAreNonNullAndValid_ReturnsNonNullPropertyValues() { var metadata = new Dictionary <string, object>() { { NuGetProjectMetadataKeys.FullPath, "a" }, { NuGetProjectMetadataKeys.Name, "b" }, { NuGetProjectMetadataKeys.ProjectId, "c" }, { NuGetProjectMetadataKeys.SupportedFrameworks, new[] { NuGetFramework.Parse("net48"), NuGetFramework.Parse("net50") } }, { NuGetProjectMetadataKeys.TargetFramework, NuGetFramework.Parse("net50") }, { NuGetProjectMetadataKeys.UniqueName, "d" } }; ProjectMetadataContextInfo projectMetadata = ProjectMetadataContextInfo.Create(metadata); AssertEqual(metadata, projectMetadata); }
internal static void SetupNuGet(string packageName, string packageVersion) { // Make sure our nuget local store is added to nuget config var folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string strideFolder = null; while (folder != null) { if (File.Exists(Path.Combine(folder, @"build\Stride.sln"))) { strideFolder = folder; var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null); Directory.CreateDirectory(Environment.ExpandEnvironmentVariables(DevSource)); CheckPackageSource(settings, "Stride Dev", NuGet.Configuration.Settings.ApplyEnvironmentTransform(DevSource)); settings.SaveToDisk(); break; } folder = Path.GetDirectoryName(folder); } // Note: we perform nuget restore inside the assembly resolver rather than top level module ctor (otherwise it freezes) AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => { // Check if already loaded. // Somehow it happens for Microsoft.NET.Build.Tasks -> NuGet.ProjectModel, probably due to the specific way it's loaded. var matchingAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName == eventArgs.Name); if (matchingAssembly != null) { return(matchingAssembly); } if (!assembliesResolved) { lock (assembliesLock) { // Note: using NuGet will try to recursively resolve NuGet.*.resources.dll, so set assembliesResolved right away so that it bypasses everything assembliesResolved = true; var logger = new Logger(); #if STRIDE_NUGET_RESOLVER_UX var dialogNotNeeded = new TaskCompletionSource <bool>(); var dialogClosed = new TaskCompletionSource <bool>(); // Display splash screen after a 500 msec (when NuGet takes some time to restore) var newWindowThread = new Thread(() => { Thread.Sleep(500); if (!dialogNotNeeded.Task.IsCompleted) { var splashScreen = new Stride.NuGetResolver.SplashScreenWindow(); splashScreen.Show(); // Register log logger.SetupLogAction((level, message) => { splashScreen.Dispatcher.InvokeAsync(() => { splashScreen.AppendMessage(level, message); }); }); dialogNotNeeded.Task.ContinueWith(t => { splashScreen.Dispatcher.Invoke(() => splashScreen.Close()); }); splashScreen.Closed += (sender2, e2) => splashScreen.Dispatcher.InvokeShutdown(); System.Windows.Threading.Dispatcher.Run(); splashScreen.Close(); } dialogClosed.SetResult(true); }); newWindowThread.SetApartmentState(ApartmentState.STA); newWindowThread.IsBackground = true; newWindowThread.Start(); #endif var previousSynchronizationContext = SynchronizationContext.Current; try { // Since we execute restore synchronously, we don't want any surprise concerning synchronization context (i.e. Avalonia one doesn't work with this) SynchronizationContext.SetSynchronizationContext(null); // Determine current TFM var framework = Assembly .GetEntryAssembly()? .GetCustomAttribute <TargetFrameworkAttribute>()? .FrameworkName ?? ".NETFramework,Version=v4.7.2"; var nugetFramework = NuGetFramework.ParseFrameworkName(framework, DefaultFrameworkNameProvider.Instance); // Only allow this specific version var versionRange = new VersionRange(new NuGetVersion(packageVersion), true, new NuGetVersion(packageVersion), true); var(request, result) = RestoreHelper.Restore(logger, nugetFramework, "win", packageName, versionRange); if (!result.Success) { throw new InvalidOperationException($"Could not restore NuGet packages"); } assemblies = RestoreHelper.ListAssemblies(result.LockFile); } catch (Exception e) { var logText = $@"Error restoring NuGet packages! ==== Exception details ==== {e} ==== Log ==== {string.Join(Environment.NewLine, logger.Logs.Select(x => $"[{x.Level}] {x.Message}"))} "; #if STRIDE_NUGET_RESOLVER_UX dialogClosed.Task.Wait(); #else // Display log in console Console.WriteLine(logText); #endif Environment.Exit(1); } finally { #if STRIDE_NUGET_RESOLVER_UX dialogNotNeeded.TrySetResult(true); #endif SynchronizationContext.SetSynchronizationContext(previousSynchronizationContext); } } } if (assemblies != null) { var aname = new AssemblyName(eventArgs.Name); if (aname.Name.StartsWith("Microsoft.Build") && aname.Name != "Microsoft.Build.Locator") { return(null); } var assemblyPath = assemblies.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x) == aname.Name); if (assemblyPath != null) { return(Assembly.LoadFrom(assemblyPath)); } } return(null); }; }
public async Task ContentFilesMSBuild_VerifyConditionForFallbackContentItemGroupAsync(string files, 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("contentFiles/any/any/anyMarker.txt"); foreach (var file in files.Split('|')) { packageA.AddFile(file); } 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(); var group = itemGroups.Single(e => e.ToString().Contains("anyMarker.txt")); // Assert Assert.True(result.Success, logger.ShowErrors()); Assert.Equal(expected.Trim(), group.Attribute(XName.Get("Condition")).Value.Trim()); } }
public static IEnumerable <PackageDependency> GetCompatiblePackageDependencies(this IPackageMetadata package, NuGetFramework targetFramework) { IEnumerable <PackageDependencyGroup> compatibleDependencySets; if (targetFramework == null) { compatibleDependencySets = package.DependencySets; } else { throw new NotImplementedException("filter by framework comp"); } // else if (!VersionUtility.TryGetCompatibleItems(targetFramework, package.DependencySets, out compatibleDependencySets)) // { // compatibleDependencySets = new PackageDependencyGroup[0]; // } return(compatibleDependencySets.SelectMany(d => d.Packages)); }
public async Task DependencyGraphRestoreUtility_NoopIsRestoreRequiredAsyncTest() { Debugger.Launch(); // Arrange var projectName = "testproj"; var logger = new TestLogger(); using (var rootFolder = TestDirectory.Create()) { var projectFolder = new DirectoryInfo(Path.Combine(rootFolder, projectName)); projectFolder.Create(); var projectConfig = new FileInfo(Path.Combine(projectFolder.FullName, "testproj.project.json")); var msbuildProjectPath = new FileInfo(Path.Combine(projectFolder.FullName, $"{projectName}.csproj")); BuildIntegrationTestUtility.CreateConfigJson(projectConfig.FullName); var projectTargetFramework = NuGetFramework.Parse("uap10.0"); var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext()); var project = new ProjectJsonNuGetProject(projectConfig.FullName, msbuildProjectPath.FullName); var restoreContext = new DependencyGraphCacheContext(logger, NullSettings.Instance); var projects = new List <IDependencyGraphProject>() { project }; var solutionManager = new TestSolutionManager(false); solutionManager.NuGetProjects.Add(project); var sources = new[] { Repository.Factory.GetVisualStudio(new PackageSource("https://www.nuget.org/api/v2/")) }; // Act await DependencyGraphRestoreUtility.RestoreAsync( solutionManager, restoreContext, new RestoreCommandProvidersCache(), (c) => { }, sources, false, await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(solutionManager, restoreContext), logger, CancellationToken.None); var pathContext = NuGetPathContext.Create(NullSettings.Instance); //var oldHash = restoreContext.SolutionSpecHash; //var newContext = new DependencyGraphCacheContext(logger, NullSettings.Instance); //// Act //var result = await DependencyGraphRestoreUtility.IsRestoreRequiredAsync( // solutionManager, // forceRestore: false, // pathContext: pathContext, // cacheContext: newContext, // oldDependencyGraphSpecHash: oldHash); //// Assert //Assert.Equal(false, result); Assert.Equal(0, logger.Errors); Assert.Equal(0, logger.Warnings); Assert.Equal(2, logger.MinimalMessages.Count); } }
public SupportFramework(NuGetFramework framework) { Framework = framework; RuntimeIds = s_nullRidList; }
public static async Task <RemoteMatch> FindLibraryMatchAsync( LibraryRange libraryRange, NuGetFramework framework, GraphEdge <RemoteResolveResult> outerEdge, IEnumerable <IRemoteDependencyProvider> remoteProviders, IEnumerable <IRemoteDependencyProvider> localProviders, IEnumerable <IDependencyProvider> projectProviders, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken) { var projectMatch = await FindProjectMatchAsync(libraryRange, framework, outerEdge, projectProviders, cancellationToken); if (projectMatch != null) { return(projectMatch); } if (libraryRange.VersionRange == null) { return(null); } // The resolution below is only for package types if (!libraryRange.TypeConstraintAllows(LibraryDependencyTarget.Package)) { return(null); } if (libraryRange.VersionRange.IsFloating) { // For snapshot dependencies, get the version remotely first. var remoteMatch = await FindLibraryByVersionAsync(libraryRange, framework, remoteProviders, cacheContext, logger, cancellationToken); if (remoteMatch != null) { // Try to see if the specific version found on the remote exists locally. This avoids any unnecessary // remote access incase we already have it in the cache/local packages folder. var localMatch = await FindLibraryByVersionAsync(remoteMatch.Library, framework, localProviders, cacheContext, logger, cancellationToken); if (localMatch != null && localMatch.Library.Version.Equals(remoteMatch.Library.Version)) { // If we have a local match, and it matches the version *exactly* then use it. return(localMatch); } // We found something locally, but it wasn't an exact match // for the resolved remote match. } return(remoteMatch); } else { // Check for the specific version locally. var localMatch = await FindLibraryByVersionAsync(libraryRange, framework, localProviders, cacheContext, logger, cancellationToken); if (localMatch != null && localMatch.Library.Version.Equals(libraryRange.VersionRange.MinVersion)) { // We have an exact match so use it. return(localMatch); } // Either we found a local match but it wasn't the exact version, or // we didn't find a local match. var remoteMatch = await FindLibraryByVersionAsync(libraryRange, framework, remoteProviders, cacheContext, logger, cancellationToken); if (remoteMatch != null && localMatch == null) { // There wasn't any local match for the specified version but there was a remote match. // See if that version exists locally. localMatch = await FindLibraryByVersionAsync(remoteMatch.Library, framework, remoteProviders, cacheContext, logger, cancellationToken); } if (localMatch != null && remoteMatch != null) { // We found a match locally and remotely, so pick the better version // in relation to the specified version. if (libraryRange.VersionRange.IsBetter( current: localMatch.Library.Version, considering: remoteMatch.Library.Version)) { return(remoteMatch); } else { return(localMatch); } } // Prefer local over remote generally. return(localMatch ?? remoteMatch); } }
private static void Run(CommandLineApplication cmd, ILogger log) { cmd.Description = "Add empty dependency groups or remove dependencies from existing groups."; var idFilter = cmd.Option(Constants.IdFilterTemplate, Constants.IdFilterDesc, CommandOptionType.SingleValue); var versionFilter = cmd.Option(Constants.VersionFilterTemplate, Constants.VersionFilterDesc, CommandOptionType.SingleValue); var excludeSymbolsFilter = cmd.Option(Constants.ExcludeSymbolsTemplate, Constants.ExcludeSymbolsDesc, CommandOptionType.NoValue); var highestVersionFilter = cmd.Option(Constants.HighestVersionFilterTemplate, Constants.HighestVersionFilterDesc, CommandOptionType.NoValue); var frameworkOption = cmd.Option(Constants.FrameworkOptionTemplate, Constants.FrameworkOptionDesc, CommandOptionType.MultipleValue); var argRoot = cmd.Argument( "[root]", Constants.MultiplePackagesRootDesc, multipleValues: true); cmd.HelpOption(Constants.HelpOption); var required = new List <CommandOption>() { frameworkOption }; cmd.OnExecute(() => { try { var inputs = argRoot.Values; if (inputs.Count < 1) { inputs.Add(Directory.GetCurrentDirectory()); } // Validate parameters foreach (var requiredOption in required) { if (!requiredOption.HasValue()) { throw new ArgumentException($"Missing required parameter --{requiredOption.LongName}."); } } var frameworks = new HashSet <NuGetFramework>(); if (frameworkOption.HasValue()) { foreach (var option in frameworkOption.Values) { var fw = NuGetFramework.Parse(option); log.LogInformation($"adding empty dependency groups for {fw.GetShortFolderName()}"); frameworks.Add(fw); } } var packages = Util.GetPackagesWithFilter(idFilter, versionFilter, excludeSymbolsFilter, highestVersionFilter, inputs.ToArray()); foreach (var package in packages) { log.LogMinimal($"processing {package}"); // Get nuspec file path string nuspecPath = null; XDocument nuspecXml = null; using (var packageReader = new PackageArchiveReader(package)) { nuspecPath = packageReader.GetNuspecFile(); nuspecXml = XDocument.Load(packageReader.GetNuspec()); } var metadata = Util.GetMetadataElement(nuspecXml); var ns = metadata.GetDefaultNamespace().NamespaceName; var dependenciesNode = metadata.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("dependencies", StringComparison.OrdinalIgnoreCase)); if (dependenciesNode == null) { dependenciesNode = new XElement(XName.Get("dependencies", ns)); metadata.Add(dependenciesNode); } // Convert non-grouped to group var rootDeps = dependenciesNode.Elements() .Where(e => e.Name.LocalName.Equals("dependency", StringComparison.OrdinalIgnoreCase)) .ToArray(); if (rootDeps.Length > 1) { var anyGroup = new XElement(XName.Get("group", ns)); dependenciesNode.AddFirst(anyGroup); foreach (var rootDep in rootDeps) { rootDep.Remove(); anyGroup.Add(rootDep); } } // Remove existing groups foreach (var node in dependenciesNode.Elements() .Where(e => e.Name.LocalName.Equals("group", StringComparison.OrdinalIgnoreCase)) .ToArray()) { var groupFramework = NuGetFramework.AnyFramework; var tfm = node.Attribute(XName.Get("targetFramework"))?.Value; if (!string.IsNullOrEmpty(tfm)) { groupFramework = NuGetFramework.Parse(tfm); } if (frameworks.Remove(groupFramework)) { foreach (var child in node.Elements().ToArray()) { child.Remove(); } } } // Add empty groups for those remaining foreach (var fw in frameworks) { var groupNode = DependenciesUtil.CreateGroupNode(ns, fw); dependenciesNode.Add(groupNode); } // Update zip Util.AddOrReplaceZipEntry(package, nuspecPath, nuspecXml, log); } return(0); } catch (Exception ex) { log.LogError(ex.Message); log.LogDebug(ex.ToString()); } return(1); }); }
public void PackagesConfigWriter_Duplicate() { var stream = new MemoryStream(); using (PackagesConfigWriter writer = new PackagesConfigWriter(stream)) { writer.WritePackageEntry("packageA", NuGetVersion.Parse("1.0.1"), NuGetFramework.Parse("net45")); Assert.Throws <PackagingException>(() => writer.WritePackageEntry("packageA", NuGetVersion.Parse("2.0.1"), NuGetFramework.Parse("net4"))); } }
public FrameworkInfo(NuGetFramework framework, IList <string> dependencies) { Framework = framework; Dependencies = new ReadOnlyCollection <string>(dependencies); }
/// <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, 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); // Old version expects to be installed in GamePackages if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0) && oldRootDirectory != null) { installPath = oldRootDirectory; } var specPath = Path.Combine("TestProject", "project.json"); var spec = new PackageSpec() { Name = "TestProject", // make sure this package never collides with a dependency FilePath = specPath, Dependencies = new List <LibraryDependency>() { new LibraryDependency { LibraryRange = new LibraryRange(packageId, new VersionRange(version.ToNuGetVersion()), LibraryDependencyTarget.Package), } }, TargetFrameworks = { new TargetFrameworkInformation { FrameworkName = NuGetFramework.Parse("net472"), } }, }; using (var context = new SourceCacheContext()) { context.IgnoreFailedSources = true; var provider = RestoreCommandProviders.Create(installPath, new List <string>(), sourceRepositoryProvider.GetRepositories(), context, new LocalPackageFileCache(), NativeLogger); var request = new RestoreRequest(spec, provider, context, null, NativeLogger) { //RequestedRuntimes = { "win7-d3d11" }, ProjectStyle = ProjectStyle.DotnetCliTool, }; var command = new RestoreCommand(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; } } }
public async Task <InternalNuGetCompatibilityResult> CheckCompatibilityAsync(string packageName, string version, string targetFramework, IEnumerable <SourceRepository> internalRepositories) { if (packageName == null || targetFramework == null || internalRepositories == null) { var invalidParamNames = new List <string>(); if (packageName == null) { invalidParamNames.Add(nameof(packageName)); } if (targetFramework == null) { invalidParamNames.Add(nameof(targetFramework)); } if (internalRepositories == null) { invalidParamNames.Add(nameof(internalRepositories)); } throw new ArgumentException($"Invalid parameter(s) found. The following parameters " + $"cannot be null: {string.Join(", ", invalidParamNames)}"); } string tmpPath = Path.GetTempPath(); var framework = NuGetFramework.Parse(targetFramework); var package = new PackageIdentity(packageName, NuGetVersion.Parse(version)); // Get package information from Nuget SourcePackageDependencyInfo packageSource = null; foreach (var sourceRepository in internalRepositories) { var dependencyInfoResource = await sourceRepository.GetResourceAsync <DependencyInfoResource>(); packageSource = await dependencyInfoResource.ResolvePackage( package, framework, _cacheContext, NullLogger.Instance, CancellationToken.None); if (packageSource != null) { break; } } if (packageSource == null) { var errorMessage = $"Error: No package source found for {package}."; _logger.LogError(errorMessage); var innerException = new PackageSourceNotFoundException(errorMessage); throw new PortingAssistantClientException(ExceptionMessage.PackageSourceNotFound(package), innerException); } // Download package var downloadResource = await packageSource.Source.GetResourceAsync <DownloadResource>(); var downloadResult = await downloadResource.GetDownloadResourceResultAsync( packageSource, new PackageDownloadContext(_cacheContext), Path.Combine(tmpPath), NullLogger.Instance, CancellationToken.None); var packageReader = downloadResult.PackageReader; var nuspecReader = packageReader.NuspecReader; var dependencies = nuspecReader.GetDependencyGroups(); var dependencyPackages = dependencies .SelectMany(d => d.Packages) .Select(p => p.Id) .ToList(); // Gather dlls var frameworkReducer = new FrameworkReducer(); var libItems = packageReader.GetLibItems(); var nearestTargetFrameworks = libItems .Select(li => frameworkReducer.GetNearest( framework, new List <NuGetFramework> { li.TargetFramework })) .ToList(); var isCompatible = libItems.Any() ? nearestTargetFrameworks.Any(nugetFramework => nugetFramework != null) : frameworkReducer.GetNearest(framework, packageReader.GetSupportedFrameworks()) != null; var compatibleDlls = libItems .Where(li => nearestTargetFrameworks.Contains(li.TargetFramework)) .SelectMany(li => li.Items) .Where(s => s.EndsWith("dll", StringComparison.OrdinalIgnoreCase)) .ToList(); var incompatibleDlls = libItems .SelectMany(li => li.Items) .Where(s => !compatibleDlls.Contains(s) && s.EndsWith("dll", StringComparison.OrdinalIgnoreCase)) .ToList(); return(new InternalNuGetCompatibilityResult { IncompatibleDlls = incompatibleDlls, CompatibleDlls = compatibleDlls, IsCompatible = isCompatible, DependencyPackages = dependencyPackages, Source = packageSource.Source.PackageSource.Name }); }
public IQueryable <V2FeedPackage> GetUpdates( string packageIds, string versions, bool includePrerelease, bool includeAllVersions, string targetFrameworks, string versionConstraints) { if (String.IsNullOrEmpty(packageIds) || String.IsNullOrEmpty(versions)) { return(Enumerable.Empty <V2FeedPackage>().AsQueryable()); } // Workaround https://github.com/NuGet/NuGetGallery/issues/674 for NuGet 2.1 client. Can probably eventually be retired (when nobody uses 2.1 anymore...) // Note - it was URI un-escaping converting + to ' ', undoing that is actually a pretty conservative substitution because // space characters are never acepted as valid by VersionUtility.ParseFrameworkName. if (!string.IsNullOrEmpty(targetFrameworks)) { targetFrameworks = targetFrameworks.Replace(' ', '+'); } var idValues = packageIds.Trim().ToLowerInvariant().Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var versionValues = versions.Trim().Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var targetFrameworkValues = String.IsNullOrEmpty(targetFrameworks) ? null : targetFrameworks.Split('|').Select(tfx => NuGetFramework.Parse(tfx)).ToList(); var versionConstraintValues = String.IsNullOrEmpty(versionConstraints) ? new string[idValues.Length] : versionConstraints.Split('|'); if (idValues.Length == 0 || idValues.Length != versionValues.Length || idValues.Length != versionConstraintValues.Length) { // Exit early if the request looks invalid return(Enumerable.Empty <V2FeedPackage>().AsQueryable()); } var versionLookup = idValues.Select((id, i) => { NuGetVersion currentVersion; if (NuGetVersion.TryParse(versionValues[i], out currentVersion)) { VersionRange versionConstraint = null; if (versionConstraintValues[i] != null) { if (!VersionRange.TryParse(versionConstraintValues[i], out versionConstraint)) { versionConstraint = null; } } return(Tuple.Create(id, Tuple.Create(currentVersion, versionConstraint))); } return(null); }) .Where(t => t != null) .ToLookup(t => t.Item1, t => t.Item2, StringComparer.OrdinalIgnoreCase); var packages = PackageRepository.GetAll() .Include(p => p.PackageRegistration) .Include(p => p.SupportedFrameworks) .Where(p => !p.Deleted && p.Listed && (includePrerelease || !p.IsPrerelease) && idValues.Contains(p.PackageRegistration.Id.ToLower())) .OrderBy(p => p.PackageRegistration.Id); return(GetUpdates(packages, versionLookup, targetFrameworkValues, includeAllVersions).AsQueryable() .ToV2FeedPackageQuery(GetSiteRoot(), Configuration.Features.FriendlyLicenses)); }
public async Task Restore_PackageNamespace_Fails() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages"); var externalRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ExternalRepository"); Directory.CreateDirectory(externalRepositoryPath); var contosoRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ContosoRepository"); Directory.CreateDirectory(contosoRepositoryPath); var configPath = Path.Combine(pathContext.WorkingDirectory, "nuget.config"); SettingsTestUtils.CreateConfigurationFile(configPath, $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <packageSources> <!--To inherit the global NuGet package sources remove the <clear/> line below --> <clear /> <add key=""ExternalRepository"" value=""{externalRepositoryPath}"" /> <add key=""ContosoRepository"" value=""{contosoRepositoryPath}"" /> </packageSources> <packageNamespaces> <packageSource key=""ExternalRepository""> <namespace id=""External.*"" /> <namespace id=""Others.*"" /> </packageSource> <packageSource key=""ContosoRepository""> <namespace id=""Contoso.*"" /> <!--Contoso.A package doesn't exist Contoso repository, so restore should fail--> <namespace id=""Test.*"" /> </packageSource> </packageNamespaces> </configuration>"); var ExternalA = new SimpleTestPackageContext() { Id = "Contoso.A", // Initial version had package id conflict with Contoso repository Version = "1.0.0" }; ExternalA.AddFile("lib/net461/externalA.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( externalRepositoryPath, PackageSaveMode.Defaultv3, ExternalA); var ExternalB = new SimpleTestPackageContext() { Id = "External.B", // name conflict resolved. Version = "2.0.0" }; ExternalB.AddFile("lib/net461/externalB.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( externalRepositoryPath, PackageSaveMode.Defaultv3, ExternalB); Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config", @"<packages> <package id=""Contoso.A"" version=""1.0.0"" targetFramework=""net461"" /> <package id=""External.B"" version=""2.0.0"" targetFramework=""net461"" /> </packages>"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); // Act var result = RunRestore(pathContext, _failureExitCode); // Assert Assert.Contains("Unable to find version '1.0.0' of package 'Contoso.A'", result.Errors); } }
private void AddFrameworks(RuntimeOptions runtimeOptions, ProjectContext.RuntimeFramework[] runtimeFrameworks, LockFileTargetLibrary lockFilePlatformLibrary, bool isFrameworkDependent) { runtimeOptions.Tfm = NuGetFramework.Parse(TargetFrameworkMoniker).GetShortFolderName(); var frameworks = new List <RuntimeConfigFramework>(); if (runtimeFrameworks == null || runtimeFrameworks.Length == 0) { // If the project is not targetting .NET Core, it will not have any platform library (and is marked as non-FrameworkDependent). if (lockFilePlatformLibrary != null) { // If there are no RuntimeFrameworks (which would be set in the ProcessFrameworkReferences task based // on FrameworkReference items), then use package resolved from MicrosoftNETPlatformLibrary for // the runtimeconfig RuntimeConfigFramework framework = new RuntimeConfigFramework(); framework.Name = lockFilePlatformLibrary.Name; framework.Version = lockFilePlatformLibrary.Version.ToNormalizedString(); frameworks.Add(framework); } } else { HashSet <string> usedFrameworkNames = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (var platformLibrary in runtimeFrameworks) { if (runtimeFrameworks.Length > 1 && platformLibrary.Name.Equals("Microsoft.NETCore.App", StringComparison.OrdinalIgnoreCase) && isFrameworkDependent) { // If there are multiple runtime frameworks, then exclude Microsoft.NETCore.App, // as a workaround for https://github.com/dotnet/core-setup/issues/4947 // The workaround only applies to normal framework references, included frameworks // (in self-contained apps) must list all frameworks. continue; } // Don't add multiple entries for the same shared framework. // This is necessary if there are FrameworkReferences to different profiles // that map to the same shared framework. if (!usedFrameworkNames.Add(platformLibrary.Name)) { continue; } RuntimeConfigFramework framework = new RuntimeConfigFramework(); framework.Name = platformLibrary.Name; framework.Version = platformLibrary.Version; frameworks.Add(framework); } } if (isFrameworkDependent) { runtimeOptions.RollForward = RollForward; // If there is only one runtime framework, then it goes in the framework property of the json // If there are multiples, then we leave the framework property unset and put the list in // the frameworks property. if (frameworks.Count == 1) { runtimeOptions.Framework = frameworks[0]; } else { runtimeOptions.Frameworks = frameworks; } } else if (WriteIncludedFrameworks) { // Self-contained apps don't have framework references, instead write the frameworks // into the includedFrameworks property. runtimeOptions.IncludedFrameworks = frameworks; } }
public async Task Restore_LegacyPackagesConfig_WithNuGetLockFileLockedMode() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/net461/x.dll"); var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageY.Files.Clear(); packageY.AddFile("lib/net461/y.dll"); Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config", @"<packages> <package id=""x"" version=""1.0.0"" targetFramework=""net461"" /> </packages>"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); // Restore to set up lock file var result = RunRestore(pathContext, _successExitCode, "-UseLockFile"); Assert.True(File.Exists(projectA.NuGetLockFileOutputPath)); // Change packages to cause lock file difference Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config", @"<packages> <package id=""y"" version=""1.0.0"" targetFramework=""net461"" /> </packages>"); // Act result = RunRestore(pathContext, _failureExitCode, "-UseLockFile", "-LockedMode"); // Assert Assert.Contains("NU1004:", result.Errors); } }
// Thread safe fetch for the target only, no child dependencies private async Task Ensure(NuGet.Packaging.Core.PackageDependency target, NuGetFramework projectFramework, bool includePrerelease, CancellationToken token) { object lockObj = _lockObjsById.GetOrAdd(target.Id, new object()); // lock per package Id lock (lockObj) { VersionRange alreadySearched = null; if (!_rangeSearched.TryGetValue(target.Id, out alreadySearched)) { alreadySearched = EmptyRange; } if (alreadySearched == null || !target.VersionRange.IsSubSetOrEqualTo(alreadySearched)) { // find what we haven't checked already var needed = NeededRange(alreadySearched, target.VersionRange); // adjust prerelease, is this needed? needed = ModifyRange(needed, includePrerelease); if (!_versionRangeComparer.Equals(needed, EmptyRange)) { // server search IEnumerable <IPackage> repoPackages = null; if (_useFindById) { // Ranges fail in some cases for local repos, to work around this just collect every // version of the package to filter later repoPackages = V2Client.FindPackagesById(target.Id); } else { // DataService Repository repoPackages = V2Client.FindPackages(target.Id, GetVersionSpec(needed), includePrerelease, false); } List <VersionRange> currentRanges = new List <VersionRange>(); currentRanges.Add(target.VersionRange); if (alreadySearched != null) { currentRanges.Add(alreadySearched); } // update the already searched range VersionRange combined = null; if (_useFindById) { // for local repos we found all possible versions combined = VersionRange.All; } else { // for non-local repos find the real range combined = VersionRange.Combine(currentRanges); } _rangeSearched.AddOrUpdate(target.Id, combined, (k, v) => combined); HashSet <PackageDependencyInfo> foundPackages = null; // add everything to found if (!_found.TryGetValue(target.Id, out foundPackages)) { foundPackages = new HashSet <PackageDependencyInfo>(PackageIdentity.Comparer); _found.TryAdd(target.Id, foundPackages); } // add current packages to found IEnumerable <PackageDependencyInfo> packageVersions = repoPackages.Select(p => CreateDependencyInfo(p, projectFramework)); foundPackages.UnionWith(packageVersions); } } } }
public async Task Restore_LegacyPackageReference_SkipBuildTransitive() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageY.Files.Clear(); packageY.AddFile("lib/net461/y.dll"); packageY.AddFile("build/y.targets"); packageY.AddFile("buildCrossTargeting/y.targets"); packageY.AddFile("build/y.props"); packageY.AddFile("buildCrossTargeting/y.props"); packageY.AddFile("buildTransitive/y.targets"); packageY.Exclude = "buildTransitive"; var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/net461/x.dll"); packageX.Dependencies.Add(packageY); projectA.AddPackageToAllFrameworks(packageX); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); // Act var result = RunRestore(pathContext); // Assert var assetsFile = projectA.AssetsFile; Assert.NotNull(assetsFile); foreach (var target in assetsFile.Targets) { var library = target.Libraries.FirstOrDefault(lib => lib.Name.Equals("y")); Assert.NotNull(library); Assert.False(library.Build.Any(build => build.Path.Equals("buildTransitive/y.targets"))); Assert.False(library.Build.Any(build => build.Path.Equals("build/y.props"))); } } }
/// <summary> /// Recursive package dependency info gather /// </summary> private async Task <IEnumerable <PackageDependencyInfo> > Seek(NuGet.Packaging.Core.PackageDependency target, NuGetFramework projectFramework, bool includePrerelease, IEnumerable <string> parents, CancellationToken token) { // check if we are cancelled token.ThrowIfCancellationRequested(); List <PackageDependencyInfo> results = new List <PackageDependencyInfo>(); // circular dependency check protection if (!parents.Contains(target.Id, StringComparer.OrdinalIgnoreCase)) { await Ensure(target, projectFramework, includePrerelease, token); var packages = Get(target, includePrerelease); results.AddRange(packages); // combine all version ranges found for an id into a single range var toSeek = packages.SelectMany(g => g.Dependencies).GroupBy(d => d.Id, StringComparer.OrdinalIgnoreCase) .OrderBy(d => d.Key) .Select(g => new NuGet.Packaging.Core.PackageDependency(g.Key, VersionRange.Combine(g.Select(d => d.VersionRange)))); // recurse Stack <Task <IEnumerable <PackageDependencyInfo> > > tasks = new Stack <Task <IEnumerable <PackageDependencyInfo> > >(); foreach (NuGet.Packaging.Core.PackageDependency dep in toSeek) { // run tasks on another thread var task = Task.Run(async() => await Seek(dep, projectFramework, includePrerelease, parents.Concat(new string[] { target.Id }), token)); tasks.Push(task); } // add child dep results foreach (var task in tasks) { results.AddRange(await task); } } return(results); }
public async Task Restore_LegacyPackageReference_WithNuGetLockFilePath() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = "net461"; var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, NuGetFramework.Parse(net461)); var projectB = SimpleTestProjectContext.CreateLegacyPackageReference( "b", pathContext.SolutionRoot, NuGetFramework.Parse(net461)); // set up packages var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile($"lib/{0}/x.dll", net461); var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageY.Files.Clear(); packageY.AddFile($"lib/{0}/y.dll", net461); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); // set up projects and solution projectB.AddPackageToAllFrameworks(packageY); projectA.Properties.Add("RestorePackagesWithLockFile", "true"); var packagesLockFilePath = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "packages.custom.lock.json"); projectA.Properties.Add("NuGetLockFilePath", packagesLockFilePath); projectA.AddProjectToAllFrameworks(projectB); projectA.AddPackageToAllFrameworks(packageX); solution.Projects.Add(projectA); solution.Projects.Add(projectB); solution.Create(pathContext.SolutionRoot); // Act var result = RunRestore(pathContext); // Assert Assert.True(File.Exists(projectA.NuGetLockFileOutputPath)); Assert.Equal(packagesLockFilePath, projectA.NuGetLockFileOutputPath); var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath); Assert.Equal(4, lockFile.Targets.Count); var targets = lockFile.Targets.Where(t => t.Dependencies.Count > 0).ToList(); Assert.Equal(1, targets.Count); Assert.Equal(".NETFramework,Version=v4.6.1", targets[0].Name); Assert.Equal(3, targets[0].Dependencies.Count); Assert.Equal("x", targets[0].Dependencies[0].Id); Assert.Equal(PackageDependencyType.Direct, targets[0].Dependencies[0].Type); Assert.Equal("y", targets[0].Dependencies[1].Id); Assert.Equal(PackageDependencyType.Transitive, targets[0].Dependencies[1].Type); Assert.Equal("b", targets[0].Dependencies[2].Id); Assert.Equal(PackageDependencyType.Project, targets[0].Dependencies[2].Type); } }
private static NuGetFramework GetNuGetFrameworkFromTargetGraph(string targetGraph) { var parts = targetGraph.Split('/'); return(NuGetFramework.Parse(parts[0])); }
public async Task Restore_WithLockedModeAndNoObjFolder_RestoreFailsAndWritesOutRestoreResultFiles() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/net461/a.dll"); var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageY.Files.Clear(); packageY.AddFile("lib/net461/y.dll"); projectA.AddPackageToAllFrameworks(packageX); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); var result = RunRestore(pathContext, _successExitCode, "-UseLockFile"); Assert.True(result.Success); Assert.True(File.Exists(projectA.NuGetLockFileOutputPath)); var originalPackagesLockFileWriteTime = new FileInfo(projectA.NuGetLockFileOutputPath).LastWriteTimeUtc; projectA.AddPackageToAllFrameworks(packageY); projectA.Save(); // Remove old obj folders. Directory.Delete(Path.GetDirectoryName(projectA.AssetsFileOutputPath), recursive: true); // Act result = RunRestore(pathContext, _failureExitCode, "-LockedMode"); // Assert Assert.Contains("NU1004:", result.Errors); var logCodes = projectA.AssetsFile.LogMessages.Select(e => e.Code); Assert.Contains(NuGetLogCode.NU1004, logCodes); var ridlessMainTarget = projectA.AssetsFile.Targets.FirstOrDefault(e => string.IsNullOrEmpty(e.RuntimeIdentifier)); Assert.Equal(net461, ridlessMainTarget.TargetFramework); Assert.True(File.Exists(projectA.PropsOutput)); Assert.True(File.Exists(projectA.TargetsOutput)); Assert.True(File.Exists(projectA.CacheFileOutputPath)); var packagesLockFileWriteTime = new FileInfo(projectA.NuGetLockFileOutputPath).LastWriteTimeUtc; packagesLockFileWriteTime.Should().Be(originalPackagesLockFileWriteTime, because: "Locked mode must not overwrite the lock file"); } }
public void LockFile_ConsidersEquivalentPackageSpec() { // Arrange Func <LockFile> getLockFile = () => { var lockFile = new LockFile { Version = 2, PackageSpec = new PackageSpec(new[] { new TargetFrameworkInformation { FrameworkName = FrameworkConstants.CommonFrameworks.NetCoreApp10, Dependencies = new[] { new LibraryDependency { LibraryRange = new LibraryRange( "Microsoft.NETCore.App", new VersionRange( minVersion: new NuGetVersion("1.0.1"), originalString: "1.0.1"), LibraryDependencyTarget.Package) }, new LibraryDependency { LibraryRange = new LibraryRange( "Microsoft.NET.Sdk", new VersionRange( minVersion: new NuGetVersion("1.0.0-alpha-20161104-2"), originalString: "1.0.0-alpha-20161104-2"), LibraryDependencyTarget.Package), SuppressParent = LibraryIncludeFlags.All } } } }) { Version = new NuGetVersion("1.0.0"), RestoreMetadata = new ProjectRestoreMetadata { ProjectUniqueName = @"X:\ProjectPath\ProjectPath.csproj", ProjectName = "ProjectPath", ProjectPath = @"X:\ProjectPath\ProjectPath.csproj", OutputPath = @"X:\ProjectPath\obj\", ProjectStyle = ProjectStyle.PackageReference, OriginalTargetFrameworks = new[] { "netcoreapp1.0" }, TargetFrameworks = new List <ProjectRestoreMetadataFrameworkInfo> { new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("netcoreapp1.0")) } } } }; return(lockFile); }; var self = getLockFile(); var other = getLockFile(); // Act & Assert Assert.NotSame(self, other); Assert.Equal(self, other); }
public async Task Restore_PackageNamespace_Succeed() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages"); var externalRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ExternalRepository"); Directory.CreateDirectory(externalRepositoryPath); var contosoRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ContosoRepository"); Directory.CreateDirectory(contosoRepositoryPath); var configPath = Path.Combine(pathContext.WorkingDirectory, "nuget.config"); SettingsTestUtils.CreateConfigurationFile(configPath, $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <packageSources> <!--To inherit the global NuGet package sources remove the <clear/> line below --> <clear /> <add key=""ExternalRepository"" value=""{externalRepositoryPath}"" /> <add key=""ContosoRepository"" value=""{contosoRepositoryPath}"" /> </packageSources> <packageNamespaces> <packageSource key=""externalRepository""> <namespace id=""External.*"" /> <namespace id=""Others.*"" /> </packageSource> <packageSource key=""contosoRepository""> <namespace id=""Contoso.*"" /> <namespace id=""Test.*"" /> </packageSource> </packageNamespaces> </configuration>"); var ContosoReal = new SimpleTestPackageContext() { Id = "Contoso.A", Version = "1.0.0" }; ContosoReal.AddFile("lib/net461/contosoA.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( contosoRepositoryPath, PackageSaveMode.Defaultv3, ContosoReal); var ExternalA = new SimpleTestPackageContext() { Id = "Contoso.A", // Initial version had package id conflict with Contoso repository Version = "1.0.0" }; ExternalA.AddFile("lib/net461/externalA.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( externalRepositoryPath, PackageSaveMode.Defaultv3, ExternalA); var ExternalB = new SimpleTestPackageContext() { Id = "External.B", // name conflict resolved. Version = "2.0.0" }; ExternalB.AddFile("lib/net461/externalB.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( externalRepositoryPath, PackageSaveMode.Defaultv3, ExternalB); Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config", @"<packages> <package id=""Contoso.A"" version=""1.0.0"" targetFramework=""net461"" /> <package id=""External.B"" version=""2.0.0"" targetFramework=""net461"" /> </packages>"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); // Act var result = RunRestore(pathContext, _successExitCode); // Assert var contosoRestorePath = Path.Combine(projectAPackages, ContosoReal.ToString(), ContosoReal.ToString() + ".nupkg"); using (var nupkgReader = new PackageArchiveReader(contosoRestorePath)) { var allFiles = nupkgReader.GetFiles().ToList(); // Assert correct Contoso package from Contoso repository was restored. Assert.Contains("lib/net461/contosoA.dll", allFiles); } var externalRestorePath = Path.Combine(projectAPackages, ExternalB.ToString(), ExternalB.ToString() + ".nupkg"); Assert.True(File.Exists(externalRestorePath)); } }
public void LockFile_ConsidersLockFilesWithLogsWithDifferentMessagesAsDifferent() { // Arrange Func <LockFile> getLockFile = () => { var lockFile = new LockFile { Version = 3, PackageSpec = new PackageSpec(new[] { new TargetFrameworkInformation { FrameworkName = FrameworkConstants.CommonFrameworks.NetCoreApp10, Dependencies = new[] { new LibraryDependency { LibraryRange = new LibraryRange( "Microsoft.NETCore.App", new VersionRange( minVersion: new NuGetVersion("1.0.1"), originalString: "1.0.1"), LibraryDependencyTarget.Package) }, new LibraryDependency { LibraryRange = new LibraryRange( "Microsoft.NET.Sdk", new VersionRange( minVersion: new NuGetVersion("1.0.0-alpha-20161104-2"), originalString: "1.0.0-alpha-20161104-2"), LibraryDependencyTarget.Package), SuppressParent = LibraryIncludeFlags.All } } } }) { Version = new NuGetVersion("1.0.0"), RestoreMetadata = new ProjectRestoreMetadata { ProjectUniqueName = @"X:\ProjectPath\ProjectPath.csproj", ProjectName = "ProjectPath", ProjectPath = @"X:\ProjectPath\ProjectPath.csproj", OutputPath = @"X:\ProjectPath\obj\", ProjectStyle = ProjectStyle.PackageReference, OriginalTargetFrameworks = new[] { "netcoreapp1.0" }, TargetFrameworks = new List <ProjectRestoreMetadataFrameworkInfo> { new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("netcoreapp1.0")) } } } }; return(lockFile); }; var self = getLockFile(); var other = getLockFile(); self.LogMessages = new List <IAssetsLogMessage> { new AssetsLogMessage(LogLevel.Error, NuGetLogCode.NU1000, "test error message"), new AssetsLogMessage(LogLevel.Warning, NuGetLogCode.NU1500, "test warning message") { WarningLevel = WarningLevel.Severe }, }; other.LogMessages = new List <IAssetsLogMessage> { new AssetsLogMessage(LogLevel.Error, NuGetLogCode.NU1000, "test different error message"), new AssetsLogMessage(LogLevel.Warning, NuGetLogCode.NU1500, "test warning message") { WarningLevel = WarningLevel.Severe }, }; // Act & Assert Assert.NotSame(self, other); Assert.NotEqual(self, other); }
public PublishCommand WithFramework(NuGetFramework framework) { return(WithFramework(framework.GetShortFolderName())); }