public static void ModifyBuildOptions(PackageSpec packageSpec) { packageSpec.BuildOptions.OutputName = Guid.NewGuid().ToString(); }
public static void ModifyAuthors(PackageSpec packageSpec) { packageSpec.Authors[0] = "NewAuthor"; }
public static void ModifyOriginalTargetFrameworkInformationEdit(PackageSpec packageSpec) { packageSpec.TargetFrameworks[0].Imports.Add(NuGetFramework.Parse("net461")); }
public void DependencyGraphSpec_RoundTripMSBuildMetadata() { // Arrange var frameworks = new List <TargetFrameworkInformation>(); frameworks.Add(new TargetFrameworkInformation() { FrameworkName = NuGetFramework.Parse("net45") }); var spec = new PackageSpec(frameworks); spec.Version = NuGetVersion.Parse("24.5.1.2-alpha.1.2+a.b.c"); var msbuildMetadata = new ProjectRestoreMetadata(); spec.RestoreMetadata = msbuildMetadata; msbuildMetadata.ProjectUniqueName = "A55205E7-4D08-4672-8011-0925467CC45F"; msbuildMetadata.ProjectPath = "c:\\x\\x.csproj"; msbuildMetadata.ProjectName = PackageSpecName; msbuildMetadata.ProjectJsonPath = "c:\\x\\project.json"; msbuildMetadata.ProjectStyle = ProjectStyle.PackageReference; msbuildMetadata.PackagesPath = "c:\\packages"; msbuildMetadata.Sources = new[] { new PackageSource("https://api.nuget.org/v3/index.json") }; var tfmGroup = new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45")); msbuildMetadata.TargetFrameworks.Add(tfmGroup); tfmGroup.ProjectReferences.Add(new ProjectRestoreReference() { ProjectUniqueName = "44B29B8D-8413-42D2-8DF4-72225659619B", ProjectPath = "c:\\a\\a.csproj" }); tfmGroup.ProjectReferences.Add(new ProjectRestoreReference() { ProjectUniqueName = "78A6AD3F-9FA5-47F6-A54E-84B46A48CB2F", ProjectPath = "c:\\b\\b.csproj" }); msbuildMetadata.FallbackFolders.Add("c:\\fallback1"); msbuildMetadata.FallbackFolders.Add("c:\\fallback2"); msbuildMetadata.ConfigFilePaths.Add("c:\\nuget.config"); msbuildMetadata.ConfigFilePaths.Add("d:\\nuget.config"); msbuildMetadata.CrossTargeting = true; msbuildMetadata.LegacyPackagesDirectory = true; // Act PackageSpec readSpec = PackageSpecTestUtility.RoundTrip(spec, PackageSpecName, PackageSpecPath); ProjectRestoreMetadata msbuildMetadata2 = readSpec.RestoreMetadata; // Assert Assert.NotNull(msbuildMetadata2); Assert.Equal("A55205E7-4D08-4672-8011-0925467CC45F", msbuildMetadata2.ProjectUniqueName); Assert.Equal("c:\\x\\x.csproj", msbuildMetadata2.ProjectPath); Assert.Equal(PackageSpecName, msbuildMetadata2.ProjectName); Assert.Equal("c:\\x\\project.json", msbuildMetadata2.ProjectJsonPath); Assert.Equal(ProjectStyle.PackageReference, msbuildMetadata2.ProjectStyle); Assert.Equal("c:\\packages", msbuildMetadata2.PackagesPath); Assert.Equal("https://api.nuget.org/v3/index.json", string.Join("|", msbuildMetadata.Sources.Select(s => s.Source))); Assert.Equal("c:\\fallback1|c:\\fallback2", string.Join("|", msbuildMetadata2.FallbackFolders)); Assert.Equal("c:\\nuget.config|d:\\nuget.config", string.Join("|", msbuildMetadata.ConfigFilePaths)); Assert.Equal("44B29B8D-8413-42D2-8DF4-72225659619B|c:\\a\\a.csproj|78A6AD3F-9FA5-47F6-A54E-84B46A48CB2F|c:\\b\\b.csproj", string.Join("|", msbuildMetadata2.TargetFrameworks.Single().ProjectReferences.Select(e => $"{e.ProjectUniqueName}|{e.ProjectPath}"))); Assert.True(msbuildMetadata.CrossTargeting); Assert.True(msbuildMetadata.LegacyPackagesDirectory); // Verify build metadata is not lost. Assert.Equal("24.5.1.2-alpha.1.2+a.b.c", readSpec.Version.ToFullString()); }
public static List <MSBuildOutputFile> GetMSBuildOutputFiles(PackageSpec project, LockFile assetsFile, IEnumerable <RestoreTargetGraph> targetGraphs, IReadOnlyList <NuGetv3LocalRepository> repositories, RestoreRequest request, string assetsFilePath, bool restoreSuccess, ILogger log) { // Generate file names var targetsPath = GetMSBuildFilePath(project, request, "targets"); var propsPath = GetMSBuildFilePath(project, request, "props"); // Targets files contain a macro for the repository root. If only the user package folder was used // allow a replacement. If fallback folders were used the macro cannot be applied. // Do not use macros for fallback folders. Use only the first repository which is the user folder. var repositoryRoot = repositories.First().RepositoryRoot; // Invalid msbuild projects should write out an msbuild error target if (!targetGraphs.Any()) { return(GenerateMultiTargetFailureFiles( targetsPath, propsPath, request.ProjectStyle)); } // Add additional conditionals for multi targeting var multiTargetingFromMetadata = (request.Project.RestoreMetadata?.CrossTargeting == true); var isMultiTargeting = multiTargetingFromMetadata || request.Project.TargetFrameworks.Count > 1; // ItemGroups for each file. var props = new List <MSBuildRestoreItemGroup>(); var targets = new List <MSBuildRestoreItemGroup>(); // MultiTargeting imports are shared between TFMs, to avoid // duplicate import warnings only add each once. var multiTargetingImportsAdded = new HashSet <string>(StringComparer.OrdinalIgnoreCase); // Skip runtime graphs, msbuild targets may not come from RID specific packages. var ridlessTargets = assetsFile.Targets .Where(e => string.IsNullOrEmpty(e.RuntimeIdentifier)); foreach (var ridlessTarget in ridlessTargets) { // There could be multiple string matches from the MSBuild project. var frameworkConditions = GetMatchingFrameworkStrings(project, ridlessTarget.TargetFramework) .Select(match => string.Format(CultureInfo.InvariantCulture, TargetFrameworkCondition, match)) .ToArray(); // Find matching target in the original target graphs. var targetGraph = targetGraphs.FirstOrDefault(e => string.IsNullOrEmpty(e.RuntimeIdentifier) && ridlessTarget.TargetFramework == e.Framework); // Sort by dependency order, child package assets should appear higher in the // msbuild targets and props files so that parents can depend on them. var sortedGraph = TopologicalSortUtility.SortPackagesByDependencyOrder(ConvertToPackageDependencyInfo(targetGraph.Flattened)); // Filter out to packages only, exclude projects. var packageType = new HashSet <string>( targetGraph.Flattened.Where(e => e.Key.Type == LibraryType.Package) .Select(e => e.Key.Name), StringComparer.OrdinalIgnoreCase); // Package -> PackageInfo // PackageInfo is kept lazy to avoid hitting the disk for packages // with no relevant assets. var sortedPackages = sortedGraph.Where(e => packageType.Contains(e.Id)) .Select(sortedPkg => new KeyValuePair <LockFileTargetLibrary, Lazy <LocalPackageSourceInfo> >( key: ridlessTarget.Libraries.FirstOrDefault(assetsPkg => sortedPkg.Version == assetsPkg.Version && sortedPkg.Id.Equals(assetsPkg.Name, StringComparison.OrdinalIgnoreCase)), value: new Lazy <LocalPackageSourceInfo>(() => NuGetv3LocalRepositoryUtility.GetPackage( repositories, sortedPkg.Id, sortedPkg.Version)))) .Where(e => e.Key != null) .ToArray(); // build/ {packageId}.targets var buildTargetsGroup = new MSBuildRestoreItemGroup(); buildTargetsGroup.RootName = MSBuildRestoreItemGroup.ImportGroup; buildTargetsGroup.Position = 2; buildTargetsGroup.Items.AddRange(sortedPackages.SelectMany(pkg => pkg.Key.Build.WithExtension(TargetsExtension) .Where(e => pkg.Value.Exists()) .Select(e => pkg.Value.GetAbsolutePath(e))) .Select(path => GetPathWithMacros(path, repositoryRoot)) .Select(GenerateImport)); targets.AddRange(GenerateGroupsWithConditions(buildTargetsGroup, isMultiTargeting, frameworkConditions)); // props/ {packageId}.props var buildPropsGroup = new MSBuildRestoreItemGroup(); buildPropsGroup.RootName = MSBuildRestoreItemGroup.ImportGroup; buildPropsGroup.Position = 2; buildPropsGroup.Items.AddRange(sortedPackages.SelectMany(pkg => pkg.Key.Build.WithExtension(PropsExtension) .Where(e => pkg.Value.Exists()) .Select(e => pkg.Value.GetAbsolutePath(e))) .Select(path => GetPathWithMacros(path, repositoryRoot)) .Select(GenerateImport)); props.AddRange(GenerateGroupsWithConditions(buildPropsGroup, isMultiTargeting, frameworkConditions)); if (isMultiTargeting) { // buildMultiTargeting/ {packageId}.targets var buildCrossTargetsGroup = new MSBuildRestoreItemGroup(); buildCrossTargetsGroup.RootName = MSBuildRestoreItemGroup.ImportGroup; buildCrossTargetsGroup.Position = 0; buildCrossTargetsGroup.Items.AddRange(sortedPackages.SelectMany(pkg => pkg.Key.BuildMultiTargeting.WithExtension(TargetsExtension) .Where(e => pkg.Value.Exists()) .Select(e => pkg.Value.GetAbsolutePath(e))) .Where(path => multiTargetingImportsAdded.Add(path)) .Select(path => GetPathWithMacros(path, repositoryRoot)) .Select(GenerateImport)); targets.AddRange(GenerateGroupsWithConditions(buildCrossTargetsGroup, isMultiTargeting, CrossTargetingCondition)); // buildMultiTargeting/ {packageId}.props var buildCrossPropsGroup = new MSBuildRestoreItemGroup(); buildCrossPropsGroup.RootName = MSBuildRestoreItemGroup.ImportGroup; buildCrossPropsGroup.Position = 0; buildCrossPropsGroup.Items.AddRange(sortedPackages.SelectMany(pkg => pkg.Key.BuildMultiTargeting.WithExtension(PropsExtension) .Where(e => pkg.Value.Exists()) .Select(e => pkg.Value.GetAbsolutePath(e))) .Where(path => multiTargetingImportsAdded.Add(path)) .Select(path => GetPathWithMacros(path, repositoryRoot)) .Select(GenerateImport)); props.AddRange(GenerateGroupsWithConditions(buildCrossPropsGroup, isMultiTargeting, CrossTargetingCondition)); } // Write out contentFiles only for XPlat PackageReference projects. if (request.ProjectStyle != ProjectStyle.ProjectJson && request.Project.RestoreMetadata?.SkipContentFileWrite != true) { // Create a group for every package, with the nearest from each of allLanguages props.AddRange(sortedPackages.Select(pkg => pkg.Key.ContentFiles .Where(e => pkg.Value.Exists()) .OrderBy(e => e.Path, StringComparer.Ordinal) .Select(e => Tuple.Create( item1: pkg.Key, item2: e, item3: GetPathWithMacros(pkg.Value.GetAbsolutePath(e), repositoryRoot)))) .SelectMany(e => GetLanguageGroups(e)) .SelectMany(group => GenerateGroupsWithConditions(group, isMultiTargeting, frameworkConditions))); } } // Add exclude all condition to all groups foreach (var group in props.Concat(targets)) { group.Conditions.Add(ExcludeAllCondition); } // Create XML, these may be null if the file should be deleted/not written out. var propsXML = GenerateMSBuildFile(props, request.ProjectStyle); var targetsXML = GenerateMSBuildFile(targets, request.ProjectStyle); // Return all files to write out or delete. var files = new List <MSBuildOutputFile> { new MSBuildOutputFile(propsPath, propsXML), new MSBuildOutputFile(targetsPath, targetsXML) }; var packageFolders = repositories.Select(e => e.RepositoryRoot); AddNuGetPropertiesToFirstImport(files, packageFolders, repositoryRoot, request.ProjectStyle, assetsFilePath, restoreSuccess); return(files); }
/// <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 projectPath = Path.Combine("StrideLauncher.json"); var spec = new PackageSpec() { Name = Path.GetFileNameWithoutExtension(projectPath), // make sure this package never collides with a dependency FilePath = projectPath, Dependencies = new List <LibraryDependency>() { new LibraryDependency { LibraryRange = new LibraryRange(packageId, new VersionRange(version.ToNuGetVersion()), LibraryDependencyTarget.Package), } }, TargetFrameworks = { new TargetFrameworkInformation { FrameworkName = NuGetFramework.Parse("net472"), } }, RestoreMetadata = new ProjectRestoreMetadata { ProjectPath = projectPath, ProjectName = Path.GetFileNameWithoutExtension(projectPath), ProjectStyle = ProjectStyle.PackageReference, ProjectUniqueName = projectPath, OutputPath = Path.Combine(Path.GetTempPath(), $"StrideLauncher-{packageId}-{version.ToString()}"), OriginalTargetFrameworks = new[] { "net472" }, ConfigFilePaths = settings.GetConfigFilePaths(), PackagesPath = installPath, Sources = SettingsUtility.GetEnabledSources(settings).ToList(), FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList() }, }; using (var context = new SourceCacheContext { MaxAge = DateTimeOffset.UtcNow }) { context.IgnoreFailedSources = true; var dependencyGraphSpec = new DependencyGraphSpec(); dependencyGraphSpec.AddProject(spec); dependencyGraphSpec.AddRestore(spec.RestoreMetadata.ProjectUniqueName); IPreLoadedRestoreRequestProvider requestProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dependencyGraphSpec); var restoreArgs = new RestoreArgs { AllowNoOp = true, CacheContext = context, CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(settings)), Log = NativeLogger, }; // Create requests from the arguments var requests = requestProvider.CreateRequests(restoreArgs).Result; foreach (var request in requests) { // Limit concurrency to avoid timeout request.Request.MaxDegreeOfConcurrency = 4; var command = new RestoreCommand(request.Request); // Act var result = await command.ExecuteAsync(); if (!result.Success) { throw new InvalidOperationException($"Could not restore package {packageId}"); } foreach (var install in result.RestoreGraphs.Last().Install) { var package = result.LockFile.Libraries.FirstOrDefault(x => x.Name == install.Library.Name && x.Version == install.Library.Version); if (package != null) { var packagePath = Path.Combine(installPath, package.Path); OnPackageInstalled(this, new PackageOperationEventArgs(new PackageName(install.Library.Name, install.Library.Version.ToPackageVersion()), packagePath)); } } } } if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0)) { UpdateTargetsHelper(); } } // Load the recently installed package var installedPackages = GetPackagesInstalled(new[] { packageId }); return(installedPackages.FirstOrDefault(p => p.Version == version)); } finally { currentProgressReport = null; } } }
async Task <PackageSpec> CreateProjectPackageSpec(DependencyGraphCacheContext context) { PackageSpec packageSpec = await Runtime.RunInMainThread(() => CreateProjectPackageSpec (project, context)); return(packageSpec); }
public static void ModifyRestoreSettings(PackageSpec packageSpec) { packageSpec.RestoreSettings.HideWarningsAndErrors = false; }
public LockFile CreateLockFile( LockFile previousLockFile, PackageSpec project, IEnumerable <RestoreTargetGraph> targetGraphs, IReadOnlyList <NuGetv3LocalRepository> localRepositories, RemoteWalkContext context, IEnumerable <ToolRestoreResult> toolRestoreResults) { var lockFile = new LockFile(); lockFile.Version = _lockFileVersion; var previousLibraries = previousLockFile?.Libraries.ToDictionary(l => Tuple.Create(l.Name, l.Version)); // Use empty string as the key of dependencies shared by all frameworks lockFile.ProjectFileDependencyGroups.Add(new ProjectFileDependencyGroup( string.Empty, project.Dependencies .Select(group => group.LibraryRange.ToLockFileDependencyGroupString()) .OrderBy(group => group, StringComparer.Ordinal))); foreach (var frameworkInfo in project.TargetFrameworks .OrderBy(framework => framework.FrameworkName.ToString(), StringComparer.Ordinal)) { lockFile.ProjectFileDependencyGroups.Add(new ProjectFileDependencyGroup( frameworkInfo.FrameworkName.ToString(), frameworkInfo.Dependencies .Select(x => x.LibraryRange.ToLockFileDependencyGroupString()) .OrderBy(dependency => dependency, StringComparer.Ordinal))); } // Record all libraries used foreach (var item in targetGraphs.SelectMany(g => g.Flattened).Distinct() .OrderBy(x => x.Data.Match.Library)) { var library = item.Data.Match.Library; if (project.Name.Equals(library.Name, StringComparison.OrdinalIgnoreCase)) { // Do not include the project itself as a library. continue; } if (library.Type == LibraryType.Project || library.Type == LibraryType.ExternalProject) { // Project LocalMatch localMatch = (LocalMatch)item.Data.Match; var projectLib = new LockFileLibrary() { Name = library.Name, Version = library.Version, Type = LibraryType.Project, }; // Set the relative path if a path exists // For projects without project.json this will be empty if (!string.IsNullOrEmpty(localMatch.LocalLibrary.Path)) { projectLib.Path = PathUtility.GetRelativePath( project.FilePath, localMatch.LocalLibrary.Path, '/'); } // The msbuild project path if it exists object msbuildPath; if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.MSBuildProjectPath, out msbuildPath)) { var msbuildRelativePath = PathUtility.GetRelativePath( project.FilePath, (string)msbuildPath, '/'); projectLib.MSBuildProject = msbuildRelativePath; } lockFile.Libraries.Add(projectLib); } else if (library.Type == LibraryType.Package) { // Packages var packageInfo = NuGetv3LocalRepositoryUtility.GetPackage(localRepositories, library.Name, library.Version); if (packageInfo == null) { continue; } var package = packageInfo.Package; var resolver = packageInfo.Repository.PathResolver; var sha512 = File.ReadAllText(resolver.GetHashPath(package.Id, package.Version)); LockFileLibrary previousLibrary = null; previousLibraries?.TryGetValue(Tuple.Create(library.Name, library.Version), out previousLibrary); var lockFileLib = previousLibrary; // If we have the same library in the lock file already, use that. if (previousLibrary == null || previousLibrary.Sha512 != sha512) { var path = resolver.GetPackageDirectory(package.Id, package.Version); path = PathUtility.GetPathWithForwardSlashes(path); lockFileLib = CreateLockFileLibrary( package, sha512, path); } else if (Path.DirectorySeparatorChar != LockFile.DirectorySeparatorChar) { // Fix slashes for content model patterns lockFileLib.Files = lockFileLib.Files .Select(p => p.Replace(Path.DirectorySeparatorChar, LockFile.DirectorySeparatorChar)) .ToList(); } lockFile.Libraries.Add(lockFileLib); var packageIdentity = new PackageIdentity(lockFileLib.Name, lockFileLib.Version); context.PackageFileCache.TryAdd(packageIdentity, lockFileLib.Files); } } var libraries = lockFile.Libraries.ToDictionary(lib => Tuple.Create(lib.Name, lib.Version)); var warnForImports = project.TargetFrameworks.Any(framework => framework.Warn); var librariesWithWarnings = new HashSet <LibraryIdentity>(); // Add the targets foreach (var targetGraph in targetGraphs .OrderBy(graph => graph.Framework.ToString(), StringComparer.Ordinal) .ThenBy(graph => graph.RuntimeIdentifier, StringComparer.Ordinal)) { var target = new LockFileTarget(); target.TargetFramework = targetGraph.Framework; target.RuntimeIdentifier = targetGraph.RuntimeIdentifier; var flattenedFlags = IncludeFlagUtils.FlattenDependencyTypes(_includeFlagGraphs, project, targetGraph); var fallbackFramework = target.TargetFramework as FallbackFramework; var warnForImportsOnGraph = warnForImports && fallbackFramework != null; foreach (var graphItem in targetGraph.Flattened.OrderBy(x => x.Key)) { var library = graphItem.Key; if (library.Type == LibraryType.Project || library.Type == LibraryType.ExternalProject) { if (project.Name.Equals(library.Name, StringComparison.OrdinalIgnoreCase)) { // Do not include the project itself as a library. continue; } var localMatch = (LocalMatch)graphItem.Data.Match; // Target framework information is optional and may not exist for csproj projects // that do not have a project.json file. string projectFramework = null; object frameworkInfoObject; if (localMatch.LocalLibrary.Items.TryGetValue( KnownLibraryProperties.TargetFrameworkInformation, out frameworkInfoObject)) { // Retrieve the resolved framework name, if this is null it means that the // project is incompatible. This is marked as Unsupported. var targetFrameworkInformation = (TargetFrameworkInformation)frameworkInfoObject; projectFramework = targetFrameworkInformation.FrameworkName?.DotNetFrameworkName ?? NuGetFramework.UnsupportedFramework.DotNetFrameworkName; } // Create the target entry var lib = new LockFileTargetLibrary() { Name = library.Name, Version = library.Version, Type = LibraryType.Project, Framework = projectFramework, // Find all dependencies which would be in the nuspec // Include dependencies with no constraints, or package/project/external // Exclude suppressed dependencies, the top level project is not written // as a target so the node depth does not matter. Dependencies = graphItem.Data.Dependencies .Where( d => (d.LibraryRange.TypeConstraintAllowsAnyOf( LibraryDependencyTarget.PackageProjectExternal)) && d.SuppressParent != LibraryIncludeFlags.All) .Select(d => GetDependencyVersionRange(d)) .ToList() }; object compileAssetObject; if (localMatch.LocalLibrary.Items.TryGetValue( KnownLibraryProperties.CompileAsset, out compileAssetObject)) { var item = new LockFileItem((string)compileAssetObject); lib.CompileTimeAssemblies.Add(item); lib.RuntimeAssemblies.Add(item); } // Add frameworkAssemblies for projects object frameworkAssembliesObject; if (localMatch.LocalLibrary.Items.TryGetValue( KnownLibraryProperties.FrameworkAssemblies, out frameworkAssembliesObject)) { lib.FrameworkAssemblies.AddRange((List <string>)frameworkAssembliesObject); } target.Libraries.Add(lib); continue; } else if (library.Type == LibraryType.Package) { var packageInfo = NuGetv3LocalRepositoryUtility.GetPackage(localRepositories, library.Name, library.Version); if (packageInfo == null) { continue; } var package = packageInfo.Package; // include flags LibraryIncludeFlags includeFlags; if (!flattenedFlags.TryGetValue(library.Name, out includeFlags)) { includeFlags = ~LibraryIncludeFlags.ContentFiles; } var targetLibrary = LockFileUtils.CreateLockFileTargetLibrary( libraries[Tuple.Create(library.Name, library.Version)], package, targetGraph, dependencyType: includeFlags, targetFrameworkOverride: null, dependencies: graphItem.Data.Dependencies); target.Libraries.Add(targetLibrary); // Log warnings if the target library used the fallback framework if (warnForImportsOnGraph && !librariesWithWarnings.Contains(library)) { var nonFallbackFramework = new NuGetFramework(fallbackFramework); var targetLibraryWithoutFallback = LockFileUtils.CreateLockFileTargetLibrary( libraries[Tuple.Create(library.Name, library.Version)], package, targetGraph, targetFrameworkOverride: nonFallbackFramework, dependencyType: includeFlags, dependencies: graphItem.Data.Dependencies); if (!targetLibrary.Equals(targetLibraryWithoutFallback)) { var libraryName = $"{library.Name} {library.Version}"; _logger.LogWarning(string.Format(CultureInfo.CurrentCulture, Strings.Log_ImportsFallbackWarning, libraryName, String.Join(", ", fallbackFramework.Fallback), nonFallbackFramework)); // only log the warning once per library librariesWithWarnings.Add(library); } } } } lockFile.Targets.Add(target); } PopulateProjectFileToolGroups(project, lockFile); PopulateTools(toolRestoreResults, lockFile); PopulatePackageFolders(localRepositories.Select(repo => repo.RepositoryRoot).Distinct(), lockFile); return(lockFile); }
public static void ModifyPackOptions(PackageSpec packageSpec) { ((List <PackageType>)packageSpec.PackOptions.PackageType).Add(PackageType.DotnetCliTool); }
public static void ModifyRuntimeGraph(PackageSpec packageSpec) { packageSpec.RuntimeGraph.Supports["CompatibilityProfile"].RestoreContexts.Add(CreateFrameworkRuntimePair(rid: "win10-x64")); }
public static void ModifyPackInclude(PackageSpec packageSpec) { packageSpec.PackInclude.Add(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); }
public static void ModifyDependencies(PackageSpec packageSpec) { packageSpec.Dependencies.Add(CreateLibraryDependency()); }
public static void ModifyContentFiles(PackageSpec packageSpec) { packageSpec.ContentFiles.Add("New fnacy content file"); }
public override async Task <(IReadOnlyList <PackageSpec> dgSpecs, IReadOnlyList <IAssetsLogMessage> additionalMessages)> GetPackageSpecsAndAdditionalMessagesAsync(DependencyGraphCacheContext context) { PackageSpec packageSpec = null; if (context == null || !context.PackageSpecCache.TryGetValue(MSBuildProjectPath, out packageSpec)) { packageSpec = JsonPackageSpecReader.GetPackageSpec(ProjectName, JsonConfigPath); if (packageSpec == null) { throw new InvalidOperationException( string.Format(Strings.ProjectNotLoaded_RestoreFailed, ProjectName)); } var metadata = new ProjectRestoreMetadata(); packageSpec.RestoreMetadata = metadata; metadata.ProjectStyle = ProjectStyle.ProjectJson; metadata.OutputPath = await GetMSBuildProjectExtensionsPathAsync(); metadata.ProjectPath = MSBuildProjectPath; metadata.ProjectJsonPath = packageSpec.FilePath; metadata.ProjectName = packageSpec.Name; metadata.ProjectUniqueName = MSBuildProjectPath; metadata.CacheFilePath = await GetCacheFilePathAsync(); // Reload the target framework from csproj and update the target framework in packageSpec for restore await UpdateInternalTargetFrameworkAsync(); if (TryGetInternalFramework(out var targetFramework)) { var nuGetFramework = targetFramework as NuGetFramework; if (IsUAPFramework(nuGetFramework)) { // Ensure the project json has only one target framework if (packageSpec.TargetFrameworks != null && packageSpec.TargetFrameworks.Count == 1) { var tfi = packageSpec.TargetFrameworks.First(); if (tfi.Imports.Count > 0) { if (tfi.AssetTargetFallback) { nuGetFramework = new AssetTargetFallbackFramework(nuGetFramework, tfi.Imports.AsList()); } else { nuGetFramework = new FallbackFramework(nuGetFramework, tfi.Imports.AsList()); } } tfi.FrameworkName = nuGetFramework; } } } var references = (await ProjectServices .ReferencesReader .GetProjectReferencesAsync(context?.Logger ?? NullLogger.Instance, CancellationToken.None)) .ToList(); if (references != null && references.Count > 0) { // Add msbuild reference groups for each TFM in the project foreach (var framework in packageSpec.TargetFrameworks.Select(e => e.FrameworkName)) { metadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(framework)); } foreach (var reference in references) { // This reference applies to all frameworks // Include/exclude flags may be applied later when merged with project.json // Add the reference for all TFM groups, there are no conditional project // references in UWP. There should also be just one TFM. foreach (var frameworkInfo in metadata.TargetFrameworks) { frameworkInfo.ProjectReferences.Add(reference); } } } // Write restore settings to the package spec. // For project.json these properties may not come from the project file. var settings = context?.Settings ?? NullSettings.Instance; packageSpec.RestoreMetadata.PackagesPath = SettingsUtility.GetGlobalPackagesFolder(settings); packageSpec.RestoreMetadata.Sources = SettingsUtility.GetEnabledSources(settings).AsList(); packageSpec.RestoreMetadata.FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).AsList(); packageSpec.RestoreMetadata.ConfigFilePaths = settings.GetConfigFilePaths(); context?.PackageSpecCache.Add(MSBuildProjectPath, packageSpec); } return(new[] { packageSpec }, null); }
/// <summary> /// Returns the name of the single dependency in the spec or null. /// </summary> public static string GetToolIdOrNullFromSpec(PackageSpec spec) { return(GetToolDependencyOrNullFromSpec(spec)?.Name); }
private async Task ExecuteWorker(PythonProjectNode project) { _errorListProvider.Tasks.Clear(); var interpFactory = project.GetInterpreterFactoryOrThrow(); var startInfo = GetStartInfo(project); var packagesToInstall = new List <string>(); var pm = interpFactory.PackageManager; if (pm != null) { foreach (var pkg in startInfo.RequiredPackages) { if (!(await pm.GetInstalledPackageAsync(new PackageSpec(pkg), CancellationToken.None)).IsValid) { packagesToInstall.Add(pkg); } } } if (packagesToInstall.Any()) { var installMissingButton = new TaskDialogButton( Strings.CustomCommandPrerequisitesInstallMissing, Strings.CustomCommandPrerequisitesInstallMissingSubtext + "\r\n\r\n" + string.Join("\r\n", packagesToInstall)); var runAnywayButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesRunAnyway); var doNotRunButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesDoNotRun); var taskDialog = new TaskDialog(project.Site) { Title = Strings.ProductTitle, MainInstruction = Strings.CustomCommandPrerequisitesInstruction, Content = Strings.CustomCommandPrerequisitesContent.FormatUI(DisplayLabelWithoutAccessKeys), AllowCancellation = true, Buttons = { installMissingButton, runAnywayButton, doNotRunButton, TaskDialogButton.Cancel } }; var selectedButton = taskDialog.ShowModal(); if (selectedButton == installMissingButton) { var ui = new VsPackageManagerUI(project.Site); if (!pm.IsReady) { await pm.PrepareAsync(ui, CancellationToken.None); } await pm.InstallAsync(PackageSpec.FromArguments(string.Join(" ", packagesToInstall)), ui, CancellationToken.None); } else if (selectedButton == runAnywayButton) { } else { throw new TaskCanceledException(); } } if (startInfo.TargetType == PythonCommandTask.TargetTypePip) { if (startInfo.ExecuteInOutput && pm != null) { var ui = new VsPackageManagerUI(project.Site); if (!pm.IsReady) { await pm.PrepareAsync(ui, CancellationToken.None); } await pm.InstallAsync( PackageSpec.FromArguments(string.IsNullOrEmpty(startInfo.Arguments) ? startInfo.Filename : "{0} {1}".FormatUI(startInfo.Filename, startInfo.Arguments)), ui, CancellationToken.None ); return; } // Rewrite start info to execute startInfo.TargetType = PythonCommandTask.TargetTypeModule; startInfo.AddArgumentAtStart(startInfo.Filename); startInfo.Filename = "pip"; } if (startInfo.ExecuteInRepl) { if (await RunInRepl(project, startInfo)) { return; } } startInfo.AdjustArgumentsForProcessStartInfo(GetInterpreterPath(project, false)); if (startInfo.ExecuteInOutput) { RunInOutput(project, startInfo); } else { RunInConsole(project, startInfo); } }
public LockFile CreateLockFile(LockFile previousLockFile, PackageSpec project, IEnumerable <RestoreTargetGraph> targetGraphs, IReadOnlyList <NuGetv3LocalRepository> localRepositories, RemoteWalkContext context) { var lockFile = new LockFile() { Version = _lockFileVersion }; var previousLibraries = previousLockFile?.Libraries.ToDictionary(l => Tuple.Create(l.Name, l.Version)); if (project.RestoreMetadata?.ProjectStyle == ProjectStyle.PackageReference || project.RestoreMetadata?.ProjectStyle == ProjectStyle.DotnetToolReference) { AddProjectFileDependenciesForPackageReference(project, lockFile, targetGraphs); } else { AddProjectFileDependenciesForSpec(project, lockFile); } // Record all libraries used foreach (var item in targetGraphs.SelectMany(g => g.Flattened).Distinct() .OrderBy(x => x.Data.Match.Library)) { var library = item.Data.Match.Library; if (project.Name.Equals(library.Name, StringComparison.OrdinalIgnoreCase)) { // Do not include the project itself as a library. continue; } if (library.Type == LibraryType.Project || library.Type == LibraryType.ExternalProject) { // Project var localMatch = (LocalMatch)item.Data.Match; var projectLib = new LockFileLibrary() { Name = library.Name, Version = library.Version, Type = LibraryType.Project, }; // Set the relative path if a path exists // For projects without project.json this will be empty if (!string.IsNullOrEmpty(localMatch.LocalLibrary.Path)) { projectLib.Path = PathUtility.GetRelativePath( project.FilePath, localMatch.LocalLibrary.Path, '/'); } // The msbuild project path if it exists object msbuildPath; if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.MSBuildProjectPath, out msbuildPath)) { var msbuildRelativePath = PathUtility.GetRelativePath( project.FilePath, (string)msbuildPath, '/'); projectLib.MSBuildProject = msbuildRelativePath; } lockFile.Libraries.Add(projectLib); } else if (library.Type == LibraryType.Package) { // Packages var packageInfo = NuGetv3LocalRepositoryUtility.GetPackage(localRepositories, library.Name, library.Version); // Add the library if it was resolved, unresolved packages are not added to the assets file. if (packageInfo != null) { var package = packageInfo.Package; var resolver = packageInfo.Repository.PathResolver; var sha512 = package.Sha512; var path = PathUtility.GetPathWithForwardSlashes(resolver.GetPackageDirectory(package.Id, package.Version)); LockFileLibrary lockFileLib = null; LockFileLibrary previousLibrary = null; if (previousLibraries?.TryGetValue(Tuple.Create(package.Id, package.Version), out previousLibrary) == true) { // Check that the previous library is still valid if (previousLibrary != null && StringComparer.Ordinal.Equals(path, previousLibrary.Path) && StringComparer.Ordinal.Equals(sha512, previousLibrary.Sha512)) { // We mutate this previous library so we must take a clone of it. This is // important because later, when deciding whether the lock file has changed, // we compare the new lock file to the previous (in-memory) lock file. lockFileLib = previousLibrary.Clone(); } } // Create a new lock file library if one doesn't exist already. if (lockFileLib == null) { lockFileLib = CreateLockFileLibrary(package, sha512, path); } // Create a new lock file library lockFile.Libraries.Add(lockFileLib); } } } var libraries = lockFile.Libraries.ToDictionary(lib => Tuple.Create(lib.Name, lib.Version)); var librariesWithWarnings = new HashSet <LibraryIdentity>(); var rootProjectStyle = project.RestoreMetadata?.ProjectStyle ?? ProjectStyle.Unknown; // Cache package data and selection criteria across graphs. var builderCache = new LockFileBuilderCache(); // Add the targets foreach (var targetGraph in targetGraphs .OrderBy(graph => graph.Framework.ToString(), StringComparer.Ordinal) .ThenBy(graph => graph.RuntimeIdentifier, StringComparer.Ordinal)) { var target = new LockFileTarget { TargetFramework = targetGraph.Framework, RuntimeIdentifier = targetGraph.RuntimeIdentifier }; var flattenedFlags = IncludeFlagUtils.FlattenDependencyTypes(_includeFlagGraphs, project, targetGraph); // Check if warnings should be displayed for the current framework. var tfi = project.GetTargetFramework(targetGraph.Framework); var warnForImportsOnGraph = tfi.Warn && (target.TargetFramework is FallbackFramework || target.TargetFramework is AssetTargetFallbackFramework); foreach (var graphItem in targetGraph.Flattened.OrderBy(x => x.Key)) { var library = graphItem.Key; // include flags LibraryIncludeFlags includeFlags; if (!flattenedFlags.TryGetValue(library.Name, out includeFlags)) { includeFlags = ~LibraryIncludeFlags.ContentFiles; } if (library.Type == LibraryType.Project || library.Type == LibraryType.ExternalProject) { if (project.Name.Equals(library.Name, StringComparison.OrdinalIgnoreCase)) { // Do not include the project itself as a library. continue; } var projectLib = LockFileUtils.CreateLockFileTargetProject( graphItem, library, includeFlags, targetGraph, rootProjectStyle); target.Libraries.Add(projectLib); continue; } else if (library.Type == LibraryType.Package) { var packageInfo = NuGetv3LocalRepositoryUtility.GetPackage(localRepositories, library.Name, library.Version); if (packageInfo == null) { continue; } var package = packageInfo.Package; var targetLibrary = LockFileUtils.CreateLockFileTargetLibrary( libraries[Tuple.Create(library.Name, library.Version)], package, targetGraph, dependencyType: includeFlags, targetFrameworkOverride: null, dependencies: graphItem.Data.Dependencies, cache: builderCache); target.Libraries.Add(targetLibrary); // Log warnings if the target library used the fallback framework if (warnForImportsOnGraph && !librariesWithWarnings.Contains(library)) { var nonFallbackFramework = new NuGetFramework(target.TargetFramework); var targetLibraryWithoutFallback = LockFileUtils.CreateLockFileTargetLibrary( libraries[Tuple.Create(library.Name, library.Version)], package, targetGraph, targetFrameworkOverride: nonFallbackFramework, dependencyType: includeFlags, dependencies: graphItem.Data.Dependencies, cache: builderCache); if (!targetLibrary.Equals(targetLibraryWithoutFallback)) { var libraryName = DiagnosticUtility.FormatIdentity(library); var message = string.Format(CultureInfo.CurrentCulture, Strings.Log_ImportsFallbackWarning, libraryName, GetFallbackFrameworkString(target.TargetFramework), nonFallbackFramework); var logMessage = RestoreLogMessage.CreateWarning( NuGetLogCode.NU1701, message, library.Name, targetGraph.TargetGraphName); _logger.Log(logMessage); // only log the warning once per library librariesWithWarnings.Add(library); } } } } lockFile.Targets.Add(target); } PopulatePackageFolders(localRepositories.Select(repo => repo.RepositoryRoot).Distinct(), lockFile); // Add the original package spec to the lock file. lockFile.PackageSpec = project; return(lockFile); }
public async Task UninstallPackage(PackageSpec package) { AbortOnInvalidConfiguration(); await _packageManager.UninstallAsync(package, this, _cancelAll.Token); }
void CreatePackageSpec() { spec = PackageSpecCreator.CreatePackageSpec(project, logger); }
static PackageSpec CreateProjectPackageSpec(DotNetProject project, DependencyGraphCacheContext context) { PackageSpec packageSpec = PackageSpecCreator.CreatePackageSpec(project, context); return(packageSpec); }
public static string GetMSBuildFilePathForPackageReferenceStyleProject(PackageSpec project, string extension) { var projFileName = Path.GetFileName(project.RestoreMetadata.ProjectPath); return(Path.Combine(project.RestoreMetadata.OutputPath, projFileName + ".nuget.g" + extension)); }
public void DependencyGraphSpec_RoundTripMSBuildMetadata_ProjectReferenceFlags() { // Arrange var frameworks = new List <TargetFrameworkInformation>(); frameworks.Add(new TargetFrameworkInformation() { FrameworkName = NuGetFramework.Parse("net45") }); var spec = new PackageSpec(frameworks); var msbuildMetadata = new ProjectRestoreMetadata(); spec.RestoreMetadata = msbuildMetadata; msbuildMetadata.ProjectUniqueName = "A55205E7-4D08-4672-8011-0925467CC45F"; msbuildMetadata.ProjectPath = "c:\\x\\x.csproj"; msbuildMetadata.ProjectName = PackageSpecName; msbuildMetadata.ProjectStyle = ProjectStyle.PackageReference; var tfmGroup = new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45")); var tfmGroup2 = new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("netstandard1.3")); msbuildMetadata.TargetFrameworks.Add(tfmGroup); msbuildMetadata.TargetFrameworks.Add(tfmGroup2); var ref1 = new ProjectRestoreReference() { ProjectUniqueName = "44B29B8D-8413-42D2-8DF4-72225659619B", ProjectPath = "c:\\a\\a.csproj", IncludeAssets = LibraryIncludeFlags.Build, ExcludeAssets = LibraryIncludeFlags.Compile, PrivateAssets = LibraryIncludeFlags.Runtime }; var ref2 = new ProjectRestoreReference() { ProjectUniqueName = "78A6AD3F-9FA5-47F6-A54E-84B46A48CB2F", ProjectPath = "c:\\b\\b.csproj" }; tfmGroup.ProjectReferences.Add(ref1); tfmGroup.ProjectReferences.Add(ref2); tfmGroup2.ProjectReferences.Add(ref1); tfmGroup2.ProjectReferences.Add(ref2); // Act PackageSpec readSpec = PackageSpecTestUtility.RoundTrip(spec, PackageSpecName, PackageSpecPath); // Assert Assert.Equal(2, readSpec.RestoreMetadata.TargetFrameworks.Count); foreach (var framework in readSpec.RestoreMetadata.TargetFrameworks) { var references = framework.ProjectReferences.OrderBy(e => e.ProjectUniqueName).ToArray(); Assert.Equal("44B29B8D-8413-42D2-8DF4-72225659619B", references[0].ProjectUniqueName); Assert.Equal(LibraryIncludeFlags.Build, references[0].IncludeAssets); Assert.Equal(LibraryIncludeFlags.Compile, references[0].ExcludeAssets); Assert.Equal(LibraryIncludeFlags.Runtime, references[0].PrivateAssets); Assert.Equal("78A6AD3F-9FA5-47F6-A54E-84B46A48CB2F", references[1].ProjectUniqueName); Assert.Equal(LibraryIncludeFlags.All, references[1].IncludeAssets); Assert.Equal(LibraryIncludeFlags.None, references[1].ExcludeAssets); Assert.Equal(LibraryIncludeFlagUtils.DefaultSuppressParent, references[1].PrivateAssets); } }
/// <summary> /// Warn for project dependencies that do not include a lower bound on the version range. /// </summary> public static IEnumerable <RestoreLogMessage> GetProjectDependenciesMissingLowerBounds(PackageSpec project) { return(project.GetAllPackageDependencies() .Where(e => HasMissingLowerBound(e.LibraryRange.VersionRange)) .OrderBy(e => e.Name, StringComparer.OrdinalIgnoreCase) .Select(e => RestoreLogMessage.CreateWarning( code: NuGetLogCode.NU1604, message: string.Format(CultureInfo.CurrentCulture, Strings.Warning_ProjectDependencyMissingLowerBound, DiagnosticUtility.FormatDependency(e.Name, e.LibraryRange.VersionRange)), libraryId: e.Name, targetGraphs: GetDependencyTargetGraphs(project, e)))); }
private bool IsProjectBuildIntegrated(PackageSpec packageSpec) { return(packageSpec.RestoreMetadata?.ProjectStyle == ProjectStyle.PackageReference || packageSpec.RestoreMetadata?.ProjectStyle == ProjectStyle.ProjectJson || packageSpec.RestoreMetadata?.ProjectStyle == ProjectStyle.DotnetCliTool); }
public async Task RestoreRunner_RestoreWithExternalFile_NetCoreOutput() { // Arrange var sources = new List <PackageSource>(); var targetFrameworkInfo1 = new TargetFrameworkInformation(); targetFrameworkInfo1.FrameworkName = NuGetFramework.Parse("net45"); var frameworks1 = new[] { targetFrameworkInfo1 }; var targetFrameworkInfo2 = new TargetFrameworkInformation(); targetFrameworkInfo2.FrameworkName = NuGetFramework.Parse("net45"); var frameworks2 = new[] { targetFrameworkInfo2 }; // Create two net45 projects var spec1 = new PackageSpec(frameworks1); spec1.RestoreMetadata = new ProjectRestoreMetadata(); spec1.RestoreMetadata.ProjectUniqueName = "project1"; spec1.RestoreMetadata.ProjectName = "project1"; spec1.RestoreMetadata.ProjectStyle = ProjectStyle.PackageReference; spec1.RestoreMetadata.OriginalTargetFrameworks.Add("net45"); var spec2 = new PackageSpec(frameworks2); spec2.RestoreMetadata = new ProjectRestoreMetadata(); spec2.RestoreMetadata.ProjectUniqueName = "project2"; spec2.RestoreMetadata.ProjectName = "project2"; spec2.RestoreMetadata.ProjectStyle = ProjectStyle.PackageReference; spec2.RestoreMetadata.OriginalTargetFrameworks.Add("net45"); var specs = new[] { spec1, spec2 }; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); var project2 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2")); packagesDir.Create(); packageSource.Create(); project1.Create(); project2.Create(); sources.Add(new PackageSource(packageSource.FullName)); var projPath1 = Path.Combine(project1.FullName, "project1.csproj"); var projPath2 = Path.Combine(project2.FullName, "project2.csproj"); File.WriteAllText(projPath1, string.Empty); File.WriteAllText(projPath2, string.Empty); spec1.RestoreMetadata.ProjectPath = projPath1; spec1.FilePath = projPath1; spec1.Name = "project1"; spec2.RestoreMetadata.ProjectPath = projPath2; spec2.FilePath = projPath1; spec2.Name = "project2"; var logger = new TestLogger(); var objPath1 = Path.Combine(project1.FullName, "obj"); var objPath2 = Path.Combine(project2.FullName, "obj"); spec1.RestoreMetadata.OutputPath = objPath1; spec2.RestoreMetadata.OutputPath = objPath2; spec1.RestoreMetadata.OriginalTargetFrameworks.Add("net45"); spec2.RestoreMetadata.OriginalTargetFrameworks.Add("net45"); var lockPath1 = Path.Combine(objPath1, "project.assets.json"); var lockPath2 = Path.Combine(objPath2, "project.assets.json"); // Link projects spec1.TargetFrameworks.Single().Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange() { Name = "project2", TypeConstraint = LibraryDependencyTarget.ExternalProject } }); spec1.RestoreMetadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45"))); spec1.RestoreMetadata.TargetFrameworks .Single() .ProjectReferences .Add(new ProjectRestoreReference() { ProjectPath = projPath2, ProjectUniqueName = "project2" }); // Create dg file var dgFile = new DependencyGraphSpec(); foreach (var spec in specs) { dgFile.AddRestore(spec.RestoreMetadata.ProjectName); dgFile.AddProject(spec); } var dgPath = Path.Combine(workingDir, "input.dg"); dgFile.Save(dgPath); var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList(); var providerCache = new RestoreCommandProvidersCache(); using (var cacheContext = new SourceCacheContext()) { var restoreContext = new RestoreArgs() { CacheContext = cacheContext, DisableParallel = true, GlobalPackagesFolder = packagesDir.FullName, Sources = new List <string>() { packageSource.FullName }, Inputs = new List <string>() { dgPath }, Log = logger, CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(sources)), RequestProviders = new List <IRestoreRequestProvider>() { new DependencyGraphFileRequestProvider(providerCache) } }; // Act var summaries = await RestoreRunner.RunAsync(restoreContext); var success = summaries.All(s => s.Success); var lockFormat = new LockFileFormat(); var lockFile1 = lockFormat.Read(lockPath1); var project2Lib = lockFile1.Libraries.First(); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); Assert.True(File.Exists(lockPath1), lockPath1); Assert.True(File.Exists(lockPath2), lockPath2); Assert.Equal("project2", project2Lib.Name); } } }
public static void ModifyOriginalTargetFrameworkInformationAdd(PackageSpec packageSpec) { packageSpec.TargetFrameworks.Add(CreateTargetFrameworkInformation("net40")); }
public void MergeRequirements() { // Comments should be preserved, only package specs should change. AssertUtil.AreEqual( PythonProjectNode.MergeRequirements(new[] { "a # with a comment", "B==0.2", "# just a comment B==01234", "", "x < 1", "d==1.0 e==2.0 f==3.0" }, new[] { "b==0.1", "a==0.2", "c==0.3", "e==4.0", "x==0.8" }.Select(p => PackageSpec.FromRequirement(p)), false), "a==0.2 # with a comment", "b==0.1", "# just a comment B==01234", "", "x==0.8", "d==1.0 e==4.0 f==3.0" ); // addNew is true, so the c==0.3 should be added. AssertUtil.AreEqual( PythonProjectNode.MergeRequirements(new[] { "a # with a comment", "b==0.2", "# just a comment B==01234" }, new[] { "B==0.1", // case is updated "a==0.2", "c==0.3" }.Select(p => PackageSpec.FromRequirement(p)), true), "a==0.2 # with a comment", "B==0.1", "# just a comment B==01234", "c==0.3" ); // No existing entries, so the new ones are sorted and returned. AssertUtil.AreEqual( PythonProjectNode.MergeRequirements(null, new[] { "b==0.2", "a==0.1", "c==0.3" }.Select(p => PackageSpec.FromRequirement(p)), false), "a==0.1", "b==0.2", "c==0.3" ); // Check all the inequalities const string inequalities = "<=|>=|<|>|!=|=="; AssertUtil.AreEqual( PythonProjectNode.MergeRequirements( inequalities.Split('|').Select(s => "a " + s + " 1.2.3"), new[] { "a==0" }.Select(p => PackageSpec.FromRequirement(p)), false ), inequalities.Split('|').Select(_ => "a==0").ToArray() ); }
public static void ModifyRestoreMetadata(PackageSpec packageSpec) { packageSpec.TargetFrameworks[0].Imports.Add(NuGetFramework.Parse("net461")); }
public static void ModifyTags(PackageSpec packageSpec) { packageSpec.Tags[0] = "better tag!"; }