Ejemplo n.º 1
0
        public void ContentFiles_NetStandardFallbackToAny()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("netstandard13.app")
            }));

            var criteria = conventions.Criteria.ForFramework(NuGetFramework.Parse("netstandard1.3"));

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "contentFiles/any/any/config1.xml",
                "contentFiles/any/dotnet/config1.xml",
                "contentFiles/any/netstandard1.4/config1.xml"
            });

            // Act
            var contentFileGroup = collection.FindBestItemGroup(criteria, conventions.Patterns.ContentFiles);
            var file             = contentFileGroup.Items.Single().Path;

            // Assert
            Assert.Equal("contentFiles/any/any/config1.xml", file);
        }
Ejemplo n.º 2
0
        public void ContentModel_RuntimeAgnosticFallbackReverse()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("netcore50.app")
            }));

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "lib/netcore50/System.Reflection.Emit.dll",
                "runtimes/aot/lib/netcore50/System.Reflection.Emit.dll",
            });

            var criteria = conventions.Criteria.ForFramework(NuGetFramework.Parse("netcore50"));

            // Act
            var group = collection.FindBestItemGroup(criteria, conventions.Patterns.RuntimeAssemblies);

            // Assert
            Assert.Equal("lib/netcore50/System.Reflection.Emit.dll", group.Items.Single().Path);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Create lock file items for the best matching group.
        /// </summary>
        /// <remarks>Enumerate this once after calling.</remarks>
        private static IEnumerable <LockFileItem> GetLockFileItems(
            IReadOnlyList <SelectionCriteria> criteria,
            ContentItemCollection items,
            params PatternSet[] patterns)
        {
            // Loop through each criteria taking the first one that matches one or more items.
            foreach (var managedCriteria in criteria)
            {
                var group = items.FindBestItemGroup(
                    managedCriteria,
                    patterns);

                if (group != null)
                {
                    foreach (var item in group.Items)
                    {
                        var    newItem = new LockFileItem(item.Path);
                        object locale;
                        if (item.Properties.TryGetValue("locale", out locale))
                        {
                            newItem.Properties["locale"] = (string)locale;
                        }
                        yield return(newItem);
                    }

                    // Take only the first group that has items
                    break;
                }
            }

            yield break;
        }
Ejemplo n.º 4
0
        public void ContentModel_LibNet46WithSubFoldersAreIgnored()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var criteria = conventions.Criteria.ForFramework(NuGetFramework.Parse("net46"));

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "lib/net46/a.dll",
                "lib/net46/sub/a.dll",
            });

            // Act
            var group = collection.FindBestItemGroup(criteria, conventions.Patterns.RuntimeAssemblies);

            // Assert
            Assert.Equal(1, group.Items.Count);
            Assert.Equal("lib/net46/a.dll", group.Items[0].Path);
        }
Ejemplo n.º 5
0
        public void ContentModel_BuildRootFolderAndTFM()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var criteria = conventions.Criteria.ForFramework(NuGetFramework.AnyFramework);

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "build/packageA.targets",
                "build/packageA.props",
                "build/config.xml",
                "build/net45/task.dll",
                "build/net45/task.targets",
                "build/net45/task.props",
            });

            // Act
            var group = collection.FindBestItemGroup(criteria, conventions.Patterns.MSBuildFiles);
            var items = group.Items.OrderBy(item => item.Path).ToList();

            // Assert
            Assert.Equal(2, items.Count);
            Assert.Equal("build/packageA.props", items[0].Path);
            Assert.Equal("build/packageA.targets", items[1].Path);
        }
Ejemplo n.º 6
0
        private IReadOnlyCollection <IFile> GetAddinAssemblies(DirectoryPath path, PackageReference package)
        {
            if (!_fileSystem.Exist(path))
            {
                _log.Debug("Path not found at {0}.", path);
                return(Array.Empty <IFile>());
            }

            // Get current framework.
            var tfm = NuGetFramework.Parse(_environment.Runtime.BuiltFramework.FullName, DefaultFrameworkNameProvider.Instance);

            // Get current runtime identifier.
            string rid = _environment.Runtime.IsCoreClr ? Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.GetRuntimeIdentifier() : null;

            // Get all candidate files.
            var pathComparer = PathComparer.Default;
            var assemblies   = GetFiles(path, package, new[] { path.FullPath + "/**/*.{dll,so,dylib}" })
                               .Where(file => !"Cake.Core.dll".Equals(file.Path.GetFilename().FullPath, StringComparison.OrdinalIgnoreCase))
                               .ToDictionary(x => path.GetRelativePath(x.Path).FullPath);

            if (assemblies.Count == 0)
            {
                _log.Debug("Assemblies not found at {0}.", path);
            }

            var conventions = new ManagedCodeConventions(RuntimeGraph.Value);
            var collection  = new ContentItemCollection();

            collection.Load(assemblies.Keys);
            var criteria = conventions.Criteria.ForFrameworkAndRuntime(tfm, rid);

            var managedAssemblies = collection.FindBestItemGroup(criteria, conventions.Patterns.RuntimeAssemblies);
            var files             = managedAssemblies?.Items.Select(x => assemblies[x.Path]).Where(x => x.IsClrAssembly()).ToArray() ?? Array.Empty <IFile>();

            if (_environment.Runtime.IsCoreClr)
            {
                var nativeAssemblies = collection.FindBestItemGroup(criteria, conventions.Patterns.NativeLibraries);
                files = (nativeAssemblies?.Items.Select(x => assemblies[x.Path]) ?? Array.Empty <IFile>()).Concat(files).ToArray();
            }
            if (files.Length == 0)
            {
                _log.Debug("Assemblies not found for tfm {0} and rid {1}.", tfm, rid);
            }

            return(files);
        }
Ejemplo n.º 7
0
        public string GetBestSupportedTargetFramework(IEnumerable <string> supportedTargetFrameworks, string targetFramework)
        {
            var contentCollection = new ContentItemCollection();

            contentCollection.Load(supportedTargetFrameworks.Select(t => t + '/').ToArray());

            string[] splitStrings = targetFramework.Split('-');
            string   targetFrameworkWithoutSuffix = splitStrings[0];
            string   targetFrameworkSuffix        = splitStrings.Length > 1 ? splitStrings[1] : string.Empty;

            SelectionCriteria criteria = _conventions.Criteria.ForFrameworkAndRuntime(NuGetFramework.Parse(targetFrameworkWithoutSuffix), targetFrameworkSuffix);
            string            bestTargetFrameworkString = contentCollection.FindBestItemGroup(criteria, _configStringPattern)?.Items[0].Path;

            return(bestTargetFrameworkString?.Remove(bestTargetFrameworkString.Length - 1));
        }
Ejemplo n.º 8
0
        public AppDomainContext LoadPackageAssemblies(
            string appDomainId,
            NuGetFramework framework,
            PackageIdentity packageIdentity)
        {
            var pathResolver = new VersionFolderPathResolver(_settings.GlobalPackagesFolder);
            var hashPath     = pathResolver.GetHashPath(packageIdentity.Id, packageIdentity.Version);

            if (!File.Exists(hashPath))
            {
                throw new InvalidOperationException($"The package '{packageIdentity}' could not found.");
            }

            var installPath = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version);

            using (var packageReader = new PackageFolderReader(installPath))
            {
                var conventions = new ManagedCodeConventions(null);
                var criteria    = conventions.Criteria.ForFramework(framework);

                var files = packageReader
                            .GetFiles()
                            .Select(p => p.Replace(Path.DirectorySeparatorChar, AssetDirectorySeparator))
                            .ToList();

                var contentItems = new ContentItemCollection();
                contentItems.Load(files);

                var runtimeGroup = contentItems.FindBestItemGroup(
                    criteria,
                    conventions.Patterns.RuntimeAssemblies);

                var appDomainContext = _loader.GetAppDomainContext(appDomainId);

                foreach (var asset in runtimeGroup.Items)
                {
                    var absolutePath = Path.Combine(installPath, asset.Path.Replace(AssetDirectorySeparator, Path.DirectorySeparatorChar));
                    _loader.LoadAssembly(appDomainContext, absolutePath);
                }

                return(appDomainContext);
            }
        }
Ejemplo n.º 9
0
        public void ContentModel_NativeRIDFolder_ForFrameworkAndRuntime(string rid, string expected)
        {
            // Arrange
            var runtimeGraph = new RuntimeGraph(
                new List <RuntimeDescription>()
            {
                new RuntimeDescription("any"),
                new RuntimeDescription("win7", new[] { "any" }),
                new RuntimeDescription("win7-x64", new[] { "any", "win7" }),
                new RuntimeDescription("win7-x86", new[] { "any", "win7" })
            },
                new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("netcore50.app")
            });

            var conventions = new ManagedCodeConventions(runtimeGraph);

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "runtimes/win7-x64/native/a.dll",
                "runtimes/win7/native/a.dll",
                "runtimes/linux/native/a.dll",
                "runtimes/any/native/a.dll",
            });

            var criteria = conventions.Criteria.ForFrameworkAndRuntime(NuGetFramework.Parse("netcore50"), rid);

            // Act
            var group = collection.FindBestItemGroup(criteria, conventions.Patterns.NativeLibraries);

            var result = string.Join("|", group.Items.Select(item => item.Path).OrderBy(s => s));

            // Assert
            Assert.Equal(expected, result);
        }
Ejemplo n.º 10
0
        public void ContentModel_IncludesNestedElements()
        {
            // Arrange
            var rid      = "win-x64";
            var runtimes = new List <RuntimeDescription>()
            {
                new RuntimeDescription(rid),
            };

            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    runtimes,
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var criteria = conventions.Criteria.ForFrameworkAndRuntime(NuGetFramework.Parse("net46"), rid);

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                $"tools/net46/{rid}/a.dll",
                $"tools/net46/{rid}/net46/a.dll",
            });

            // Act
            var group = collection.FindBestItemGroup(criteria, conventions.Patterns.ToolsAssemblies);

            // Assert
            Assert.Equal(FrameworkConstants.CommonFrameworks.Net46, (NuGetFramework)group.Properties["tfm"]);
            Assert.Equal(rid, group.Properties["rid"]);
            var paths = group.Items.Select(e => e.Path);

            Assert.Contains($"tools/net46/{rid}/a.dll", paths);
            Assert.Contains($"tools/net46/{rid}/net46/a.dll", paths);
        }
        public void ContentModel_Net46TFMAndAnyRIDisAnyRID()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();
            var rid        = "any";

            collection.Load(new string[]
            {
                $"tools/net46/{rid}/a.dll",
            });

            // Arrange
            var criteria = conventions.Criteria.ForFrameworkAndRuntime(NuGetFramework.Parse("net46"), rid);

            // Act
            var group = collection.FindBestItemGroup(criteria, conventions.Patterns.ToolsAssemblies);

            // Assert
            Assert.Equal(FrameworkConstants.CommonFrameworks.Net46, (NuGetFramework)group.Properties["tfm"]);
            Assert.Equal(rid, group.Properties["rid"]);

            // Act
            List <ContentItemGroup> groups = new();

            collection.PopulateItemGroups(conventions.Patterns.ToolsAssemblies, groups);

            // Assert
            Assert.Equal(1, groups.Count);
            Assert.Equal(FrameworkConstants.CommonFrameworks.Net46, (NuGetFramework)groups.First().Properties["tfm"]);
            Assert.Equal(rid, groups.First().Properties["rid"]);
        }
Ejemplo n.º 12
0
        public void ContentModel_GetNearestRIDAndTFM()
        {
            // Arrange
            var runtimes = new List <RuntimeDescription>()
            {
                new RuntimeDescription("a"),
                new RuntimeDescription("b", new string[] { "a" }),
                new RuntimeDescription("c", new string[] { "b" }),
                new RuntimeDescription("d", new string[] { "c" }),
            };

            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    runtimes,
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var criteria = conventions.Criteria.ForFrameworkAndRuntime(NuGetFramework.Parse("net46"), "d");

            var collection = new ContentItemCollection();
            var rid        = "a";

            collection.Load(new string[]
            {
                $"tools/net46/{rid}/a.dll",
            });

            // Act
            var group = collection.FindBestItemGroup(criteria, conventions.Patterns.ToolsAssemblies);

            // Assert
            Assert.Equal(FrameworkConstants.CommonFrameworks.Net46, (NuGetFramework)group.Properties["tfm"]);
            Assert.Equal(rid, group.Properties["rid"]);
            Assert.Equal($"tools/net46/{rid}/a.dll", group.Items.Single().Path);
        }
Ejemplo n.º 13
0
        public string GetBestSupportedTargetFramework(IEnumerable <string> supportedTargetFrameworks, string targetFramework)
        {
            List <string>        exactConfigs       = supportedTargetFrameworks.Where(t => !t.StartsWith("_")).ToList();
            IEnumerable <string> placeHolderConfigs = supportedTargetFrameworks.Where(t => t.StartsWith("_")).Select(t => t.Substring(1));

            if (placeHolderConfigs.Any())
            {
                exactConfigs.AddRange(placeHolderConfigs);
            }

            var contentCollection = new ContentItemCollection();

            contentCollection.Load(exactConfigs.Select(t => t + '/').ToArray());

            string[] splitStrings = targetFramework.Split('-');
            string   targetFrameworkWithoutSuffix = splitStrings[0];
            string   targetFrameworkSuffix        = splitStrings.Length > 1 ? splitStrings[1] : string.Empty;

            SelectionCriteria criteria = _conventions.Criteria.ForFrameworkAndRuntime(NuGetFramework.Parse(targetFrameworkWithoutSuffix), targetFrameworkSuffix);
            string            bestTargetFrameworkString             = contentCollection.FindBestItemGroup(criteria, _configStringPattern)?.Items[0].Path;
            string            bestTargetFrameworkStringWithoutSlash = bestTargetFrameworkString?.Remove(bestTargetFrameworkString.Length - 1);

            return(placeHolderConfigs.Any() && placeHolderConfigs.Contains(bestTargetFrameworkStringWithoutSlash) ? null : bestTargetFrameworkStringWithoutSlash);
        }
Ejemplo n.º 14
0
        public void ContentModel_GetNearestRIDAndTFMReverse()
        {
            // Arrange
            var runtimes = new List <RuntimeDescription>()
            {
                new RuntimeDescription("a"),
                new RuntimeDescription("b", new string[] { "a" }),
                new RuntimeDescription("c", new string[] { "b" }),
                new RuntimeDescription("d", new string[] { "c" }),
            };

            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    runtimes,
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("netcore50.app")
            }));

            var criteria = conventions.Criteria.ForFrameworkAndRuntime(NuGetFramework.Parse("netcore50"), "d");

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "runtimes/c/lib/netcore50/assembly.dll",
                "runtimes/b/lib/netcore50/assembly.dll",
                "runtimes/a/lib/netcore50/assembly.dll",
            });

            // Act
            var group = collection.FindBestItemGroup(criteria, conventions.Patterns.RuntimeAssemblies);

            // Assert
            Assert.Equal("runtimes/c/lib/netcore50/assembly.dll", group.Items.Single().Path);
        }
        public static IEnumerable<string> GetAssembliesForFramework(FrameworkName framework, IPackage package, IEnumerable<string> packageAssemblies)
        {
            var patterns = PatternDefinitions.DotNetPatterns;

            if (packageAssemblies == null)
            {
                return null;
            }

            var files = packageAssemblies.Select(p => p.Replace(Path.DirectorySeparatorChar, '/')).ToList();
            var contentItems = new ContentItemCollection();
            contentItems.Load(files);

            var criteriaBuilderWithTfm = new SelectionCriteriaBuilder(patterns.Properties.Definitions);

            criteriaBuilderWithTfm = criteriaBuilderWithTfm
                 .Add["tfm", framework];

            var criteria = criteriaBuilderWithTfm.Criteria;

            var allReferencesGroup = contentItems.FindBestItemGroup(criteria, patterns.CompileTimeAssemblies, patterns.ManagedAssemblies);
            List<string> allReferencesGroupAssemblies = null;
            if (allReferencesGroup != null)
            {
                allReferencesGroupAssemblies = allReferencesGroup.Items.Select(t => t.Path).ToList();
            }

            if (allReferencesGroupAssemblies == null)
            {
                return null;
            }

            IEnumerable<string> oldLibGroupAssemblies = null;
            var oldLibGroup = contentItems.FindBestItemGroup(criteria, patterns.ManagedAssemblies);
            if (oldLibGroup != null)
            {
                oldLibGroupAssemblies = oldLibGroup.Items.Select(p => p.Path).ToList();
            }

            // COMPAT: Support lib/contract so older packages can be consumed
            string contractPath = "lib/contract/" + package.Id + ".dll";
            var hasContract = files.Any(path => contractPath.Equals(path, StringComparison.OrdinalIgnoreCase));
            var hasLib = oldLibGroupAssemblies != null && oldLibGroupAssemblies.Any();

            if (hasContract && hasLib && !DnxVersionUtility.IsDesktop(framework))
            {
                allReferencesGroupAssemblies.Clear();
                allReferencesGroupAssemblies.Add(contractPath);
            }

            // See if there's a list of specific references defined for this target framework
            IEnumerable<PackageReferenceSet> referenceSets;
            if (DnxVersionUtility.GetNearest(framework, package.PackageAssemblyReferences.ToList(), out referenceSets))
            {
                // Get the first compatible reference set
                var referenceSet = referenceSets.FirstOrDefault();

                if (referenceSet != null)
                {
                    // Remove all assemblies of which names do not appear in the References list
                    allReferencesGroupAssemblies.RemoveAll(path => path.StartsWith("lib/") 
                                                                   && !referenceSet.References.Contains(Path.GetFileName(path), StringComparer.OrdinalIgnoreCase));
                }
            }

            return allReferencesGroupAssemblies.Select(p => p.Replace('/', Path.DirectorySeparatorChar)).ToList();
        }
Ejemplo n.º 16
0
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(LockFileLibrary library, IPackage package, RestoreContext context, string correctedPackageName)
        {
            var lockFileLib = new LockFileTargetLibrary();

            var framework         = context.FrameworkName;
            var runtimeIdentifier = context.RuntimeName;

            // package.Id is read from nuspec and it might be in wrong casing.
            // correctedPackageName should be the package name used by dependency graph and
            // it has the correct casing that runtime needs during dependency resolution.
            lockFileLib.Name    = correctedPackageName ?? package.Id;
            lockFileLib.Version = package.Version;
            var files        = library.Files.Select(p => p.Replace(Path.DirectorySeparatorChar, '/'));
            var contentItems = new ContentItemCollection();

            contentItems.Load(files);

            IEnumerable <PackageDependencySet> dependencySet;

            if (VersionUtility.GetNearest(framework, package.DependencySets, out dependencySet))
            {
                var set = dependencySet.FirstOrDefault()?.Dependencies?.ToList();

                if (set != null)
                {
                    lockFileLib.Dependencies = set;
                }
            }

            // TODO: Remove this when we do #596
            // ASP.NET Core and .NET Core 5.0 don't have framework reference assemblies
            if (!VersionUtility.IsPackageBased(framework))
            {
                IEnumerable <FrameworkAssemblyReference> frameworkAssemblies;
                if (VersionUtility.GetNearest(framework, package.FrameworkAssemblies, out frameworkAssemblies))
                {
                    AddFrameworkReferences(lockFileLib, framework, frameworkAssemblies);
                }

                // Add framework assemblies with empty supported frameworks
                AddFrameworkReferences(lockFileLib, framework, package.FrameworkAssemblies.Where(f => !f.SupportedFrameworks.Any()));
            }

            var patterns = PatternDefinitions.DotNetPatterns;

            var criteriaBuilderWithTfm    = new SelectionCriteriaBuilder(patterns.Properties.Definitions);
            var criteriaBuilderWithoutTfm = new SelectionCriteriaBuilder(patterns.Properties.Definitions);

            if (context.RuntimeSpecs != null)
            {
                foreach (var runtimeSpec in context.RuntimeSpecs)
                {
                    criteriaBuilderWithTfm = criteriaBuilderWithTfm
                                             .Add["tfm", framework]["rid", runtimeSpec.Name];

                    criteriaBuilderWithoutTfm = criteriaBuilderWithoutTfm
                                                .Add["rid", runtimeSpec.Name];
                }
            }

            criteriaBuilderWithTfm = criteriaBuilderWithTfm
                                     .Add["tfm", framework];

            var criteria = criteriaBuilderWithTfm.Criteria;

            var compileGroup = contentItems.FindBestItemGroup(criteria, patterns.CompileTimeAssemblies, patterns.ManagedAssemblies);

            if (compileGroup != null)
            {
                lockFileLib.CompileTimeAssemblies = compileGroup.Items.Select(t => (LockFileItem)t.Path).ToList();
            }

            var runtimeGroup = contentItems.FindBestItemGroup(criteria, patterns.ManagedAssemblies);

            if (runtimeGroup != null)
            {
                lockFileLib.RuntimeAssemblies = runtimeGroup.Items.Select(p => (LockFileItem)p.Path).ToList();
            }

            var resourceGroup = contentItems.FindBestItemGroup(criteria, patterns.ResourceAssemblies);

            if (resourceGroup != null)
            {
                lockFileLib.ResourceAssemblies = resourceGroup.Items.Select(ToResourceLockFileItem).ToList();
            }

            var nativeGroup = contentItems.FindBestItemGroup(criteriaBuilderWithoutTfm.Criteria, patterns.NativeLibraries);

            if (nativeGroup != null)
            {
                lockFileLib.NativeLibraries = nativeGroup.Items.Select(p => (LockFileItem)p.Path).ToList();
            }

            // COMPAT: Support lib/contract so older packages can be consumed
            string contractPath = "lib/contract/" + package.Id + ".dll";
            var    hasContract  = files.Any(path => path == contractPath);
            var    hasLib       = lockFileLib.RuntimeAssemblies.Any();

            if (hasContract && hasLib && !VersionUtility.IsDesktop(framework))
            {
                lockFileLib.CompileTimeAssemblies.Clear();
                lockFileLib.CompileTimeAssemblies.Add(contractPath);
            }

            // See if there's a list of specific references defined for this target framework
            IEnumerable <PackageReferenceSet> referenceSets;

            if (VersionUtility.GetNearest(framework, package.PackageAssemblyReferences, out referenceSets))
            {
                // Get the first compatible reference set
                var referenceSet = referenceSets.FirstOrDefault();

                if (referenceSet != null)
                {
                    // Remove all assemblies of which names do not appear in the References list
                    lockFileLib.RuntimeAssemblies.RemoveAll(path => path.Path.StartsWith("lib/") && !referenceSet.References.Contains(Path.GetFileName(path), StringComparer.OrdinalIgnoreCase));
                    lockFileLib.CompileTimeAssemblies.RemoveAll(path => path.Path.StartsWith("lib/") && !referenceSet.References.Contains(Path.GetFileName(path), StringComparer.OrdinalIgnoreCase));
                }
            }

            return(lockFileLib);
        }
Ejemplo n.º 17
0
        private LockFileTargetLibrary CreateLockFileTargetLibrary(LocalPackageInfo package, RestoreTargetGraph targetGraph, DefaultPackagePathResolver defaultPackagePathResolver, string correctedPackageName)
        {
            var lockFileLib = new LockFileTargetLibrary();

            var framework         = targetGraph.Framework;
            var runtimeIdentifier = targetGraph.RuntimeIdentifier;

            // package.Id is read from nuspec and it might be in wrong casing.
            // correctedPackageName should be the package name used by dependency graph and
            // it has the correct casing that runtime needs during dependency resolution.
            lockFileLib.Name    = correctedPackageName ?? package.Id;
            lockFileLib.Version = package.Version;

            IList <string>   files;
            var              contentItems    = new ContentItemCollection();
            HashSet <string> referenceFilter = null;

            using (var nupkgStream = File.OpenRead(package.ZipPath))
            {
                var packageReader = new PackageReader(nupkgStream);
                files = packageReader.GetFiles().Select(p => p.Replace(Path.DirectorySeparatorChar, '/')).ToList();

                contentItems.Load(files);

                var dependencySet = packageReader.GetPackageDependencies().GetNearest(framework);
                if (dependencySet != null)
                {
                    var set = dependencySet.Packages;

                    if (set != null)
                    {
                        lockFileLib.Dependencies = set.ToList();
                    }
                }

                var referenceSet = packageReader.GetReferenceItems().GetNearest(framework);
                if (referenceSet != null)
                {
                    referenceFilter = new HashSet <string>(referenceSet.Items, StringComparer.OrdinalIgnoreCase);
                }

                // TODO: Remove this when we do #596
                // ASP.NET Core isn't compatible with generic PCL profiles
                if (!string.Equals(framework.Framework, FrameworkConstants.FrameworkIdentifiers.AspNetCore, StringComparison.OrdinalIgnoreCase) &&
                    !string.Equals(framework.Framework, FrameworkConstants.FrameworkIdentifiers.DnxCore, StringComparison.OrdinalIgnoreCase))
                {
                    var frameworkAssemblies = packageReader.GetFrameworkItems().GetNearest(framework);
                    if (frameworkAssemblies != null)
                    {
                        foreach (var assemblyReference in frameworkAssemblies.Items)
                        {
                            lockFileLib.FrameworkAssemblies.Add(assemblyReference);
                        }
                    }
                }
            }

            var nativeCriteria  = targetGraph.Conventions.Criteria.ForRuntime(targetGraph.RuntimeIdentifier);
            var managedCriteria = targetGraph.Conventions.Criteria.ForFrameworkAndRuntime(framework, targetGraph.RuntimeIdentifier);

            var compileGroup = contentItems.FindBestItemGroup(managedCriteria, targetGraph.Conventions.Patterns.CompileAssemblies, targetGraph.Conventions.Patterns.RuntimeAssemblies);

            if (compileGroup != null)
            {
                lockFileLib.CompileTimeAssemblies = compileGroup.Items.Select(t => t.Path).ToList();
            }

            var runtimeGroup = contentItems.FindBestItemGroup(managedCriteria, targetGraph.Conventions.Patterns.RuntimeAssemblies);

            if (runtimeGroup != null)
            {
                lockFileLib.RuntimeAssemblies = runtimeGroup.Items.Select(p => p.Path).ToList();
            }

            var nativeGroup = contentItems.FindBestItemGroup(nativeCriteria, targetGraph.Conventions.Patterns.NativeLibraries);

            if (nativeGroup != null)
            {
                lockFileLib.NativeLibraries = nativeGroup.Items.Select(p => p.Path).ToList();
            }

            // COMPAT: Support lib/contract so older packages can be consumed
            string contractPath = "lib/contract/" + package.Id + ".dll";
            var    hasContract  = files.Any(path => path == contractPath);
            var    hasLib       = lockFileLib.RuntimeAssemblies.Any();

            if (hasContract && hasLib && !framework.IsDesktop())
            {
                lockFileLib.CompileTimeAssemblies.Clear();
                lockFileLib.CompileTimeAssemblies.Add(contractPath);
            }

            // Apply filters from the <references> node in the nuspec
            if (referenceFilter != null)
            {
                // Remove anything that starts with "lib/" and is NOT specified in the reference filter.
                // runtimes/* is unaffected (it doesn't start with lib/)
                lockFileLib.RuntimeAssemblies     = lockFileLib.RuntimeAssemblies.Where(p => !p.StartsWith("lib/") || referenceFilter.Contains(p)).ToList();
                lockFileLib.CompileTimeAssemblies = lockFileLib.CompileTimeAssemblies.Where(p => !p.StartsWith("lib/") || referenceFilter.Contains(p)).ToList();
            }

            return(lockFileLib);
        }
        public NugetRepositoryEntry ResolveGroups(LocalPackageSourceInfo localPackageSourceInfo)
        {
            var collection = new ContentItemCollection();

            collection.Load(localPackageSourceInfo.Package.Files);
            var allPackageDependencyGroups = localPackageSourceInfo.Package.Nuspec.GetDependencyGroups().ToArray();
            var frameworkReferenceGroups   = localPackageSourceInfo.Package.Nuspec.GetFrameworkRefGroups().ToArray();

            var entry = new NugetRepositoryEntry(localPackageSourceInfo);

            foreach (var target in _targets)
            {
                SelectionCriteria criteria = _conventions.Criteria.ForFrameworkAndRuntime(target.Framework, target.RuntimeIdentifier);

                // The nunit3testadapter package publishes dll's in build/
                var buildAssemblies = new PatternSet(_conventions.Properties, new[]
                {
                    new PatternDefinition("build/{tfm}/{any?}"),
                    new PatternDefinition("build/{assembly?}")
                }, new[]
                {
                    new PatternDefinition("build/{tfm}/{assembly}"),
                    new PatternDefinition("build/{assembly}")
                });

                // shipped debug binaries
                var netcoreappdebugAssemblies = new PatternSet(_conventions.Properties, new[]
                {
                    new PatternDefinition("netcoreappdebug/{tfm}/{any?}"),
                    new PatternDefinition("netcoreappdebug/{assembly?}")
                }, new[]
                {
                    new PatternDefinition("netcoreappdebug/{tfm}/{assembly}"),
                    new PatternDefinition("netcoreappdebug/{assembly}")
                });

                // The analyzer dll's are published in analyzers/ or analyzers/dotnet/cs/
                var analyzerAssemblies = new PatternSet(_conventions.Properties, new []
                {
                    new PatternDefinition("analyzers/dotnet/cs/{assembly?}"),
                    new PatternDefinition("analyzers/{assembly?}")
                }, new []
                {
                    new PatternDefinition("analyzers/dotnet/cs/{assembly}"),
                    new PatternDefinition("analyzers/{assembly}")
                });

                AddIfNotNull(entry.RefItemGroups, target.Framework,
                             collection.FindBestItemGroup(criteria,
                                                          _conventions.Patterns.CompileRefAssemblies,
                                                          _conventions.Patterns.CompileLibAssemblies)
                             ?.Items);

                AddIfNotNull(entry.RuntimeItemGroups, target.Framework,
                             collection.FindBestItemGroup(criteria,
                                                          _conventions.Patterns.RuntimeAssemblies,
                                                          _conventions.Patterns.NativeLibraries,
                                                          buildAssemblies)
                             ?.Items.Where(IsDll));

                AddIfNotNull(entry.DebugRuntimeItemGroups, target.Framework,
                             collection.FindItemGroups(netcoreappdebugAssemblies)
                             .SingleOrDefault()
                             ?.Items.Where(IsDll));

                AddIfNotNull(entry.ContentFileGroups, target.Framework,
                             collection.FindBestItemGroup(criteria,
                                                          _conventions.Patterns.ContentFiles)
                             ?.Items);

                AddIfNotNull(entry.AnalyzerItemGroups, target.Framework,
                             collection.FindItemGroups(analyzerAssemblies)
                             .SingleOrDefault()
                             ?.Items);

                // Merge FrameworkReferences with normal PackageReferences
                var dependencies = NuGetFrameworkUtility.GetNearest(allPackageDependencyGroups, target.Framework);
                var frameworks   = NuGetFrameworkUtility.GetNearest(frameworkReferenceGroups, target.Framework);

                if (dependencies != null || frameworks != null)
                {
                    entry.DependencyGroups.Add(new PackageDependencyGroup(
                                                   dependencies?.TargetFramework ?? frameworks?.TargetFramework,
                                                   new[]
                    {
                        frameworks?.FrameworkReferences.Select(FrameworkDependencyResolver.ConvertToDependency),
                        dependencies?.Packages,
                    }
                                                   .SelectMany(v => v ?? Array.Empty <PackageDependency>())));
                }
            }

            return(entry);
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(
            LockFileLibrary library,
            LocalPackageInfo package,
            RestoreTargetGraph targetGraph,
            VersionFolderPathResolver defaultPackagePathResolver,
            string correctedPackageName,
            LibraryIncludeFlags dependencyType,
            NuGetFramework targetFrameworkOverride,
            IEnumerable <LibraryDependency> dependencies)
        {
            var lockFileLib = new LockFileTargetLibrary();

            var framework         = targetFrameworkOverride ?? targetGraph.Framework;
            var runtimeIdentifier = targetGraph.RuntimeIdentifier;

            // package.Id is read from nuspec and it might be in wrong casing.
            // correctedPackageName should be the package name used by dependency graph and
            // it has the correct casing that runtime needs during dependency resolution.
            lockFileLib.Name    = correctedPackageName ?? package.Id;
            lockFileLib.Version = package.Version;
            lockFileLib.Type    = LibraryType.Package;

            IList <string>   files;
            var              contentItems    = new ContentItemCollection();
            HashSet <string> referenceFilter = null;

            // If the previous LockFileLibrary was given, use that to find the file list. Otherwise read the nupkg.
            if (library == null)
            {
                using (var packageReader = new PackageFolderReader(package.ExpandedPath))
                {
                    if (Path.DirectorySeparatorChar != LockFile.DirectorySeparatorChar)
                    {
                        files = packageReader
                                .GetFiles()
                                .Select(p => p.Replace(Path.DirectorySeparatorChar, LockFile.DirectorySeparatorChar))
                                .ToList();
                    }
                    else
                    {
                        files = packageReader
                                .GetFiles()
                                .ToList();
                    }
                }
            }
            else
            {
                if (Path.DirectorySeparatorChar != LockFile.DirectorySeparatorChar)
                {
                    files = library.Files.Select(p => p.Replace(Path.DirectorySeparatorChar, LockFile.DirectorySeparatorChar)).ToList();
                }
                else
                {
                    files = library.Files;
                }
            }

            contentItems.Load(files);

            // This will throw an appropriate error if the nuspec is missing
            var nuspec = package.Nuspec;

            if (dependencies == null)
            {
                var dependencySet = nuspec
                                    .GetDependencyGroups()
                                    .GetNearest(framework);

                if (dependencySet != null)
                {
                    var set = dependencySet.Packages;

                    if (set != null)
                    {
                        lockFileLib.Dependencies = set.ToList();
                    }
                }
            }
            else
            {
                // Filter the dependency set down to packages and projects.
                // Framework references will not be displayed
                lockFileLib.Dependencies = dependencies
                                           .Where(ld => ld.LibraryRange.TypeConstraintAllowsAnyOf(LibraryDependencyTarget.PackageProjectExternal))
                                           .Select(ld => new PackageDependency(ld.Name, ld.LibraryRange.VersionRange))
                                           .ToList();
            }

            var referenceSet = nuspec.GetReferenceGroups().GetNearest(framework);

            if (referenceSet != null)
            {
                referenceFilter = new HashSet <string>(referenceSet.Items, StringComparer.OrdinalIgnoreCase);
            }

            // Exclude framework references for package based frameworks.
            if (!framework.IsPackageBased)
            {
                var frameworkAssemblies = nuspec.GetFrameworkReferenceGroups().GetNearest(framework);
                if (frameworkAssemblies != null)
                {
                    foreach (var assemblyReference in frameworkAssemblies.Items)
                    {
                        lockFileLib.FrameworkAssemblies.Add(assemblyReference);
                    }
                }
            }

            // Create an ordered list of selection criteria. Each will be applied, if the result is empty
            // fallback frameworks from "imports" will be tried.
            // These are only used for framework/RID combinations where content model handles everything.
            var orderedCriteria = CreateCriteria(targetGraph, framework);

            // Compile
            var compileGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.CompileAssemblies,
                targetGraph.Conventions.Patterns.RuntimeAssemblies);

            lockFileLib.CompileTimeAssemblies.AddRange(compileGroup);

            // Runtime
            var runtimeGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.RuntimeAssemblies);

            lockFileLib.RuntimeAssemblies.AddRange(runtimeGroup);

            // Resources
            var resourceGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.ResourceAssemblies);

            lockFileLib.ResourceAssemblies.AddRange(resourceGroup);

            // Native
            var nativeCriteria = targetGraph.Conventions.Criteria.ForRuntime(targetGraph.RuntimeIdentifier);

            var nativeGroup = contentItems.FindBestItemGroup(
                nativeCriteria,
                targetGraph.Conventions.Patterns.NativeLibraries);

            if (nativeGroup != null)
            {
                lockFileLib.NativeLibraries = nativeGroup.Items.Select(p => new LockFileItem(p.Path)).ToList();
            }

            // content v2 items
            var contentFileGroups = contentItems.FindItemGroups(targetGraph.Conventions.Patterns.ContentFiles);

            // Multiple groups can match the same framework, find all of them
            var contentFileGroupsForFramework = ContentFileUtils.GetContentGroupsForFramework(
                lockFileLib,
                framework,
                contentFileGroups);

            lockFileLib.ContentFiles = ContentFileUtils.GetContentFileGroup(
                framework,
                nuspec,
                contentFileGroupsForFramework);

            // Runtime targets
            // These are applied only to non-RID target graphs.
            // They are not used for compatibility checks.
            if (string.IsNullOrEmpty(runtimeIdentifier))
            {
                // Runtime targets contain all the runtime specific assets
                // that could be contained in the runtime specific target graphs.
                // These items are contained in a flat list and have additional properties
                // for the RID and lock file section the assembly would belong to.
                var runtimeTargetItems = new List <LockFileRuntimeTarget>();

                // Runtime
                runtimeTargetItems.AddRange(GetRuntimeTargetLockFileItems(
                                                targetGraph,
                                                lockFileLib,
                                                contentItems,
                                                framework,
                                                dependencyType,
                                                LibraryIncludeFlags.Runtime,
                                                targetGraph.Conventions.Patterns.RuntimeAssemblies,
                                                "runtime"));

                // Resource
                runtimeTargetItems.AddRange(GetRuntimeTargetLockFileItems(
                                                targetGraph,
                                                lockFileLib,
                                                contentItems,
                                                framework,
                                                dependencyType,
                                                LibraryIncludeFlags.Runtime,
                                                targetGraph.Conventions.Patterns.ResourceAssemblies,
                                                "resource"));

                // Native
                runtimeTargetItems.AddRange(GetRuntimeTargetLockFileItems(
                                                targetGraph,
                                                lockFileLib,
                                                contentItems,
                                                framework,
                                                dependencyType,
                                                LibraryIncludeFlags.Native,
                                                targetGraph.Conventions.Patterns.NativeLibraries,
                                                "native"));

                lockFileLib.RuntimeTargets = runtimeTargetItems;
            }

            // COMPAT: Support lib/contract so older packages can be consumed
            var contractPath = "lib/contract/" + package.Id + ".dll";
            var hasContract  = files.Any(path => path == contractPath);
            var hasLib       = lockFileLib.RuntimeAssemblies.Any();

            if (hasContract &&
                hasLib &&
                !framework.IsDesktop())
            {
                lockFileLib.CompileTimeAssemblies.Clear();
                lockFileLib.CompileTimeAssemblies.Add(new LockFileItem(contractPath));
            }

            // Apply filters from the <references> node in the nuspec
            if (referenceFilter != null)
            {
                // Remove anything that starts with "lib/" and is NOT specified in the reference filter.
                // runtimes/* is unaffected (it doesn't start with lib/)
                lockFileLib.RuntimeAssemblies     = lockFileLib.RuntimeAssemblies.Where(p => !p.Path.StartsWith("lib/") || referenceFilter.Contains(Path.GetFileName(p.Path))).ToList();
                lockFileLib.CompileTimeAssemblies = lockFileLib.CompileTimeAssemblies.Where(p => !p.Path.StartsWith("lib/") || referenceFilter.Contains(Path.GetFileName(p.Path))).ToList();
            }

            // Exclude items
            if ((dependencyType & LibraryIncludeFlags.Runtime) == LibraryIncludeFlags.None)
            {
                ClearIfExists(lockFileLib.RuntimeAssemblies);
                lockFileLib.FrameworkAssemblies.Clear();
                lockFileLib.ResourceAssemblies.Clear();
            }

            if ((dependencyType & LibraryIncludeFlags.Compile) == LibraryIncludeFlags.None)
            {
                ClearIfExists(lockFileLib.CompileTimeAssemblies);
            }

            if ((dependencyType & LibraryIncludeFlags.Native) == LibraryIncludeFlags.None)
            {
                ClearIfExists(lockFileLib.NativeLibraries);
            }

            if ((dependencyType & LibraryIncludeFlags.ContentFiles) == LibraryIncludeFlags.None &&
                GroupHasNonEmptyItems(lockFileLib.ContentFiles))
            {
                // Empty lock file items still need lock file properties for language, action, and output.
                lockFileLib.ContentFiles.Clear();
                lockFileLib.ContentFiles.Add(ContentFileUtils.CreateEmptyItem());
            }

            return(lockFileLib);
        }
Ejemplo n.º 20
0
        private LockFileTargetLibrary CreateLockFileTargetLibrary(LocalPackageInfo package, RestoreTargetGraph targetGraph, DefaultPackagePathResolver defaultPackagePathResolver, string correctedPackageName)
        {
            var lockFileLib = new LockFileTargetLibrary();

            var framework = targetGraph.Framework;
            var runtimeIdentifier = targetGraph.RuntimeIdentifier;

            // package.Id is read from nuspec and it might be in wrong casing.
            // correctedPackageName should be the package name used by dependency graph and
            // it has the correct casing that runtime needs during dependency resolution.
            lockFileLib.Name = correctedPackageName ?? package.Id;
            lockFileLib.Version = package.Version;

            IList<string> files;
            var contentItems = new ContentItemCollection();
            HashSet<string> referenceFilter = null;
            using (var nupkgStream = File.OpenRead(package.ZipPath))
            {
                var packageReader = new PackageReader(nupkgStream);
                files = packageReader.GetFiles().Select(p => p.Replace(Path.DirectorySeparatorChar, '/')).ToList();

                contentItems.Load(files);

                var dependencySet = packageReader.GetPackageDependencies().GetNearest(framework);
                if (dependencySet != null)
                {
                    var set = dependencySet.Packages;

                    if (set != null)
                    {
                        lockFileLib.Dependencies = set.ToList();
                    }
                }

                var referenceSet = packageReader.GetReferenceItems().GetNearest(framework);
                if (referenceSet != null)
                {
                    referenceFilter = new HashSet<string>(referenceSet.Items, StringComparer.OrdinalIgnoreCase);
                }

                // TODO: Remove this when we do #596
                // ASP.NET Core isn't compatible with generic PCL profiles
                if (!string.Equals(framework.Framework, FrameworkConstants.FrameworkIdentifiers.AspNetCore, StringComparison.OrdinalIgnoreCase)
                    &&
                    !string.Equals(framework.Framework, FrameworkConstants.FrameworkIdentifiers.DnxCore, StringComparison.OrdinalIgnoreCase))
                {
                    var frameworkAssemblies = packageReader.GetFrameworkItems().GetNearest(framework);
                    if (frameworkAssemblies != null)
                    {
                        foreach (var assemblyReference in frameworkAssemblies.Items)
                        {
                            lockFileLib.FrameworkAssemblies.Add(assemblyReference);
                        }
                    }
                }
            }

            var nativeCriteria = targetGraph.Conventions.Criteria.ForRuntime(targetGraph.RuntimeIdentifier);
            var managedCriteria = targetGraph.Conventions.Criteria.ForFrameworkAndRuntime(framework, targetGraph.RuntimeIdentifier);

            var compileGroup = contentItems.FindBestItemGroup(managedCriteria, targetGraph.Conventions.Patterns.CompileAssemblies, targetGraph.Conventions.Patterns.RuntimeAssemblies);

            if (compileGroup != null)
            {
                lockFileLib.CompileTimeAssemblies = compileGroup.Items.Select(t => new LockFileItem(t.Path)).ToList();
            }

            var runtimeGroup = contentItems.FindBestItemGroup(managedCriteria, targetGraph.Conventions.Patterns.RuntimeAssemblies);
            if (runtimeGroup != null)
            {
                lockFileLib.RuntimeAssemblies = runtimeGroup.Items.Select(p => new LockFileItem(p.Path)).ToList();
            }

            var resourceGroup = contentItems.FindBestItemGroup(managedCriteria, targetGraph.Conventions.Patterns.ResourceAssemblies);
            if (resourceGroup != null)
            {
                lockFileLib.ResourceAssemblies = resourceGroup.Items.Select(ToResourceLockFileItem).ToList();
            }

            var nativeGroup = contentItems.FindBestItemGroup(nativeCriteria, targetGraph.Conventions.Patterns.NativeLibraries);
            if (nativeGroup != null)
            {
                lockFileLib.NativeLibraries = nativeGroup.Items.Select(p => new LockFileItem(p.Path)).ToList();
            }

            // COMPAT: Support lib/contract so older packages can be consumed
            var contractPath = "lib/contract/" + package.Id + ".dll";
            var hasContract = files.Any(path => path == contractPath);
            var hasLib = lockFileLib.RuntimeAssemblies.Any();

            if (hasContract
                && hasLib
                && !framework.IsDesktop())
            {
                lockFileLib.CompileTimeAssemblies.Clear();
                lockFileLib.CompileTimeAssemblies.Add(new LockFileItem(contractPath));
            }

            // Apply filters from the <references> node in the nuspec
            if (referenceFilter != null)
            {
                // Remove anything that starts with "lib/" and is NOT specified in the reference filter.
                // runtimes/* is unaffected (it doesn't start with lib/)
                lockFileLib.RuntimeAssemblies = lockFileLib.RuntimeAssemblies.Where(p => !p.Path.StartsWith("lib/") || referenceFilter.Contains(p.Path)).ToList();
                lockFileLib.CompileTimeAssemblies = lockFileLib.CompileTimeAssemblies.Where(p => !p.Path.StartsWith("lib/") || referenceFilter.Contains(p.Path)).ToList();
            }

            return lockFileLib;
        }
Ejemplo n.º 21
0
        private void WriteTargetsAndProps(PackageSpec project, List<RestoreTargetGraph> targetGraphs, NuGetv3LocalRepository repository)
        {
            // Get the runtime-independent graphs
            var tfmGraphs = targetGraphs.Where(g => string.IsNullOrEmpty(g.RuntimeIdentifier)).ToList();
            if (tfmGraphs.Count > 1)
            {
                var name = $"{project.Name}.nuget.targets";
                var path = Path.Combine(project.BaseDirectory, name);
                _log.LogInformation($"Generating MSBuild file {name}");

                GenerateMSBuildErrorFile(path);
                return;
            }
            var graph = tfmGraphs[0];

            var pathResolver = new DefaultPackagePathResolver(repository.RepositoryRoot);

            var targets = new List<string>();
            var props = new List<string>();
            foreach (var library in graph.Flattened.Distinct().OrderBy(g => g.Data.Match.Library))
            {
                var package = repository.FindPackagesById(library.Key.Name).FirstOrDefault(p => p.Version == library.Key.Version);
                if (package != null)
                {
                    var criteria = graph.Conventions.Criteria.ForFramework(graph.Framework);
                    var contentItemCollection = new ContentItemCollection();
                    using (var nupkgStream = File.OpenRead(package.ZipPath))
                    {
                        var reader = new PackageReader(nupkgStream);
                        contentItemCollection.Load(reader.GetFiles());
                    }

                    // Find MSBuild thingies
                    var buildItems = contentItemCollection.FindBestItemGroup(criteria, graph.Conventions.Patterns.MSBuildFiles);
                    if (buildItems != null)
                    {
                        // We need to additionally filter to items that are named "{packageId}.targets" and "{packageId}.props"
                        // Filter by file name here and we'll filter by extension when we add things to the lists.
                        var items = buildItems.Items
                            .Where(item => Path.GetFileNameWithoutExtension(item.Path).Equals(package.Id, StringComparison.OrdinalIgnoreCase))
                            .ToList();

                        targets.AddRange(items
                            .Select(c => c.Path)
                            .Where(path => Path.GetExtension(path).Equals(".targets", StringComparison.OrdinalIgnoreCase))
                            .Select(path => Path.Combine(pathResolver.GetPackageDirectory(package.Id, package.Version), path.Replace('/', Path.DirectorySeparatorChar))));
                        props.AddRange(items
                            .Select(c => c.Path)
                            .Where(path => Path.GetExtension(path).Equals(".props", StringComparison.OrdinalIgnoreCase))
                            .Select(path => Path.Combine(pathResolver.GetPackageDirectory(package.Id, package.Version), path.Replace('/', Path.DirectorySeparatorChar))));
                    }
                }
            }

            // Generate the files as needed
            var targetsName = $"{project.Name}.nuget.targets";
            var propsName = $"{project.Name}.nuget.props";
            var targetsPath = Path.Combine(project.BaseDirectory, targetsName);
            var propsPath = Path.Combine(project.BaseDirectory, propsName);

            if (targets.Any())
            {
                _log.LogInformation($"Generating MSBuild file {targetsName}");

                GenerateImportsFile(repository, targetsPath, targets);
            }
            else if (File.Exists(targetsPath))
            {
                File.Delete(targetsPath);
            }

            if (props.Any())
            {
                _log.LogInformation($"Generating MSBuild file {propsName}");

                GenerateImportsFile(repository, propsPath, props);
            }
            else if (File.Exists(propsPath))
            {
                File.Delete(propsPath);
            }
        }
Ejemplo n.º 22
0
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(LockFileLibrary library, IPackage package, RestoreContext context, string correctedPackageName)
        {
            var lockFileLib = new LockFileTargetLibrary();

            var framework = context.FrameworkName;
            var runtimeIdentifier = context.RuntimeName;

            // package.Id is read from nuspec and it might be in wrong casing.
            // correctedPackageName should be the package name used by dependency graph and
            // it has the correct casing that runtime needs during dependency resolution.
            lockFileLib.Name = correctedPackageName ?? package.Id;
            lockFileLib.Version = package.Version;
            var files = library.Files.Select(p => p.Replace(Path.DirectorySeparatorChar, '/'));
            var contentItems = new ContentItemCollection();
            contentItems.Load(files);

            IEnumerable<PackageDependencySet> dependencySet;
            if (VersionUtility.GetNearest(framework, package.DependencySets, out dependencySet))
            {
                var set = dependencySet.FirstOrDefault()?.Dependencies?.ToList();

                if (set != null)
                {
                    lockFileLib.Dependencies = set;
                }
            }

            // TODO: Remove this when we do #596
            // ASP.NET Core and .NET Core 5.0 don't have framework reference assemblies
            if (!VersionUtility.IsPackageBased(framework))
            {
                IEnumerable<FrameworkAssemblyReference> frameworkAssemblies;
                if (VersionUtility.GetNearest(framework, package.FrameworkAssemblies, out frameworkAssemblies))
                {
                    AddFrameworkReferences(lockFileLib, framework, frameworkAssemblies);
                }

                // Add framework assemblies with empty supported frameworks
                AddFrameworkReferences(lockFileLib, framework, package.FrameworkAssemblies.Where(f => !f.SupportedFrameworks.Any()));
            }

            var patterns = PatternDefinitions.DotNetPatterns;

            var criteriaBuilderWithTfm = new SelectionCriteriaBuilder(patterns.Properties.Definitions);
            var criteriaBuilderWithoutTfm = new SelectionCriteriaBuilder(patterns.Properties.Definitions);

            if (context.RuntimeSpecs != null)
            {
                foreach (var runtimeSpec in context.RuntimeSpecs)
                {
                    criteriaBuilderWithTfm = criteriaBuilderWithTfm
                        .Add["tfm", framework]["rid", runtimeSpec.Name];

                    criteriaBuilderWithoutTfm = criteriaBuilderWithoutTfm
                        .Add["rid", runtimeSpec.Name];
                }
            }

            criteriaBuilderWithTfm = criteriaBuilderWithTfm
                .Add["tfm", framework];

            var criteria = criteriaBuilderWithTfm.Criteria;

            var compileGroup = contentItems.FindBestItemGroup(criteria, patterns.CompileTimeAssemblies, patterns.ManagedAssemblies);
            if (compileGroup != null)
            {
                lockFileLib.CompileTimeAssemblies = compileGroup.Items.Select(t => (LockFileItem)t.Path).ToList();
            }

            var runtimeGroup = contentItems.FindBestItemGroup(criteria, patterns.ManagedAssemblies);
            if (runtimeGroup != null)
            {
                lockFileLib.RuntimeAssemblies = runtimeGroup.Items.Select(p => (LockFileItem)p.Path).ToList();
            }

            var resourceGroup = contentItems.FindBestItemGroup(criteria, patterns.ResourceAssemblies);
            if (resourceGroup != null)
            {
                lockFileLib.ResourceAssemblies = resourceGroup.Items.Select(ToResourceLockFileItem).ToList();
            }

            var nativeGroup = contentItems.FindBestItemGroup(criteriaBuilderWithoutTfm.Criteria, patterns.NativeLibraries);
            if (nativeGroup != null)
            {
                lockFileLib.NativeLibraries = nativeGroup.Items.Select(p => (LockFileItem)p.Path).ToList();
            }

            // COMPAT: Support lib/contract so older packages can be consumed
            string contractPath = "lib/contract/" + package.Id + ".dll";
            var hasContract = files.Any(path => path == contractPath);
            var hasLib = lockFileLib.RuntimeAssemblies.Any();

            if (hasContract && hasLib && !VersionUtility.IsDesktop(framework))
            {
                lockFileLib.CompileTimeAssemblies.Clear();
                lockFileLib.CompileTimeAssemblies.Add(contractPath);
            }

            // See if there's a list of specific references defined for this target framework
            IEnumerable<PackageReferenceSet> referenceSets;
            if (VersionUtility.GetNearest(framework, package.PackageAssemblyReferences, out referenceSets))
            {
                // Get the first compatible reference set
                var referenceSet = referenceSets.FirstOrDefault();

                if (referenceSet != null)
                {
                    // Remove all assemblies of which names do not appear in the References list
                    lockFileLib.RuntimeAssemblies.RemoveAll(path => path.Path.StartsWith("lib/") && !referenceSet.References.Contains(Path.GetFileName(path), StringComparer.OrdinalIgnoreCase));
                    lockFileLib.CompileTimeAssemblies.RemoveAll(path => path.Path.StartsWith("lib/") && !referenceSet.References.Contains(Path.GetFileName(path), StringComparer.OrdinalIgnoreCase));
                }
            }

            return lockFileLib;
        }
Ejemplo n.º 23
0
        private void WriteTargetsAndProps(PackageSpec project, List <RestoreTargetGraph> targetGraphs, NuGetv3LocalRepository repository)
        {
            // Get the runtime-independent graphs
            var tfmGraphs = targetGraphs.Where(g => string.IsNullOrEmpty(g.RuntimeIdentifier)).ToList();

            if (tfmGraphs.Count > 1)
            {
                var name = $"{project.Name}.nuget.targets";
                var path = Path.Combine(project.BaseDirectory, name);
                _log.LogInformation($"Generating MSBuild file {name}");

                GenerateMSBuildErrorFile(path);
                return;
            }
            var graph = tfmGraphs[0];

            var pathResolver = new DefaultPackagePathResolver(repository.RepositoryRoot);

            var targets = new List <string>();
            var props   = new List <string>();

            foreach (var library in graph.Flattened.Distinct().OrderBy(g => g.Data.Match.Library))
            {
                var package = repository.FindPackagesById(library.Key.Name).FirstOrDefault(p => p.Version == library.Key.Version);
                if (package != null)
                {
                    var criteria = graph.Conventions.Criteria.ForFramework(graph.Framework);
                    var contentItemCollection = new ContentItemCollection();
                    using (var nupkgStream = File.OpenRead(package.ZipPath))
                    {
                        var reader = new PackageReader(nupkgStream);
                        contentItemCollection.Load(reader.GetFiles());
                    }

                    // Find MSBuild thingies
                    var buildItems = contentItemCollection.FindBestItemGroup(criteria, graph.Conventions.Patterns.MSBuildFiles);
                    if (buildItems != null)
                    {
                        // We need to additionally filter to items that are named "{packageId}.targets" and "{packageId}.props"
                        // Filter by file name here and we'll filter by extension when we add things to the lists.
                        var items = buildItems.Items
                                    .Where(item => Path.GetFileNameWithoutExtension(item.Path).Equals(package.Id, StringComparison.OrdinalIgnoreCase))
                                    .ToList();

                        targets.AddRange(items
                                         .Select(c => c.Path)
                                         .Where(path => Path.GetExtension(path).Equals(".targets", StringComparison.OrdinalIgnoreCase))
                                         .Select(path => Path.Combine(pathResolver.GetPackageDirectory(package.Id, package.Version), path.Replace('/', Path.DirectorySeparatorChar))));
                        props.AddRange(items
                                       .Select(c => c.Path)
                                       .Where(path => Path.GetExtension(path).Equals(".props", StringComparison.OrdinalIgnoreCase))
                                       .Select(path => Path.Combine(pathResolver.GetPackageDirectory(package.Id, package.Version), path.Replace('/', Path.DirectorySeparatorChar))));
                    }
                }
            }

            // Generate the files as needed
            var targetsName = $"{project.Name}.nuget.targets";
            var propsName   = $"{project.Name}.nuget.props";
            var targetsPath = Path.Combine(project.BaseDirectory, targetsName);
            var propsPath   = Path.Combine(project.BaseDirectory, propsName);

            if (targets.Any())
            {
                _log.LogInformation($"Generating MSBuild file {targetsName}");

                GenerateImportsFile(repository, targetsPath, targets);
            }
            else if (File.Exists(targetsPath))
            {
                File.Delete(targetsPath);
            }

            if (props.Any())
            {
                _log.LogInformation($"Generating MSBuild file {propsName}");

                GenerateImportsFile(repository, propsPath, props);
            }
            else if (File.Exists(propsPath))
            {
                File.Delete(propsPath);
            }
        }