예제 #1
0
        /// <summary>
        /// Get a ContentItemCollection of the package files.
        /// </summary>
        /// <remarks>Library is optional.</remarks>
        public ContentItemCollection GetContentItems(LockFileLibrary library, LocalPackageInfo package)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            var identity = new PackageIdentity(package.Id, package.Version);

            if (!_contentItems.TryGetValue(identity, out var collection))
            {
                collection = new ContentItemCollection();

                if (library == null)
                {
                    // Read folder
                    collection.Load(package.Files);
                }
                else
                {
                    // Use existing library
                    collection.Load(library.Files);
                }

                _contentItems.Add(identity, collection);
            }

            return(collection);
        }
예제 #2
0
        public void ContentModel_LibNoFilesAtRootNoAnyGroup()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

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

            List <ContentItemGroup> itemGroups = new();

            collection.PopulateItemGroups(conventions.Patterns.RuntimeAssemblies, itemGroups);
            var groups = itemGroups
                         .Select(group => ((NuGetFramework)group.Properties["tfm"]))
                         .ToList();

            // Assert
            Assert.Equal(0, groups.Count(framework => framework == NuGetFramework.AnyFramework));
        }
예제 #3
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);
        }
예제 #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);
        }
예제 #5
0
        public void ContentModel_LibRootAndTFM()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

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

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

            collection.PopulateItemGroups(conventions.Patterns.RuntimeAssemblies, itemGroups);
            var groups = itemGroups
                         .OrderBy(group => ((NuGetFramework)group.Properties["tfm"]).GetShortFolderName())
                         .ToList();

            // Assert
            Assert.Equal(2, groups.Count);
            Assert.Equal(NuGetFramework.Parse("net"), groups[0].Properties["tfm"]);
            Assert.Equal(NuGetFramework.Parse("net46"), groups[1].Properties["tfm"]);
        }
예제 #6
0
        public void ContentModel_LibRootFolderOnly()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

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

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

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

            // Assert
            Assert.Equal(1, groups.Count);
            Assert.Equal(NuGetFramework.Parse("net"), groups[0].Properties["tfm"]);
        }
예제 #7
0
        public void ContentModel_BuildRootFolderRandomFiles()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

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

            // Act
            var groups = collection.FindItemGroups(conventions.Patterns.MSBuildFiles);

            // Assert
            Assert.Equal(1, groups.Count());
            Assert.Equal(NuGetFramework.Parse("net45"), groups.First().Properties["tfm"] as NuGetFramework);
        }
예제 #8
0
        public void ContentModel_MSBuildAnyMapsToDotnet()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "build/any/a.targets",
            });

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

            collection.PopulateItemGroups(conventions.Patterns.MSBuildFiles, itemGroups);
            var groups = itemGroups
                         .OrderBy(group => ((NuGetFramework)group.Properties["tfm"]).GetShortFolderName())
                         .ToList();

            // Assert
            Assert.Equal(1, groups.Count);
            Assert.Equal(FrameworkConstants.CommonFrameworks.DotNet, (NuGetFramework)groups[0].Properties["tfm"]);
        }
예제 #9
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);
        }
예제 #10
0
        public void ContentModel_ResourcesAnyMapsToDotnet()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "lib/any/en-us/a.resources.dll",
            });

            // Act
            var groups = collection.FindItemGroups(conventions.Patterns.ResourceAssemblies)
                         .OrderBy(group => ((NuGetFramework)group.Properties["tfm"]).GetShortFolderName())
                         .ToList();

            // Assert
            Assert.Equal(1, groups.Count);
            Assert.Equal(FrameworkConstants.CommonFrameworks.DotNet, (NuGetFramework)groups[0].Properties["tfm"]);
        }
예제 #11
0
        public void ContentModel_AnyTFMDefaultsToAnyandAnyRIDisAnyRID()
        {
            // 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/any/{rid}/a.dll",
            });

            // Act
            var groups = collection.FindItemGroups(conventions.Patterns.ToolsAssemblies)
                         .ToList();

            // Assert
            Assert.Equal(1, groups.Count);
            Assert.Equal(NuGetFramework.AnyFramework, (NuGetFramework)groups.First().Properties["tfm"]);
            Assert.Equal(rid, groups.First().Properties["rid"]);
        }
예제 #12
0
        public void ContentModel_BuildNoFilesAtRootNoAnyGroup()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "build/net46/packageA.targets",
                "build/net45/packageA.targets",
                "build/net35/packageA.targets",
                "build/net20/packageA.targets",
                "build/uap10.0/packageA.targets",
            });

            // Act
            var groups = collection.FindItemGroups(conventions.Patterns.MSBuildFiles)
                         .Select(group => ((NuGetFramework)group.Properties["tfm"]))
                         .ToList();

            // Assert
            Assert.Equal(0, groups.Count(framework => framework == NuGetFramework.AnyFramework));
        }
예제 #13
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);
        }
예제 #14
0
        public void ContentModel_NoRidMatchReturnsNothing()
        {
            // 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/nativeassets/win81/a.dll",
                "runtimes/win7/nativeassets/win8/a.dll",
                "runtimes/win7/native/a.dll",
            });

            var criteria = conventions.Criteria.ForFrameworkAndRuntime(NuGetFramework.Parse("win8"), "linux");

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

            // Assert
            Assert.Null(group);
        }
예제 #15
0
        public void ContentModel_ContentFilesAnyMapsToAny()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "contentFiles/any/any/a.txt",
            });

            // Act
            var groups = collection.FindItemGroups(conventions.Patterns.ContentFiles)
                         .OrderBy(group => ((NuGetFramework)group.Properties["tfm"]).GetShortFolderName())
                         .ToList();

            // Assert
            Assert.Equal(1, groups.Count);
            Assert.Equal(NuGetFramework.AnyFramework, (NuGetFramework)groups[0].Properties["tfm"]);
        }
예제 #16
0
        public void ContentModel_NativeSubFoldersAllowed()
        {
            // 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/sub/a.dll"
            });

            var criteria1 = conventions.Criteria.ForRuntime("win7-x64");

            // Act
            var group1 = collection.FindBestItemGroup(criteria1, conventions.Patterns.NativeLibraries);

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

            // Assert
            Assert.Equal("runtimes/win7-x64/native/sub/a.dll", result1);
        }
예제 #17
0
        public void ContentModel_NoTFMAndRuntimeIdentifierNoMatch()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

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

            // Act
            var groups = collection.FindItemGroups(conventions.Patterns.ToolsAssemblies)
                         .Select(group => ((NuGetFramework)group.Properties["tfm"]))
                         .ToList();

            // Assert
            Assert.Equal(0, groups.Count);
        }
예제 #18
0
        private static HashSet <FrameworkRuntimePair> GetAvailableFrameworkRuntimePairs(CompatibilityData compatibilityData, RestoreTargetGraph graph)
        {
            var available = new HashSet <FrameworkRuntimePair>();

            var contentItems = new ContentItemCollection();

            contentItems.Load(compatibilityData.Files);


            if (compatibilityData.TargetLibrary.PackageType.Contains(PackageType.DotnetTool))
            {
                foreach (var group in contentItems.FindItemGroups(graph.Conventions.Patterns.ToolsAssemblies))
                {
                    group.Properties.TryGetValue(ManagedCodeConventions.PropertyNames.RuntimeIdentifier, out var ridObj);
                    group.Properties.TryGetValue(ManagedCodeConventions.PropertyNames.TargetFrameworkMoniker, out var tfmObj);

                    var tfm = tfmObj as NuGetFramework;
                    var rid = ridObj as string;
                    if (tfm?.IsSpecificFramework == true)
                    {
                        available.Add(new FrameworkRuntimePair(tfm, rid));
                    }
                }
            }

            return(available);
        }
예제 #19
0
        public void ContentModel_BuildAnyFolderTreatedAsDotNet()
        {
            // Arrange
            var conventions = new ManagedCodeConventions(
                new RuntimeGraph(
                    new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("net46.app")
            }));

            var collection = new ContentItemCollection();

            collection.Load(new string[]
            {
                "build/any/packageA.targets"
            });

            // Act
            var framework = collection.FindItemGroups(conventions.Patterns.MSBuildFiles)
                            .Select(group => ((NuGetFramework)group.Properties["tfm"]))
                            .Single();

            // Assert
            Assert.Equal(".NETPlatform", framework.Framework);
        }
예제 #20
0
        public void ContentFiles_InvalidPaths()
        {
            // 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[]
            {
                "contentFiles/any/config1.xml",
                "contentFiles/in.valid/net45/config2.xml",
                "contentFiles/any/config3.xml",
                "contentFiles/config4.xml",
                "contentFiles",
                "contentFiles/+/uap10.0.0/config6.xml"
            });

            // Act
            var contentFileGroups = collection.FindItemGroups(conventions.Patterns.ContentFiles);

            // Assert
            Assert.Equal(0, contentFileGroups.Count());
        }
예제 #21
0
        public void ContentFiles_Empty()
        {
            // 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[]
            {
                // empty
            });

            // Act
            var contentFileGroups = collection.FindItemGroups(conventions.Patterns.ContentFiles);

            // Assert
            Assert.Equal(0, contentFileGroups.Count());
        }
예제 #22
0
        private void DumpPackageContents(LibraryDescription library, SelectionCriteria criteria)
        {
            var packageContents = new ContentItemCollection();

            packageContents.Load(library.Path);

            var group = packageContents.FindBestItemGroup(criteria, Patterns.ManagedAssemblies);

            if (group == null)
            {
                // No matching groups
                return;
            }

            Logger.WriteInformation(library.ToString().White());
            Logger.WriteInformation("=========================");
            foreach (var item in group.Items)
            {
                Logger.WriteInformation(item.Path.White());

                foreach (var property in item.Properties)
                {
                    Logger.WriteInformation(property.Key.Yellow() + " = " + property.Value);
                }
            }

            Logger.WriteInformation("=========================");
            Console.WriteLine();
        }
예제 #23
0
        private static void ValidateFileFrameworks(IEnumerable <IPackageFile> files)
        {
            var set = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var file in files.Where(t => t.Path != null).Select(t => PathUtility.GetPathWithDirectorySeparator(t.Path)))
            {
                set.Add(file);
            }

            var managedCodeConventions = new ManagedCodeConventions(new RuntimeGraph());
            var collection             = new ContentItemCollection();

            collection.Load(set.Select(path => path.Replace('\\', '/')).ToArray());

            var patterns = managedCodeConventions.Patterns;

            var frameworkPatterns = new List <PatternSet>()
            {
                patterns.RuntimeAssemblies,
                patterns.CompileRefAssemblies,
                patterns.CompileLibAssemblies,
                patterns.NativeLibraries,
                patterns.ResourceAssemblies,
                patterns.MSBuildFiles,
                patterns.ContentFiles,
                patterns.ToolsAssemblies,
                patterns.EmbedAssemblies,
                patterns.MSBuildTransitiveFiles
            };
            var warnPaths = new HashSet <string>();

            var frameworksMissingPlatformVersion = new HashSet <string>();

            foreach (var pattern in frameworkPatterns)
            {
                IEnumerable <ContentItemGroup> targetedItemGroups = ContentExtractor.GetContentForPattern(collection, pattern);
                foreach (ContentItemGroup group in targetedItemGroups)
                {
                    foreach (ContentItem item in group.Items)
                    {
                        var framework = (NuGetFramework)item.Properties["tfm"];
                        if (framework == null)
                        {
                            continue;
                        }

                        if (framework.HasPlatform && framework.PlatformVersion == FrameworkConstants.EmptyVersion)
                        {
                            frameworksMissingPlatformVersion.Add(framework.GetShortFolderName());
                        }
                    }
                }
            }

            if (frameworksMissingPlatformVersion.Any())
            {
                throw new PackagingException(NuGetLogCode.NU1012, string.Format(CultureInfo.CurrentCulture, Strings.MissingTargetPlatformVersionsFromIncludedFiles, string.Join(", ", frameworksMissingPlatformVersion.OrderBy(str => str))));
            }
        }
예제 #24
0
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(
            LockFileLibrary library,
            LocalPackageInfo package,
            RestoreTargetGraph targetGraph,
            LibraryIncludeFlags dependencyType,
            NuGetFramework targetFrameworkOverride,
            IEnumerable <LibraryDependency> dependencies)
        {
            LockFileTargetLibrary lockFileLib = null;

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

            // Read files from package
            var files        = GetPackageFiles(library, package);
            var contentItems = new ContentItemCollection();

            contentItems.Load(files);

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

            // Create fallback criteria, this will always be one or more.
            var orderedCriteriaSets = CreateOrderedCriteriaSets(targetGraph, framework);

            for (var i = 0; i < orderedCriteriaSets.Count; i++)
            {
                // Create a new library each time to avoid
                // assets being added from other criteria.
                lockFileLib = new LockFileTargetLibrary()
                {
                    Name    = package.Id,
                    Version = package.Version,
                    Type    = LibraryType.Package
                };

                // Populate assets
                AddAssets(library, package, targetGraph, dependencyType, lockFileLib, framework, runtimeIdentifier, files, contentItems, nuspec, orderedCriteriaSets[i]);

                // Check if compatile assets were found.
                // If no compatible assets were found and this is the last check
                // continue on with what was given, this will fail in the normal
                // compat verification.
                if (CompatibilityChecker.HasCompatibleAssets(lockFileLib))
                {
                    // Stop when compatible assets are found.
                    break;
                }
            }

            // Add dependencies
            AddDependencies(dependencies, lockFileLib, framework, nuspec);

            // Exclude items
            ExcludeItems(lockFileLib, dependencyType);

            return(lockFileLib);
        }
예제 #25
0
        /// <summary>
        /// Extracts the lib files to execution directory
        /// </summary>
        /// <param name="package">
        /// The package to extract
        /// </param>
        /// <param name="runtime">
        /// The current runtime
        /// </param>
        /// <param name="frameworkName">
        /// The current framework name
        /// </param>
        /// <param name="executionDir">
        /// The execution directory to load packages
        /// </param>
        /// <param name="logAction">The log writing action</param>
        /// <returns>
        /// The list of extracted files
        /// </returns>
        private static IEnumerable <string> ExtractPackage(
            DownloadResourceResult package,
            string runtime,
            NuGetFramework frameworkName,
            string executionDir,
            Action <string> logAction = null)
        {
            try
            {
                var id    = package.PackageReader.GetIdentity();
                var files = NuGetFrameworkUtility.GetNearest(package.PackageReader.GetLibItems(), frameworkName)?.Items.ToList()
                            ?? NuGetFrameworkUtility.GetNearest(package.PackageReader.GetToolItems(), frameworkName)?.Items.ToList();

                if (files == null || files.Count == 0)
                {
                    var collection = new ContentItemCollection();
                    collection.Load(package.PackageReader.GetFiles());

                    var conventions = new ManagedCodeConventions(runtimeGraph);
                    var criteria    = conventions.Criteria.ForFrameworkAndRuntime(
                        NuGetFramework.ParseFrameworkName(
                            PackageRepositoryExtensions.CurrentRuntime,
                            DefaultFrameworkNameProvider.Instance),
                        runtime);

                    files = collection.FindBestItemGroup(criteria, conventions.Patterns.NativeLibraries)?.Items
                            .Select(i => i.Path).ToList();
                    if (files == null || files.Count == 0)
                    {
                        files = collection.FindBestItemGroup(criteria, conventions.Patterns.RuntimeAssemblies)?.Items
                                .Select(i => i.Path).ToList();
                    }

                    if (files == null || files.Count == 0)
                    {
                        return(new string[0]);
                    }
                    else
                    {
                        logAction?.Invoke($"{id.Id}: {string.Join(", ", files)}");
                    }
                }

                foreach (var file in files)
                {
                    using (var fileStream = File.Create(Path.Combine(executionDir, Path.GetFileName(file) ?? file)))
                    {
                        package.PackageReader.GetStream(file).CopyTo(fileStream);
                    }
                }

                return(files.Select(file => Path.GetFileName(file) ?? file));
            }
            finally
            {
                package.Dispose();
            }
        }
        public void GetRelatedFileExtensionProperty_SingleAssemblyAsset_GetNullProperty(string assembly, string[] assetsPaths, string expectedRelatedProperty)
        {
            // Arrange
            var collection = new ContentItemCollection();

            collection.Load(assetsPaths);

            // Act
            string relatedProperty = collection.GetRelatedFileExtensionProperty(assembly, CreateAssetsFromPathList(assetsPaths));

            // Assert
            Assert.Equal(expectedRelatedProperty, relatedProperty);
        }
예제 #27
0
        public NuGetAssetResolver(string runtimeFile, IEnumerable<string> packageItems)
        {
            RuntimeGraph runtimeGraph = null;

            if (!String.IsNullOrEmpty(runtimeFile))
            {
                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(runtimeFile);
            }
            _conventions = new ManagedCodeConventions(runtimeGraph);

            _sourceItems = new ContentItemCollection();
            _sourceItems.Load(packageItems);
        }
예제 #28
0
        public NuGetAssetResolver(string runtimeFile, IEnumerable <string> packageItems)
        {
            RuntimeGraph runtimeGraph = null;

            if (!String.IsNullOrEmpty(runtimeFile))
            {
                runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(runtimeFile);
            }
            _conventions = new ManagedCodeConventions(runtimeGraph);

            _sourceItems = new ContentItemCollection();
            _sourceItems.Load(packageItems);
        }
        private void LoadContents(Library library)
        {
            var contents = new ContentItemCollection();
            var files    = library.GetItem <IEnumerable <string> >("files");

            if (files != null)
            {
                contents.Load(files);
            }
            else
            {
                var packageInfo = library.GetItem <LocalPackageInfo>("package");

                if (packageInfo == null)
                {
                    return;
                }

                contents.Load(packageInfo.ExpandedPath);
            }

            library.Items["contents"] = contents;
        }
예제 #30
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));
        }
        private static IEnumerable <NuGetFramework> GetPackageFrameworks(
            CompatibilityData compatibilityData,
            RestoreTargetGraph graph)
        {
            var available = new HashSet <NuGetFramework>();

            var contentItems = new ContentItemCollection();

            contentItems.Load(compatibilityData.Files);

            var patterns = new[]
            {
                graph.Conventions.Patterns.ResourceAssemblies,
                graph.Conventions.Patterns.CompileRefAssemblies,
                graph.Conventions.Patterns.RuntimeAssemblies,
                graph.Conventions.Patterns.EmbedAssemblies,
                graph.Conventions.Patterns.ContentFiles
            };

            List <ContentItemGroup> itemGroups = new();

            foreach (var pattern in patterns)
            {
                itemGroups.Clear();
                contentItems.PopulateItemGroups(pattern, itemGroups);
                foreach (var group in itemGroups)
                {
                    // lib/net45/subfolder/a.dll will be returned as a group with zero items since sub
                    // folders are not allowed. Completely empty groups are not compatible, a group with
                    // _._ would contain _._ as an item.
                    if (group.Items.Count > 0)
                    {
                        group.Properties.TryGetValue(ManagedCodeConventions.PropertyNames.RuntimeIdentifier, out var ridObj);
                        group.Properties.TryGetValue(ManagedCodeConventions.PropertyNames.TargetFrameworkMoniker, out var tfmObj);

                        var tfm = tfmObj as NuGetFramework;

                        // RID specific items should be ignored here since they are only used in the runtime assembly check
                        if (ridObj == null && tfm?.IsSpecificFramework == true)
                        {
                            available.Add(tfm);
                        }
                    }
                }
            }

            return(available);
        }
        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();
        }
예제 #33
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);
            }
        }
예제 #34
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;
        }
예제 #35
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;
        }