Example #1
0
        /// <summary>
        /// Replace excluded asset groups with _._ if they have > 0 items.
        /// </summary>
        private static void ExcludeItems(LockFileTargetLibrary lockFileLib, LibraryIncludeFlags dependencyType)
        {
            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());
            }

            if ((dependencyType & LibraryIncludeFlags.Build) == LibraryIncludeFlags.None)
            {
                ClearIfExists(lockFileLib.Build);
                ClearIfExists(lockFileLib.BuildMultiTargeting);
            }
        }
Example #2
0
        private static List <LockFileRuntimeTarget> GetRuntimeTargetLockFileItems(
            ContentItemCollection contentItems,
            NuGetFramework framework,
            LibraryIncludeFlags dependencyType,
            LibraryIncludeFlags groupType,
            PatternSet patternSet,
            string assetType,
            MaccatalystFallback maccatalystFallback)
        {
            var groups = contentItems.FindItemGroups(patternSet).ToList();

            var groupsForFramework = GetContentGroupsForFramework(
                framework,
                groups,
                ManagedCodeConventions.PropertyNames.RuntimeIdentifier,
                maccatalystFallback);

            var items = GetRuntimeTargetItems(groupsForFramework, assetType);

            if ((dependencyType & groupType) == LibraryIncludeFlags.None)
            {
                ClearIfExists <LockFileRuntimeTarget>(items);
            }

            return(items);
        }
Example #3
0
        private string ReadLibraryIncludeFlags(LibraryIncludeFlags includeFlags)
        {
            if ((includeFlags & LibraryIncludeFlags.All) == LibraryIncludeFlags.All)
            {
                return("All");
            }

            var flagString       = "";
            var allFlagsAndNames = new List <Tuple <string, LibraryIncludeFlags> >
            {
                Tuple.Create("Analyzers", LibraryIncludeFlags.Analyzers),
                Tuple.Create("Build", LibraryIncludeFlags.Build),
                Tuple.Create("Compile", LibraryIncludeFlags.Compile),
                Tuple.Create("ContentFiles", LibraryIncludeFlags.ContentFiles),
                Tuple.Create("Native", LibraryIncludeFlags.Native),
                Tuple.Create("Runtime", LibraryIncludeFlags.Runtime)
            };

            foreach (var flagAndName in allFlagsAndNames)
            {
                var name = flagAndName.Item1;
                var flag = flagAndName.Item2;

                if ((includeFlags & flag) == flag)
                {
                    if (!string.IsNullOrEmpty(flagString))
                    {
                        flagString += ";";
                    }
                    flagString += name;
                }
            }

            return(flagString);
        }
Example #4
0
        public void GetFlags_WhenFlagsIsSingleValue_ReturnsFlag(
            LibraryIncludeFlags input,
            LibraryIncludeFlags expectedResult)
        {
            LibraryIncludeFlags actualResult = LibraryIncludeFlagUtils.GetFlags(new[] { input.ToString() });

            Assert.Equal(expectedResult, actualResult);
        }
Example #5
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);
        }
        Task <bool> InstallPackageAsync(string packageId, string version, LibraryIncludeFlags includeType, LibraryIncludeFlags suppressParent)
        {
            var packageIdentity = new PackageIdentity(packageId, NuGetVersion.Parse(version));
            var versionRange    = new VersionRange(packageIdentity.Version);

            var installationContext = CreateInstallationContext(includeType, suppressParent);

            return(project.InstallPackageAsync(packageId, versionRange, context, installationContext, CancellationToken.None));
        }
Example #7
0
 /// <summary>
 /// Create a library for a project.
 /// </summary>
 public static LockFileTargetLibrary CreateLockFileTargetProject(
     GraphItem <RemoteResolveResult> graphItem,
     LibraryIdentity library,
     LibraryIncludeFlags dependencyType,
     RestoreTargetGraph targetGraph,
     ProjectStyle rootProjectStyle)
 {
     return(CreateLockFileTargetProject(graphItem, library, dependencyType, targetGraph, rootProjectStyle, maccatalystFallback: null));
 }
Example #8
0
 public LibraryDependency(
     LibraryRange libraryRange,
     LibraryDependencyType type,
     LibraryIncludeFlags includeType,
     LibraryIncludeFlags suppressParent,
     IList <NuGetLogCode> noWarn,
     bool autoReferenced,
     bool generatePathProperty) : this(libraryRange, type, includeType, suppressParent, noWarn, autoReferenced, generatePathProperty, versionCentrallyManaged : false, libraryDependencyReferenceType : LibraryDependencyReferenceType.Direct)
 {
 }
        /// <summary>
        /// Gets the <see cref="LibraryIncludeFlags" /> for the specified value.
        /// </summary>
        /// <param name="value">A semicolon delimited list of include flags.</param>
        /// <param name="defaultValue">The default value ot return if the value contains no flags.</param>
        /// <returns>The <see cref="LibraryIncludeFlags" /> for the specified value, otherwise the <paramref name="defaultValue" />.</returns>
        private static LibraryIncludeFlags GetLibraryIncludeFlags(string value, LibraryIncludeFlags defaultValue)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return(defaultValue);
            }

            string[] parts = MSBuildStringUtility.Split(value);

            return(parts.Length > 0 ? LibraryIncludeFlagUtils.GetFlags(parts) : defaultValue);
        }
Example #10
0
 public static LockFileTargetLibrary CreateLockFileTargetLibrary(
     LockFileLibrary library,
     LocalPackageInfo package,
     RestoreTargetGraph targetGraph,
     LibraryIncludeFlags dependencyType,
     NuGetFramework targetFrameworkOverride,
     IEnumerable <LibraryDependency> dependencies,
     LockFileBuilderCache cache)
 {
     return(CreateLockFileTargetLibrary(libraryDependency: null, library, package, targetGraph, dependencyType, targetFrameworkOverride, dependencies, cache));
 }
        private static LibraryIncludeFlags GetIncludeFlags(string value, LibraryIncludeFlags defaultValue)
        {
            var parts = MSBuildStringUtility.Split(value);

            if (parts.Length > 0)
            {
                return(LibraryIncludeFlagUtils.GetFlags(parts));
            }
            else
            {
                return(defaultValue);
            }
        }
Example #12
0
        public void GetFlags_WhenFlagsIsMultipleValues_ReturnsCombinationOfValues()
        {
            LibraryIncludeFlags[] expectedFlags = new[]
            {
                LibraryIncludeFlags.Runtime,
                LibraryIncludeFlags.Compile,
                LibraryIncludeFlags.Build
            };

            LibraryIncludeFlags flags = LibraryIncludeFlagUtils.GetFlags(expectedFlags.Select(flag => flag.ToString()));

            Assert.Equal("Runtime, Compile, Build", flags.ToString());
        }
Example #13
0
        /// <summary>
        /// Runtime targets
        /// These are applied only to non-RID target graphs.
        /// They are not used for compatibility checks.
        /// </summary>
        private static void AddRuntimeTargets(
            RestoreTargetGraph targetGraph,
            LibraryIncludeFlags dependencyType,
            LockFileTargetLibrary lockFileLib,
            NuGetFramework framework,
            string runtimeIdentifier,
            ContentItemCollection contentItems,
            MaccatalystFallback maccatalystFallback)
        {
            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(
                                                contentItems,
                                                framework,
                                                dependencyType,
                                                LibraryIncludeFlags.Runtime,
                                                targetGraph.Conventions.Patterns.RuntimeAssemblies,
                                                "runtime",
                                                maccatalystFallback));

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

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

                lockFileLib.RuntimeTargets = runtimeTargetItems;
            }
        }
Example #14
0
 public static LockFileTargetLibrary CreateLockFileTargetLibrary(
     LockFileLibrary library,
     LocalPackageInfo package,
     RestoreTargetGraph targetGraph,
     LibraryIncludeFlags dependencyType)
 {
     return(CreateLockFileTargetLibrary(
                library,
                package,
                targetGraph,
                dependencyType: dependencyType,
                targetFrameworkOverride: null,
                dependencies: null));
 }
 public LibraryDependency(
     LibraryRange libraryRange,
     LibraryDependencyType type,
     LibraryIncludeFlags includeType,
     LibraryIncludeFlags suppressParent,
     IList <NuGetLogCode> noWarn,
     bool autoReferenced)
 {
     LibraryRange   = libraryRange;
     Type           = type;
     IncludeType    = includeType;
     SuppressParent = suppressParent;
     NoWarn         = noWarn;
     AutoReferenced = autoReferenced;
 }
Example #16
0
 public static LockFileTargetLibrary CreateLockFileTargetLibrary(
     LockFileLibrary library,
     LocalPackageInfo package,
     RestoreTargetGraph targetGraph,
     LibraryIncludeFlags dependencyType)
 {
     return(CreateLockFileTargetLibrary(
                aliases: null,
                library,
                package,
                targetGraph,
                dependencyType: dependencyType,
                targetFrameworkOverride: null,
                dependencies: null,
                cache: new LockFileBuilderCache(),
                maccatalystFallback: null));
 }
Example #17
0
        public void Equals_WithExcludeAssets(LibraryIncludeFlags left, LibraryIncludeFlags right, bool expected)
        {
            var leftSide = new ProjectRestoreReference()
            {
                ProjectPath       = "path",
                ProjectUniqueName = "path",
                ExcludeAssets     = left
            };

            var rightSide = new ProjectRestoreReference()
            {
                ProjectPath       = "path",
                ProjectUniqueName = "path",
                ExcludeAssets     = right
            };

            AssertEquality(expected, leftSide, rightSide);
        }
 public static LockFileTargetLibrary CreateLockFileTargetLibrary(
     LockFileLibrary library,
     LocalPackageInfo package,
     RestoreTargetGraph targetGraph,
     VersionFolderPathResolver defaultPackagePathResolver,
     string correctedPackageName,
     LibraryIncludeFlags dependencyType)
 {
     return(CreateLockFileTargetLibrary(
                library,
                package,
                targetGraph,
                defaultPackagePathResolver,
                correctedPackageName,
                dependencyType: dependencyType,
                targetFrameworkOverride: null,
                dependencies: null));
 }
Example #19
0
        private static void AddToolsAssets(LockFileLibrary library,
                                           LocalPackageInfo package,
                                           RestoreTargetGraph targetGraph,
                                           LibraryIncludeFlags dependencyType,
                                           LockFileTargetLibrary lockFileLib,
                                           NuGetFramework framework,
                                           string runtimeIdentifier,
                                           ContentItemCollection contentItems,
                                           NuspecReader nuspec,
                                           IReadOnlyList <SelectionCriteria> orderedCriteria)
        {
            var toolsGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.ToolsAssemblies);

            lockFileLib.ToolsAssemblies.AddRange(toolsGroup);
        }
Example #20
0
        public void HashCode_WithPrivateAssets(LibraryIncludeFlags left, LibraryIncludeFlags right, bool expected)
        {
            var leftSide = new ProjectRestoreReference()
            {
                ProjectPath       = "path",
                ProjectUniqueName = "path",
                PrivateAssets     = left
            };

            var rightSide = new ProjectRestoreReference()
            {
                ProjectPath       = "path",
                ProjectUniqueName = "path",
                PrivateAssets     = right
            };

            AssertHashCode(expected, leftSide, rightSide);
        }
 public LibraryDependency(
     LibraryRange libraryRange,
     LibraryDependencyType type,
     LibraryIncludeFlags includeType,
     LibraryIncludeFlags suppressParent,
     IList <NuGetLogCode> noWarn,
     bool autoReferenced,
     bool generatePathProperty,
     bool versionCentrallyManaged)
 {
     LibraryRange            = libraryRange;
     Type                    = type;
     IncludeType             = includeType;
     SuppressParent          = suppressParent;
     NoWarn                  = noWarn;
     AutoReferenced          = autoReferenced;
     GeneratePathProperty    = generatePathProperty;
     VersionCentrallyManaged = versionCentrallyManaged;
 }
        /// <summary>
        /// Convert set of flag strings into a LibraryIncludeFlags.
        /// </summary>
        public static LibraryIncludeFlags GetFlags(string flags, LibraryIncludeFlags defaultFlags)
        {
            LibraryIncludeFlags result = defaultFlags;

            if (!string.IsNullOrEmpty(flags))
            {
                var splitFlags = flags.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                 .Select(s => s.Trim())
                                 .Where(s => !string.IsNullOrEmpty(s))
                                 .ToArray();

                if (splitFlags.Length > 0)
                {
                    result = GetFlags(splitFlags);
                }
            }

            return(result);
        }
Example #23
0
 internal LibraryDependency(
     LibraryRange libraryRange,
     LibraryIncludeFlags includeType,
     LibraryIncludeFlags suppressParent,
     IList <NuGetLogCode> noWarn,
     bool autoReferenced,
     bool generatePathProperty,
     bool versionCentrallyManaged,
     LibraryDependencyReferenceType libraryDependencyReferenceType,
     string aliases)
 {
     LibraryRange            = libraryRange;
     IncludeType             = includeType;
     SuppressParent          = suppressParent;
     NoWarn                  = noWarn;
     AutoReferenced          = autoReferenced;
     GeneratePathProperty    = generatePathProperty;
     VersionCentrallyManaged = versionCentrallyManaged;
     ReferenceType           = libraryDependencyReferenceType;
     Aliases                 = aliases;
 }
        /// <summary>
        /// Convert library flags to a friendly string.
        /// </summary>
        public static string GetFlagString(LibraryIncludeFlags flags)
        {
            if (flags == LibraryIncludeFlags.None)
            {
                return("none");
            }

            if (flags == LibraryIncludeFlags.All)
            {
                return("all");
            }

            var flagStrings = new List <string>();

            foreach (LibraryIncludeFlags value in Enum.GetValues(typeof(LibraryIncludeFlags)))
            {
                if (value != LibraryIncludeFlags.None && flags.HasFlag(value))
                {
                    flagStrings.Add(value.ToString().ToLowerInvariant());
                }
            }

            return(string.Join(", ", flagStrings));
        }
        public static PackageSpec WithTestProjectReference(this PackageSpec parent, PackageSpec child, LibraryIncludeFlags privateAssets, params NuGetFramework[] frameworks)
        {
            var spec = parent.Clone();

            if (frameworks.Length == 0)
            {
                // Use all frameworks if none were given
                frameworks = spec.TargetFrameworks.Select(e => e.FrameworkName).ToArray();
            }

            foreach (var framework in spec
                     .RestoreMetadata
                     .TargetFrameworks
                     .Where(e => frameworks.Contains(e.FrameworkName)))
            {
                framework.ProjectReferences.Add(new ProjectRestoreReference()
                {
                    ProjectUniqueName = child.RestoreMetadata.ProjectUniqueName,
                    ProjectPath       = child.RestoreMetadata.ProjectPath,
                    PrivateAssets     = privateAssets,
                });
            }

            return(spec);
        }
Example #26
0
        public static LockFileTargetLibrary CreateLockFileTargetLibrary(
            LockFileLibrary library,
            LocalPackageInfo package,
            RestoreTargetGraph targetGraph,
            LibraryIncludeFlags dependencyType,
            NuGetFramework targetFrameworkOverride,
            IEnumerable <LibraryDependency> dependencies)
        {
            var lockFileLib = new LockFileTargetLibrary();

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

            lockFileLib.Name    = 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 nativeGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.NativeLibraries);

            lockFileLib.NativeLibraries.AddRange(nativeGroup);

            // 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(
                                                contentItems,
                                                framework,
                                                dependencyType,
                                                LibraryIncludeFlags.Runtime,
                                                targetGraph.Conventions.Patterns.RuntimeAssemblies,
                                                "runtime"));

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

                // Native
                runtimeTargetItems.AddRange(GetRuntimeTargetLockFileItems(
                                                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);
        }
Example #27
0
        /// <summary>
        /// Replace excluded asset groups with _._ if they have > 0 items.
        /// </summary>
        public static void ExcludeItems(LockFileTargetLibrary lockFileLib, LibraryIncludeFlags dependencyType)
        {
            if ((dependencyType & LibraryIncludeFlags.Runtime) == LibraryIncludeFlags.None)
            {
                ClearIfExists(lockFileLib.RuntimeAssemblies);
                lockFileLib.FrameworkAssemblies.Clear();
                lockFileLib.ResourceAssemblies.Clear();
            }

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

            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());
            }

            if ((dependencyType & LibraryIncludeFlags.BuildTransitive) == LibraryIncludeFlags.None &&
                (dependencyType & LibraryIncludeFlags.Build) == LibraryIncludeFlags.None)
            {
                // If BuildTransitive is excluded then all build assets are cleared.
                ClearIfExists(lockFileLib.Build);
                ClearIfExists(lockFileLib.BuildMultiTargeting);
            }
            else if ((dependencyType & LibraryIncludeFlags.Build) == LibraryIncludeFlags.None)
            {
                if (!lockFileLib.Build.Any(item => item.Path.StartsWith("buildTransitive/", StringComparison.OrdinalIgnoreCase)))
                {
                    // all build assets are from /build folder so just clear them all.
                    ClearIfExists(lockFileLib.Build);
                    ClearIfExists(lockFileLib.BuildMultiTargeting);
                }
                else
                {
                    // only clear /build assets, leaving /BuildTransitive behind
                    var newBuildAssets = new List <LockFileItem>();

                    for (var i = 0; i < lockFileLib.Build.Count; i++)
                    {
                        var currentBuildItem = lockFileLib.Build[i];

                        if (!currentBuildItem.Path.StartsWith("build/", StringComparison.OrdinalIgnoreCase))
                        {
                            newBuildAssets.Add(currentBuildItem);
                        }
                        else
                        {
                            // if current asset is from build then also clear it for BuildMultiTargeting if exists.
                            var multiBuildAsset = lockFileLib.BuildMultiTargeting.FirstOrDefault(
                                item => Path.GetFileName(item.Path).Equals(Path.GetFileName(currentBuildItem.Path), StringComparison.OrdinalIgnoreCase));

                            if (multiBuildAsset != null)
                            {
                                lockFileLib.BuildMultiTargeting.Remove(multiBuildAsset);
                            }
                        }
                    }

                    lockFileLib.Build = newBuildAssets;
                }
            }
        }
Example #28
0
        public static void AddDependencyGroups(IEnumerable <LibraryDependency> dependencies, NuGetFramework framework, PackageBuilder builder)
        {
            ISet <PackageDependency> packageDependencies = new HashSet <PackageDependency>();

            foreach (var dependency in dependencies)
            {
                LibraryIncludeFlags effectiveInclude = dependency.IncludeType & ~dependency.SuppressParent;

                if (dependency.IncludeType == LibraryIncludeFlags.None || dependency.SuppressParent == LibraryIncludeFlags.All)
                {
                    continue;
                }

                if (dependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.Reference)
                {
                    var reference = builder.FrameworkReferences.FirstOrDefault(r => r.AssemblyName == dependency.Name);
                    if (reference == null)
                    {
                        builder.FrameworkReferences.Add(new FrameworkAssemblyReference(dependency.Name, new NuGetFramework [] { framework }));
                    }
                    else
                    {
                        if (!reference.SupportedFrameworks.Contains(framework))
                        {
                            // Add another framework reference by replacing the existing reference
                            var newReference = new FrameworkAssemblyReference(reference.AssemblyName, reference.SupportedFrameworks.Concat(new NuGetFramework[] { framework }));
                            int index        = builder.FrameworkReferences.IndexOf(reference);
                            builder.FrameworkReferences.Remove(reference);
                            builder.FrameworkReferences.Insert(index, newReference);
                        }
                    }
                }
                else
                {
                    List <string> includes = new List <string>();
                    List <string> excludes = new List <string>();
                    if (effectiveInclude == LibraryIncludeFlags.All)
                    {
                        includes.Add(LibraryIncludeFlags.All.ToString());
                    }
                    else if ((effectiveInclude & LibraryIncludeFlags.ContentFiles) == LibraryIncludeFlags.ContentFiles)
                    {
                        includes.AddRange(effectiveInclude.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
                    }
                    else
                    {
                        if ((LibraryIncludeFlagUtils.NoContent & ~effectiveInclude) != LibraryIncludeFlags.None)
                        {
                            excludes.AddRange((LibraryIncludeFlagUtils.NoContent & ~effectiveInclude).ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
                        }
                    }

                    VersionRange version = dependency.LibraryRange.VersionRange;
                    if (!version.HasLowerBound && !version.HasUpperBound)
                    {
                        version = new VersionRange(builder.Version);
                    }

                    packageDependencies.Add(new PackageDependency(dependency.Name, version, includes, excludes));
                }
            }

            var dependencyGroup = builder.DependencyGroups.FirstOrDefault(r => r.TargetFramework.Equals(framework));

            if (dependencyGroup != null)
            {
                var existingDependencies = new HashSet <PackageDependency>(dependencyGroup.Packages);
                foreach (var packageDependency in packageDependencies)
                {
                    PackCommandRunner.AddPackageDependency(packageDependency, existingDependencies);
                }
                var newDependencyGroup = new PackageDependencyGroup(framework, existingDependencies);
                builder.DependencyGroups.Remove(dependencyGroup);
                builder.DependencyGroups.Add(newDependencyGroup);
            }
            else
            {
                builder.DependencyGroups.Add(new PackageDependencyGroup(framework, packageDependencies));
            }
        }
Example #29
0
        /// <summary>
        /// Populate assets for a <see cref="LockFileLibrary"/>.
        /// </summary>
        private static void AddAssets(
            LockFileLibrary library,
            LocalPackageInfo package,
            RestoreTargetGraph targetGraph,
            LibraryIncludeFlags dependencyType,
            LockFileTargetLibrary lockFileLib,
            NuGetFramework framework,
            string runtimeIdentifier,
            IList <string> files,
            ContentItemCollection contentItems,
            NuspecReader nuspec,
            IReadOnlyList <SelectionCriteria> orderedCriteria)
        {
            // Add framework references for desktop projects.
            AddFrameworkReferences(lockFileLib, framework, nuspec);

            // Compile
            // ref takes precedence over lib
            var compileGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.CompileRefAssemblies,
                targetGraph.Conventions.Patterns.CompileLibAssemblies);

            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 nativeGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.NativeLibraries);

            lockFileLib.NativeLibraries.AddRange(nativeGroup);

            // Build
            var buildGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.MSBuildFiles);

            lockFileLib.Build.AddRange(GetBuildItemsForPackageId(buildGroup, library.Name));

            // Build multi targeting
            var buildMultiTargetingGroup = GetLockFileItems(
                orderedCriteria,
                contentItems,
                targetGraph.Conventions.Patterns.MSBuildMultiTargetingFiles);

            lockFileLib.BuildMultiTargeting.AddRange(GetBuildItemsForPackageId(buildMultiTargetingGroup, library.Name));

            // Add content files
            AddContentFiles(targetGraph, lockFileLib, framework, contentItems, nuspec);

            // Runtime targets
            // These are applied only to non-RID target graphs.
            // They are not used for compatibility checks.
            AddRuntimeTargets(targetGraph, dependencyType, lockFileLib, framework, runtimeIdentifier, contentItems);

            // COMPAT: Support lib/contract so older packages can be consumed
            ApplyLibContract(package, lockFileLib, framework, files);

            // Apply filters from the <references> node in the nuspec
            ApplyReferenceFilter(lockFileLib, framework, nuspec);
        }
Example #30
0
        /// <summary>
        /// Create a library for a project.
        /// </summary>
        public static LockFileTargetLibrary CreateLockFileTargetProject(
            GraphItem <RemoteResolveResult> graphItem,
            LibraryIdentity library,
            LibraryIncludeFlags dependencyType,
            RestoreTargetGraph targetGraph,
            ProjectStyle rootProjectStyle)
        {
            var localMatch = (LocalMatch)graphItem.Data.Match;

            // Target framework information is optional and may not exist for csproj projects
            // that do not have a project.json file.
            string projectFramework = null;
            object frameworkInfoObject;

            if (localMatch.LocalLibrary.Items.TryGetValue(
                    KnownLibraryProperties.TargetFrameworkInformation,
                    out frameworkInfoObject))
            {
                // Retrieve the resolved framework name, if this is null it means that the
                // project is incompatible. This is marked as Unsupported.
                var targetFrameworkInformation = (TargetFrameworkInformation)frameworkInfoObject;
                projectFramework = targetFrameworkInformation.FrameworkName?.DotNetFrameworkName
                                   ?? NuGetFramework.UnsupportedFramework.DotNetFrameworkName;
            }

            // Create the target entry
            var projectLib = new LockFileTargetLibrary()
            {
                Name      = library.Name,
                Version   = library.Version,
                Type      = LibraryType.Project,
                Framework = projectFramework,

                // Find all dependencies which would be in the nuspec
                // Include dependencies with no constraints, or package/project/external
                // Exclude suppressed dependencies, the top level project is not written
                // as a target so the node depth does not matter.
                Dependencies = graphItem.Data.Dependencies
                               .Where(
                    d => (d.LibraryRange.TypeConstraintAllowsAnyOf(
                              LibraryDependencyTarget.PackageProjectExternal)) &&
                    d.SuppressParent != LibraryIncludeFlags.All)
                               .Select(d => GetDependencyVersionRange(d))
                               .ToList()
            };

            if (rootProjectStyle == ProjectStyle.PackageReference)
            {
                // Add files under asset groups
                object filesObject;
                object msbuildPath;
                if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.MSBuildProjectPath, out msbuildPath))
                {
                    var files      = new List <ProjectRestoreMetadataFile>();
                    var fileLookup = new Dictionary <string, ProjectRestoreMetadataFile>(StringComparer.OrdinalIgnoreCase);

                    // Find the project path, this is provided by the resolver
                    var msbuildFilePathInfo = new FileInfo((string)msbuildPath);

                    // Ensure a trailing slash for the relative path helper.
                    var projectDir = PathUtility.EnsureTrailingSlash(msbuildFilePathInfo.Directory.FullName);

                    // Read files from the project if they were provided.
                    if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.ProjectRestoreMetadataFiles, out filesObject))
                    {
                        files.AddRange((List <ProjectRestoreMetadataFile>)filesObject);
                    }

                    var targetFrameworkShortName = targetGraph.Framework.GetShortFolderName();
                    var libAnyPath = $"lib/{targetFrameworkShortName}/any.dll";

                    if (files.Count == 0)
                    {
                        // If the project did not provide a list of assets, add in default ones.
                        // These are used to detect transitive vs non-transitive project references.
                        var absolutePath = Path.Combine(projectDir, "bin", "placeholder", $"{localMatch.Library.Name}.dll");

                        files.Add(new ProjectRestoreMetadataFile(libAnyPath, absolutePath));
                    }

                    // Process and de-dupe files
                    for (var i = 0; i < files.Count; i++)
                    {
                        var path = files[i].PackagePath;

                        // LIBANY avoid compatibility checks and will always be used.
                        if (LIBANY.Equals(path, StringComparison.Ordinal))
                        {
                            path = libAnyPath;
                        }

                        if (!fileLookup.ContainsKey(path))
                        {
                            fileLookup.Add(path, files[i]);
                        }
                    }

                    var contentItems = new ContentItemCollection();
                    contentItems.Load(fileLookup.Keys);

                    // 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, targetGraph.Framework);

                    // Compile
                    // ref takes precedence over lib
                    var compileGroup = GetLockFileItems(
                        orderedCriteria,
                        contentItems,
                        targetGraph.Conventions.Patterns.CompileRefAssemblies,
                        targetGraph.Conventions.Patterns.CompileLibAssemblies);

                    projectLib.CompileTimeAssemblies.AddRange(
                        ConvertToProjectPaths(fileLookup, projectDir, compileGroup));

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

                    projectLib.RuntimeAssemblies.AddRange(
                        ConvertToProjectPaths(fileLookup, projectDir, runtimeGroup));
                }
            }

            // Add frameworkAssemblies for projects
            object frameworkAssembliesObject;

            if (localMatch.LocalLibrary.Items.TryGetValue(
                    KnownLibraryProperties.FrameworkAssemblies,
                    out frameworkAssembliesObject))
            {
                projectLib.FrameworkAssemblies.AddRange((List <string>)frameworkAssembliesObject);
            }

            // Exclude items
            ExcludeItems(projectLib, dependencyType);

            return(projectLib);
        }