private static LibraryDependency ToPackageLibraryDependency(IVsReferenceItem item)
        {
            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: item.Name,
                    versionRange: GetVersionRange(item),
                    typeConstraint: LibraryDependencyTarget.Package),

                // Mark packages coming from the SDK as AutoReferenced
                AutoReferenced = GetPropertyBoolOrFalse(item, "IsImplicitlyDefined")
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                includeAssets: GetPropertyValueOrNull(item, IncludeAssets),
                excludeAssets: GetPropertyValueOrNull(item, ExcludeAssets),
                privateAssets: GetPropertyValueOrNull(item, PrivateAssets));

            return(dependency);
        }
Beispiel #2
0
        public override async Task <bool> InstallPackageAsync(
            string packageId,
            VersionRange range,
            INuGetProjectContext _,
            BuildIntegratedInstallationContext __,
            CancellationToken token)
        {
            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: packageId,
                    versionRange: range,
                    typeConstraint: LibraryDependencyTarget.Package),
                SuppressParent = __.SuppressParent,
                IncludeType    = __.IncludeType
            };

            await ProjectServices.References.AddOrUpdatePackageReferenceAsync(dependency, token);

            return(true);
        }
        public void TransitiveCentralPackageVersions_TryAdd_DuplicatesAreIgnored()
        {
            // Arrange
            var transitiveCentralPackageVersions = new RemoteDependencyWalker.TransitiveCentralPackageVersions();
            var centralPackageVersionDependency  = new LibraryDependency()
            {
                LibraryRange = new LibraryRange("name1", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package),
            };
            bool resultAdd1 = transitiveCentralPackageVersions.TryAdd(centralPackageVersionDependency);
            bool resultAdd2 = transitiveCentralPackageVersions.TryAdd(centralPackageVersionDependency);

            // Assert
            Assert.True(resultAdd1);
            Assert.False(resultAdd2);

            // Once the data is added it cannot be re-added even if after TryTake
            bool resultTake1 = transitiveCentralPackageVersions.TryTake(out LibraryDependency centralPackageVersionTake1);
            bool resultAdd3  = transitiveCentralPackageVersions.TryAdd(centralPackageVersionDependency);

            Assert.True(resultTake1);
            Assert.False(resultAdd3);
        }
        public void TransitiveCentralPackageVersions_AddAndTake()
        {
            // Arrange
            var transitiveCentralPackageVersions = new RemoteDependencyWalker.TransitiveCentralPackageVersions();
            var centralPackageVersionDependency  = new LibraryDependency()
            {
                LibraryRange = new LibraryRange("name1", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package),
            };

            bool resultAdd   = transitiveCentralPackageVersions.TryAdd(centralPackageVersionDependency);
            bool resultTake1 = transitiveCentralPackageVersions.TryTake(out LibraryDependency centralPackageVersionTake1);
            // nothing more to take
            bool resultTake2 = transitiveCentralPackageVersions.TryTake(out LibraryDependency centralPackageVersionTake2);

            // Assert
            Assert.True(resultAdd);
            Assert.True(resultTake1);
            Assert.False(resultTake2);

            Assert.Equal(centralPackageVersionDependency, centralPackageVersionTake1);
            Assert.Null(centralPackageVersionTake2);
        }
        private TargetFrameworkInformation CreateTargetFrameworkInformation(List<CentralPackageVersion> centralVersionDependencies)
        {
            NuGetFramework nugetFramework = new NuGetFramework("net40");
            var dependencyFoo = new LibraryDependency(new LibraryRange("foo", VersionRange.All, LibraryDependencyTarget.All),
                LibraryIncludeFlags.All,
                LibraryIncludeFlags.All,
                new List<Common.NuGetLogCode>(),
                autoReferenced: true,
                generatePathProperty: true,
                versionCentrallyManaged: false,
                LibraryDependencyReferenceType.Direct,
                aliases: "Alias",
                versionOverride: null);

            var downloadDependency = new DownloadDependency("foo", VersionRange.All);
            var frameworkDependency = new FrameworkDependency("framework", FrameworkDependencyFlags.All);

            var dependencies = new List<LibraryDependency>() { dependencyFoo };
            var assetTargetFallback = true;
            var warn = false;

            TargetFrameworkInformation tfi = new TargetFrameworkInformation()
            {
                AssetTargetFallback = assetTargetFallback,
                Dependencies = dependencies,
                Warn = warn,
                FrameworkName = nugetFramework,
            };

            foreach (var cdep in centralVersionDependencies)
            {
                tfi.CentralPackageVersions.Add(cdep.Name, cdep);
            }

            tfi.DownloadDependencies.Add(downloadDependency);
            tfi.FrameworkReferences.Add(frameworkDependency);

            return tfi;
        }
        private static void AddPackageReferences(PackageSpec spec, IEnumerable <IMSBuildItem> items)
        {
            foreach (var item in GetItemByType(items, "Dependency"))
            {
                var dependency = new LibraryDependency
                {
                    LibraryRange = new LibraryRange(
                        name: item.GetProperty("Id"),
                        versionRange: GetVersionRange(item),
                        typeConstraint: LibraryDependencyTarget.Package),

                    AutoReferenced = IsPropertyTrue(item, "IsImplicitlyDefined"),

                    GeneratePathProperty = IsPropertyTrue(item, "GeneratePathProperty")
                };

                // Add warning suppressions
                foreach (var code in MSBuildStringUtility.GetNuGetLogCodes(item.GetProperty("NoWarn")))
                {
                    dependency.NoWarn.Add(code);
                }

                ApplyIncludeFlags(dependency, item);

                var frameworks = GetFrameworks(item);

                if (frameworks.Count == 0)
                {
                    AddDependencyIfNotExist(spec, dependency);
                }
                else
                {
                    foreach (var framework in frameworks)
                    {
                        AddDependencyIfNotExist(spec, framework, dependency);
                    }
                }
            }
        }
Beispiel #7
0
        internal static TargetFrameworkInformation CreateTargetFrameworkInformation(string tfm = "net461", string alias = null)
        {
            var framework  = NuGetFramework.Parse(tfm);
            var dependency = new LibraryDependency(
                libraryRange: new LibraryRange("Dependency", LibraryDependencyTarget.Package),
                type: LibraryDependencyType.Default,
                includeType: LibraryIncludeFlags.None,
                suppressParent: LibraryIncludeFlags.ContentFiles,
                noWarn: new List <NuGetLogCode>()
            {
                NuGetLogCode.NU1000, NuGetLogCode.NU1001
            },
                autoReferenced: false,
                generatePathProperty: false,
                versionCentrallyManaged: false,
                LibraryDependencyReferenceType.Direct,
                aliases: "stuff");
            var imports = NuGetFramework.Parse("net45"); // This makes no sense in the context of fallback, just for testing :)

            var originalTargetFrameworkInformation = new TargetFrameworkInformation();

            originalTargetFrameworkInformation.TargetAlias   = alias ?? Guid.NewGuid().ToString();
            originalTargetFrameworkInformation.FrameworkName = framework;
            originalTargetFrameworkInformation.Dependencies  = new List <LibraryDependency>()
            {
                dependency
            };
            originalTargetFrameworkInformation.AssetTargetFallback = false;
            originalTargetFrameworkInformation.Imports             = new List <NuGetFramework>()
            {
                imports
            };
            originalTargetFrameworkInformation.DownloadDependencies.Add(new DownloadDependency("X", VersionRange.Parse("1.0.0")));
            originalTargetFrameworkInformation.FrameworkReferences.Add(new FrameworkDependency("frameworkRef", FrameworkDependencyFlags.All));
            originalTargetFrameworkInformation.FrameworkReferences.Add(new FrameworkDependency("FrameworkReference", FrameworkDependencyFlags.None));
            originalTargetFrameworkInformation.RuntimeIdentifierGraphPath = @"path/to/dotnet/sdk/3.0.100/runtime.json";
            originalTargetFrameworkInformation.CentralPackageVersions.Add("CVD", new CentralPackageVersion("CVD", VersionRange.Parse("1.0.0")));
            return(originalTargetFrameworkInformation);
        }
Beispiel #8
0
        private static TargetFrameworkInformation CreateTargetFrameworkInformation()
        {
            var nugetFramework = new NuGetFramework("net40");
            var dependencyFoo  = new LibraryDependency(
                new LibraryRange("foo", versionRange: null, LibraryDependencyTarget.Package),
                LibraryDependencyType.Default,
                LibraryIncludeFlags.All,
                LibraryIncludeFlags.All,
                new List <Common.NuGetLogCode>(),
                autoReferenced: false,
                generatePathProperty: true,
                versionCentrallyManaged: false,
                LibraryDependencyReferenceType.Direct,
                aliases: null);

            var centralVersionFoo = new CentralPackageVersion("foo", VersionRange.Parse("1.0.0"));
            var centralVersionBar = new CentralPackageVersion("bar", VersionRange.Parse("2.0.0"));

            var dependencies = new List <LibraryDependency>()
            {
                dependencyFoo
            };
            var assetTargetFallback = true;
            var warn = false;

            var tfi = new TargetFrameworkInformation()
            {
                AssetTargetFallback = assetTargetFallback,
                Dependencies        = dependencies,
                Warn          = warn,
                FrameworkName = nugetFramework,
            };

            tfi.CentralPackageVersions.Add(centralVersionFoo.Name, centralVersionFoo);
            tfi.CentralPackageVersions.Add(centralVersionBar.Name, centralVersionBar);

            return(tfi);
        }
        public void CentralTransitiveDependencyGroup_EqualObjects()
        {
            // Arrange
            var nuGetFramework = NuGetFramework.Parse("NETStandard2.0");
            var libraryDep     = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    "packageA",
                    VersionRange.Parse("1.0.0"),
                    LibraryDependencyTarget.Package)
            };
            var dependencies = new List <LibraryDependency>()
            {
                libraryDep
            };
            var centralTransitiveDependencyGroup1 = new CentralTransitiveDependencyGroup(nuGetFramework, dependencies);
            var centralTransitiveDependencyGroup2 = new CentralTransitiveDependencyGroup(nuGetFramework, dependencies);

            // Act = Assert
            Assert.True(centralTransitiveDependencyGroup1.Equals(centralTransitiveDependencyGroup1));
            Assert.True(centralTransitiveDependencyGroup1.Equals(centralTransitiveDependencyGroup2));
            Assert.Equal(centralTransitiveDependencyGroup1.GetHashCode(), centralTransitiveDependencyGroup2.GetHashCode());
        }
        public Task <int> ExecuteCommand(PackageReferenceArgs packageReferenceArgs, MSBuildAPIUtility msBuild)
        {
            packageReferenceArgs.Logger.LogInformation(string.Format(CultureInfo.CurrentCulture,
                                                                     Strings.Info_RemovePkgRemovingReference,
                                                                     packageReferenceArgs.PackageId,
                                                                     packageReferenceArgs.ProjectPath));

            //Setup the Credential Service - This allows the msbuild sdk resolver to auth if needed.
            DefaultCredentialServiceUtility.SetupDefaultCredentialService(packageReferenceArgs.Logger, !packageReferenceArgs.Interactive);

            var libraryDependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: packageReferenceArgs.PackageId,
                    versionRange: VersionRange.All,
                    typeConstraint: LibraryDependencyTarget.Package)
            };

            // Remove reference from the project
            var result = msBuild.RemovePackageReference(packageReferenceArgs.ProjectPath, libraryDependency);

            return(Task.FromResult(result));
        }
Beispiel #11
0
        private static LibraryDependency ToPackageLibraryDependency(IVsReferenceItem item, bool cpvmEnabled)
        {
            if (!TryGetVersionRange(item, "Version", out VersionRange versionRange))
            {
                versionRange = cpvmEnabled ? null : VersionRange.All;
            }

            TryGetVersionRange(item, "VersionOverride", out VersionRange versionOverrideRange);

            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: item.Name,
                    versionRange: versionRange,
                    typeConstraint: LibraryDependencyTarget.Package),

                // Mark packages coming from the SDK as AutoReferenced
                AutoReferenced       = GetPropertyBoolOrFalse(item, "IsImplicitlyDefined"),
                GeneratePathProperty = GetPropertyBoolOrFalse(item, "GeneratePathProperty"),
                Aliases         = GetPropertyValueOrNull(item, "Aliases"),
                VersionOverride = versionOverrideRange
            };

            // Add warning suppressions
            foreach (var code in MSBuildStringUtility.GetNuGetLogCodes(GetPropertyValueOrNull(item, ProjectBuildProperties.NoWarn)))
            {
                dependency.NoWarn.Add(code);
            }

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                includeAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.IncludeAssets),
                excludeAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.ExcludeAssets),
                privateAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.PrivateAssets));

            return(dependency);
        }
Beispiel #12
0
        private static void AddOrUpdateDependencyInDependencyList(
            IList <LibraryDependency> list,
            string packageId,
            VersionRange range)
        {
            var dependencies = list.Where(e => StringComparer.OrdinalIgnoreCase.Equals(e.Name, packageId)).ToList();

            if (dependencies.Count != 0)
            {
                foreach (var library in dependencies)
                {
                    library.LibraryRange.VersionRange = range;
                }
            }
            else
            {
                var dependency = new LibraryDependency
                {
                    LibraryRange = new LibraryRange(packageId, range, LibraryDependencyTarget.Package)
                };

                list.Add(dependency);
            }
        }
Beispiel #13
0
        private static TargetFrameworkInformation CreateTargetFrameworkInformation(List <LibraryDependency> dependencies, List <CentralPackageVersion> centralVersionsDependencies, bool cpvmEnabled)
        {
            NuGetFramework nugetFramework = new NuGetFramework("net40");

            TargetFrameworkInformation tfi = new TargetFrameworkInformation()
            {
                AssetTargetFallback = true,
                Warn          = false,
                FrameworkName = nugetFramework,
                Dependencies  = dependencies,
            };

            foreach (var cvd in centralVersionsDependencies)
            {
                tfi.CentralPackageVersions.Add(cvd.Name, cvd);
            }

            if (cpvmEnabled)
            {
                LibraryDependency.ApplyCentralVersionInformation(tfi.Dependencies, tfi.CentralPackageVersions);
            }

            return(tfi);
        }
Beispiel #14
0
 /// <summary>
 /// Returns all package references after evaluating the condition on the item groups.
 /// This method is used when we need package references for a specific target framework.
 /// </summary>
 /// <param name="project">Project for which the package references have to be obtained.</param>
 /// <param name="libraryDependency">Library dependency to get the name of the package</param>
 /// <returns>List of Items containing the package reference for the package.
 /// If the libraryDependency is null then it returns all package references</returns>
 private static IEnumerable <ProjectItem> GetPackageReferences(Project project, LibraryDependency libraryDependency)
 {
     return(GetPackageReferences(project, libraryDependency.Name));
 }
        private async Task <GraphNode <RemoteResolveResult> > CreateGraphNode(
            LibraryRange libraryRange,
            NuGetFramework framework,
            string runtimeName,
            RuntimeGraph runtimeGraph,
            Func <LibraryRange, DependencyResult> predicate,
            GraphEdge <RemoteResolveResult> outerEdge)
        {
            var dependencies        = new List <LibraryDependency>();
            var runtimeDependencies = new HashSet <string>();

            if (!string.IsNullOrEmpty(runtimeName) && runtimeGraph != null)
            {
                // HACK(davidfowl): This is making runtime.json support package redirects

                // Look up any additional dependencies for this package
                foreach (var runtimeDependency in runtimeGraph.FindRuntimeDependencies(runtimeName, libraryRange.Name))
                {
                    var libraryDependency = new LibraryDependency
                    {
                        LibraryRange = new LibraryRange()
                        {
                            Name           = runtimeDependency.Id,
                            VersionRange   = runtimeDependency.VersionRange,
                            TypeConstraint = LibraryDependencyTarget.PackageProjectExternal
                        }
                    };

                    if (StringComparer.OrdinalIgnoreCase.Equals(runtimeDependency.Id, libraryRange.Name))
                    {
                        if (libraryRange.VersionRange != null &&
                            runtimeDependency.VersionRange != null &&
                            libraryRange.VersionRange.MinVersion < runtimeDependency.VersionRange.MinVersion)
                        {
                            libraryRange = libraryDependency.LibraryRange;
                        }
                    }
                    else
                    {
                        // Otherwise it's a dependency of this node
                        dependencies.Add(libraryDependency);
                        runtimeDependencies.Add(libraryDependency.Name);
                    }
                }
            }

            var node = new GraphNode <RemoteResolveResult>(libraryRange)
            {
                // Resolve the dependency from the cache or sources
                Item = await FindLibraryCached(
                    _context.FindLibraryEntryCache,
                    libraryRange,
                    framework,
                    outerEdge,
                    CancellationToken.None)
            };

            Debug.Assert(node.Item != null, "FindLibraryCached should return an unresolved item instead of null");
            if (node.Key.VersionRange != null &&
                node.Key.VersionRange.IsFloating)
            {
                var cacheKey = new LibraryRangeCacheKey(node.Key, framework);

                _context.FindLibraryEntryCache.TryAdd(cacheKey, Task.FromResult(node.Item));
            }

            var tasks = new List <Task <GraphNode <RemoteResolveResult> > >();

            if (dependencies.Count > 0)
            {
                // Create a new item on this node so that we can update it with the new dependencies from
                // runtime.json files
                // We need to clone the item since they can be shared across multiple nodes
                node.Item = new GraphItem <RemoteResolveResult>(node.Item.Key)
                {
                    Data = new RemoteResolveResult()
                    {
                        Dependencies = dependencies.Concat(node.Item.Data.Dependencies.Where(d => !runtimeDependencies.Contains(d.Name))).ToList(),
                        Match        = node.Item.Data.Match
                    }
                };
            }

            foreach (var dependency in node.Item.Data.Dependencies)
            {
                // Skip dependencies if the dependency edge has 'all' excluded and
                // the node is not a direct dependency.
                if (outerEdge == null ||
                    dependency.SuppressParent != LibraryIncludeFlags.All)
                {
                    var result = predicate(dependency.LibraryRange);

                    if (result == DependencyResult.Acceptable)
                    {
                        // Dependency edge from the current node to the dependency
                        var innerEdge = new GraphEdge <RemoteResolveResult>(outerEdge, node.Item, dependency);

                        tasks.Add(CreateGraphNode(
                                      dependency.LibraryRange,
                                      framework,
                                      runtimeName,
                                      runtimeGraph,
                                      ChainPredicate(predicate, node, dependency),
                                      innerEdge));
                    }
                    else
                    {
                        // Keep the node in the tree if we need to look at it later
                        if (result == DependencyResult.PotentiallyDowngraded ||
                            result == DependencyResult.Cycle)
                        {
                            var dependencyNode = new GraphNode <RemoteResolveResult>(dependency.LibraryRange)
                            {
                                Disposition = result == DependencyResult.Cycle ? Disposition.Cycle : Disposition.PotentiallyDowngraded
                            };

                            dependencyNode.OuterNode = node;
                            node.InnerNodes.Add(dependencyNode);
                        }
                    }
                }
            }

            while (tasks.Any())
            {
                // Wait for any node to finish resolving
                var task = await Task.WhenAny(tasks);

                // Extract the resolved node
                tasks.Remove(task);
                var dependencyNode = await task;
                dependencyNode.OuterNode = node;

                node.InnerNodes.Add(dependencyNode);
            }

            return(node);
        }
        private Func <LibraryRange, DependencyResult> ChainPredicate(Func <LibraryRange, DependencyResult> predicate, GraphNode <RemoteResolveResult> node, LibraryDependency dependency)
        {
            var item = node.Item;

            return(library =>
            {
                if (StringComparer.OrdinalIgnoreCase.Equals(item.Data.Match.Library.Name, library.Name))
                {
                    return DependencyResult.Cycle;
                }

                foreach (var d in item.Data.Dependencies)
                {
                    if (d != dependency && library.IsEclipsedBy(d.LibraryRange))
                    {
                        if (d.LibraryRange.VersionRange != null &&
                            library.VersionRange != null &&
                            !IsGreaterThanOrEqualTo(d.LibraryRange.VersionRange, library.VersionRange))
                        {
                            return DependencyResult.PotentiallyDowngraded;
                        }

                        return DependencyResult.Eclipsed;
                    }
                }

                return predicate(library);
            });
        }
 private static void ApplyIncludeFlags(LibraryDependency dependency, IMSBuildItem item)
 {
     ApplyIncludeFlags(dependency, item.GetProperty("IncludeAssets"), item.GetProperty("ExcludeAssets"), item.GetProperty("PrivateAssets"));
 }
 Func <string, bool> ChainPredicate(Func <string, bool> predicate, GraphItem item, LibraryDependency dependency)
 {
     return(name =>
     {
         if (item.Match.Library.Name == name)
         {
             throw new Exception(string.Format("TODO: Circular dependency references not supported. Package '{0}'.", name));
         }
         if (item.Dependencies.Any(d => d != dependency && d.Name == name))
         {
             return false;
         }
         return predicate(name);
     });
 }
Beispiel #19
0
 public GraphEdge(GraphEdge <TItem> outerEdge, GraphItem <TItem> item, LibraryDependency edge)
 {
     OuterEdge = outerEdge;
     Item      = item;
     Edge      = edge;
 }
Beispiel #20
0
        public void AddProject_WhenDependencyVersionIsNull_CentralPackageVersionAppliesOnlyWhenAutoReferencedIsFalse()
        {
            // Arrange
            var dependencyFoo = new LibraryDependency(
                new LibraryRange("foo", versionRange: null, LibraryDependencyTarget.Package),
                LibraryIncludeFlags.All,
                LibraryIncludeFlags.All,
                new List <Common.NuGetLogCode>(),
                autoReferenced: false,
                generatePathProperty: true,
                versionCentrallyManaged: false,
                LibraryDependencyReferenceType.Direct,
                aliases: null);
            var dependencyBar = new LibraryDependency(
                new LibraryRange("bar", VersionRange.Parse("3.0.0"), LibraryDependencyTarget.Package),
                LibraryIncludeFlags.All,
                LibraryIncludeFlags.All,
                new List <Common.NuGetLogCode>(),
                autoReferenced: true,
                generatePathProperty: true,
                versionCentrallyManaged: false,
                LibraryDependencyReferenceType.Direct,
                aliases: null);
            var dependencyBoom = new LibraryDependency(
                new LibraryRange("boom", versionRange: null, LibraryDependencyTarget.Package),
                LibraryIncludeFlags.All,
                LibraryIncludeFlags.All,
                new List <Common.NuGetLogCode>(),
                autoReferenced: true,
                generatePathProperty: true,
                versionCentrallyManaged: false,
                LibraryDependencyReferenceType.Direct,
                aliases: null);
            var centralVersionFoo  = new CentralPackageVersion("foo", VersionRange.Parse("1.0.0"));
            var centralVersionBar  = new CentralPackageVersion("bar", VersionRange.Parse("2.0.0"));
            var centralVersionBoom = new CentralPackageVersion("boom", VersionRange.Parse("4.0.0"));

            var tfi = CreateTargetFrameworkInformation(
                new List <LibraryDependency>()
            {
                dependencyFoo, dependencyBar, dependencyBoom
            },
                new List <CentralPackageVersion>()
            {
                centralVersionFoo, centralVersionBar, centralVersionBoom
            });

            // Act
            DependencyGraphSpec dependencyGraphSpec = CreateDependencyGraphSpecWithCentralDependencies(tfi);

            // Assert
            Assert.Equal(1, dependencyGraphSpec.Projects.Count);
            PackageSpec packSpec = dependencyGraphSpec.Projects[0];
            IList <TargetFrameworkInformation> tfms         = packSpec.TargetFrameworks;
            IList <LibraryDependency>          dependencies = tfms[0].Dependencies;

            Assert.Equal(1, tfms.Count);
            Assert.Equal(3, dependencies.Count);
            Assert.Equal("[1.0.0, )", dependencies.Where(d => d.Name == "foo").First().LibraryRange.VersionRange.ToNormalizedString());
            Assert.True(dependencies.Where(d => d.Name == "foo").First().VersionCentrallyManaged);
            Assert.Equal("[3.0.0, )", dependencies.Where(d => d.Name == "bar").First().LibraryRange.VersionRange.ToNormalizedString());
            Assert.False(dependencies.Where(d => d.Name == "bar").First().VersionCentrallyManaged);
            Assert.Null(dependencies.Where(d => d.Name == "boom").First().LibraryRange.VersionRange);
        }
        public void LockFile_ConsiderCentralTransitiveDependencyGroupsForEquality()
        {
            // Arrange
            var dotNetFramework     = FrameworkConstants.CommonFrameworks.NetCoreApp10;
            var libraryDependency_1 = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    "Microsoft.NETCore.App",
                    new VersionRange(
                        minVersion: new NuGetVersion("1.0.1"),
                        originalString: "1.0.1"),
                    LibraryDependencyTarget.Package)
            };
            var libraryDependency_2 = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    "Microsoft.NETCore.App",
                    new VersionRange(
                        minVersion: new NuGetVersion("2.0.1"),
                        originalString: "2.0.1"),
                    LibraryDependencyTarget.Package)
            };
            var libraryDependency_3 = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    "Microsoft.NETCore.App",
                    new VersionRange(
                        minVersion: new NuGetVersion("3.0.1"),
                        originalString: "3.0.1"),
                    LibraryDependencyTarget.Package)
            };
            var libraryDependency_11 = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    "Microsoft.NETCore.App",
                    new VersionRange(
                        minVersion: new NuGetVersion("1.0.1"),
                        originalString: "1.0.1"),
                    LibraryDependencyTarget.Package)
            };
            var libraryDependency_22 = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    "Microsoft.NETCore.App",
                    new VersionRange(
                        minVersion: new NuGetVersion("2.0.1"),
                        originalString: "2.0.1"),
                    LibraryDependencyTarget.Package)
            };
            var projCTDG_1_2 = new CentralTransitiveDependencyGroup(dotNetFramework, new List <LibraryDependency>()
            {
                libraryDependency_1, libraryDependency_2
            });
            var projCTDG_11_22 = new CentralTransitiveDependencyGroup(dotNetFramework, new List <LibraryDependency>()
            {
                libraryDependency_1, libraryDependency_2
            });

            var lockFile_1_2 = new LockFile
            {
                Version = 3,
                CentralTransitiveDependencyGroups = new List <CentralTransitiveDependencyGroup>()
                {
                    projCTDG_1_2
                }
            };
            var lockFile_11_22 = new LockFile
            {
                Version = 3,
                CentralTransitiveDependencyGroups = new List <CentralTransitiveDependencyGroup>()
                {
                    projCTDG_11_22
                }
            };
            var lockFile_1 = new LockFile
            {
                Version = 3,
                CentralTransitiveDependencyGroups = new List <CentralTransitiveDependencyGroup>()
                {
                    new CentralTransitiveDependencyGroup(dotNetFramework, new List <LibraryDependency>()
                    {
                        libraryDependency_1
                    })
                }
            };
            var lockFile_1_3 = new LockFile
            {
                Version = 3,
                CentralTransitiveDependencyGroups = new List <CentralTransitiveDependencyGroup>()
                {
                    new CentralTransitiveDependencyGroup(dotNetFramework, new List <LibraryDependency>()
                    {
                        libraryDependency_1, libraryDependency_3
                    })
                }
            };

            // Act & Assert
            Assert.Equal(lockFile_1_2, lockFile_1_2);
            Assert.Equal(lockFile_1_2, lockFile_11_22);
            Assert.NotEqual(lockFile_1_2, lockFile_1);
            Assert.NotEqual(lockFile_1_2, lockFile_1_3);
            Assert.Equal(lockFile_1_2.GetHashCode(), lockFile_11_22.GetHashCode());
        }
Beispiel #22
0
        private static bool AddDependencyIfNotExist(PackageSpec spec, string targetAlias, LibraryDependency dependency)
        {
            var frameworkInfo = spec.TargetFrameworks.Single(e => e.TargetAlias.Equals(targetAlias, StringComparison.Ordinal));

            if (!spec.Dependencies
                .Concat(frameworkInfo.Dependencies)
                .Select(d => d.Name)
                .Contains(dependency.Name, StringComparer.OrdinalIgnoreCase))
            {
                frameworkInfo.Dependencies.Add(dependency);

                return(true);
            }

            return(false);
        }
Beispiel #23
0
        /// <summary>
        /// Emulates a JSON deserialization from project.json to PackageSpec in a post-project.json world
        /// </summary>
        private async Task <PackageSpec> GetPackageSpecAsync(ISettings settings)
        {
            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var projectReferences = await ProjectServices
                                    .ReferencesReader
                                    .GetProjectReferencesAsync(Common.NullLogger.Instance, CancellationToken.None);

            var targetFramework = await _vsProjectAdapter.GetTargetFrameworkAsync();

            var packageReferences = (await ProjectServices
                                     .ReferencesReader
                                     .GetPackageReferencesAsync(targetFramework, CancellationToken.None))
                                    .ToList();

            var packageTargetFallback = MSBuildStringUtility.Split(_vsProjectAdapter.PackageTargetFallback)
                                        .Select(NuGetFramework.Parse)
                                        .ToList();

            var assetTargetFallback = MSBuildStringUtility.Split(_vsProjectAdapter.AssetTargetFallback)
                                      .Select(NuGetFramework.Parse)
                                      .ToList();

            var projectTfi = new TargetFrameworkInformation
            {
                FrameworkName = targetFramework,
                Dependencies  = packageReferences,
            };

            bool isCpvmEnabled = await IsCentralPackageManagementVersionsEnabledAsync();

            if (isCpvmEnabled)
            {
                // Add the central version information and merge the information to the package reference dependencies
                projectTfi.CentralPackageVersions.AddRange(await GetCentralPackageVersionsAsync());
                LibraryDependency.ApplyCentralVersionInformation(projectTfi.Dependencies, projectTfi.CentralPackageVersions);
            }

            // Apply fallback settings
            AssetTargetFallbackUtility.ApplyFramework(projectTfi, packageTargetFallback, assetTargetFallback);

            // Build up runtime information.
            var runtimes = await _vsProjectAdapter.GetRuntimeIdentifiersAsync();

            var supports = await _vsProjectAdapter.GetRuntimeSupportsAsync();

            var runtimeGraph = new RuntimeGraph(runtimes, supports);

            // In legacy CSProj, we only have one target framework per project
            var tfis = new TargetFrameworkInformation[] { projectTfi };

            var projectName = _projectName ?? _projectUniqueName;

            string specifiedPackageId = await GetSpecifiedPackageIdAsync();

            if (!string.IsNullOrWhiteSpace(specifiedPackageId))
            {
                projectName = specifiedPackageId;
            }
            else
            {
                string specifiedAssemblyName = await GetSpecifiedAssemblyNameAsync();

                if (!string.IsNullOrWhiteSpace(specifiedAssemblyName))
                {
                    projectName = specifiedAssemblyName;
                }
            }

            return(new PackageSpec(tfis)
            {
                Name = projectName,
                Version = new NuGetVersion(_vsProjectAdapter.Version),
                FilePath = _projectFullPath,
                RuntimeGraph = runtimeGraph,
                RestoreMetadata = new ProjectRestoreMetadata
                {
                    ProjectStyle = ProjectStyle.PackageReference,
                    OutputPath = await GetMSBuildProjectExtensionsPathAsync(),
                    ProjectPath = _projectFullPath,
                    ProjectName = projectName,
                    ProjectUniqueName = _projectFullPath,
                    OriginalTargetFrameworks = tfis
                                               .Select(tfi => tfi.FrameworkName.GetShortFolderName())
                                               .ToList(),
                    TargetFrameworks = new List <ProjectRestoreMetadataFrameworkInfo>
                    {
                        new ProjectRestoreMetadataFrameworkInfo(tfis[0].FrameworkName)
                        {
                            ProjectReferences = projectReferences?.ToList()
                        }
                    },
                    SkipContentFileWrite = true,
                    CacheFilePath = await GetCacheFilePathAsync(),
                    PackagesPath = GetPackagesPath(settings),
                    Sources = GetSources(settings),
                    FallbackFolders = GetFallbackFolders(settings),
                    ConfigFilePaths = GetConfigFilePaths(settings),
                    ProjectWideWarningProperties = WarningProperties.GetWarningProperties(
                        treatWarningsAsErrors: _vsProjectAdapter.TreatWarningsAsErrors,
                        noWarn: _vsProjectAdapter.NoWarn,
                        warningsAsErrors: _vsProjectAdapter.WarningsAsErrors),
                    RestoreLockProperties = new RestoreLockProperties(
                        await _vsProjectAdapter.GetRestorePackagesWithLockFileAsync(),
                        await _vsProjectAdapter.GetNuGetLockFilePathAsync(),
                        await _vsProjectAdapter.IsRestoreLockedAsync()),
                    CentralPackageVersionsEnabled = isCpvmEnabled
                }
            });
        }
Beispiel #24
0
 /// <summary>
 /// Given a project, a library dependency and a framework, it returns the package references
 /// for the specific target framework
 /// </summary>
 /// <param name="project">Project for which the package references have to be obtained.</param>
 /// <param name="libraryDependency">Dependency of the package.</param>
 /// <param name="framework">Specific framework to look at</param>
 /// <returns>List of Items containing the package reference for the package.
 /// If the libraryDependency is null then it returns all package references</returns>
 private static IEnumerable <ProjectItem> GetPackageReferencesPerFramework(Project project,
                                                                           LibraryDependency libraryDependency, string framework)
 {
     return(GetPackageReferencesPerFramework(project, libraryDependency.Name, framework));
 }
Beispiel #25
0
        /// <summary>
        /// Returns all package references after evaluating the condition on the item groups.
        /// This method is used when we need package references for all target frameworks.
        /// </summary>
        /// <param name="project">Project for which the package references have to be obtained.
        /// The project should have the global property set to have a specific framework</param>
        /// <param name="libraryDependency">Dependency of the package.</param>
        /// <returns>List of Items containing the package reference for the package.
        /// If the libraryDependency is null then it returns all package reference</returns>
        private static IEnumerable <ProjectItem> GetPackageReferencesForAllFrameworks(Project project,
                                                                                      LibraryDependency libraryDependency)
        {
            var frameworks = GetProjectFrameworks(project);
            var mergedPackageReferences = new List <ProjectItem>();

            foreach (var framework in frameworks)
            {
                mergedPackageReferences.AddRange(GetPackageReferencesPerFramework(project, libraryDependency, framework));
            }
            return(mergedPackageReferences);
        }
        private bool IsProject(LibraryDependency dependency)
        {
            var type = dependency.LibraryRange.TypeConstraint;

            return(SupportsType(type));
        }
Beispiel #27
0
        public void IsLockFileStillValid_TransitiveDependencyNotCentrallyManaged_DoesNotInvalidateLockFile()
        {
            // Arrange
            var framework   = CommonFrameworks.NetStandard20;
            var projectName = "project";
            var cpvm1       = new CentralPackageVersion("cpvm1", VersionRange.Parse("1.0.0"));
            var cpvm2       = new CentralPackageVersion("cpvm2", VersionRange.Parse("1.0.0"));
            var dependency1 = new LibraryDependency(
                new LibraryRange("cpvm1", versionRange: null, LibraryDependencyTarget.Package),
                LibraryDependencyType.Default,
                LibraryIncludeFlags.All,
                LibraryIncludeFlags.All,
                new List <Common.NuGetLogCode>(),
                autoReferenced: false,
                generatePathProperty: true,
                versionCentrallyManaged: false,
                LibraryDependencyReferenceType.Direct,
                aliases: "stuff");

            var tfm = new TargetFrameworkInformation();

            tfm.FrameworkName = framework;
            tfm.CentralPackageVersions.Add("cpvm1", cpvm1);
            tfm.CentralPackageVersions.Add("cpvm2", cpvm2);
            tfm.Dependencies.Add(dependency1);
            LibraryDependency.ApplyCentralVersionInformation(tfm.Dependencies, tfm.CentralPackageVersions);

            var project = new PackageSpec(new List <TargetFrameworkInformation>()
            {
                tfm
            });

            project.RestoreMetadata = new ProjectRestoreMetadata()
            {
                ProjectUniqueName = projectName, CentralPackageVersionsEnabled = true
            };

            DependencyGraphSpec dgSpec = new DependencyGraphSpec();

            dgSpec.AddRestore(projectName);
            dgSpec.AddProject(project);

            var lockFile1 = new PackagesLockFileBuilder()
                            .WithTarget(target => target
                                        .WithFramework(CommonFrameworks.NetStandard20)
                                        .WithDependency(dep => dep
                                                        .WithId("cpvm1")
                                                        .WithRequestedVersion(VersionRange.Parse("1.0.0"))
                                                        .WithType(PackageDependencyType.Direct))
                                        .WithDependency(dep => dep
                                                        .WithId("otherDep")
                                                        .WithRequestedVersion(VersionRange.Parse("1.0.0"))
                                                        .WithType(PackageDependencyType.Transitive)))
                            .Build();

            var lockFile2 = new PackagesLockFileBuilder()
                            .WithVersion(PackagesLockFileFormat.PackagesLockFileVersion)
                            .WithTarget(target => target
                                        .WithFramework(CommonFrameworks.NetStandard20)
                                        .WithDependency(dep => dep
                                                        .WithId("cpvm1")
                                                        .WithRequestedVersion(VersionRange.Parse("1.0.0"))
                                                        .WithType(PackageDependencyType.Direct))
                                        .WithDependency(dep => dep
                                                        .WithId("otherDep")
                                                        .WithRequestedVersion(VersionRange.Parse("1.0.0"))
                                                        .WithType(PackageDependencyType.Transitive)))
                            .Build();

            // Nothing changed
            // different versions of lock file versions are handled
            Assert.True(PackagesLockFileUtilities.IsLockFileStillValid(dgSpec, lockFile1));
            Assert.True(PackagesLockFileUtilities.IsLockFileStillValid(dgSpec, lockFile2));
        }
        private static bool AddDependencyIfNotExist(PackageSpec spec, NuGetFramework framework, LibraryDependency dependency)
        {
            var frameworkInfo = spec.GetTargetFramework(framework);

            if (!spec.Dependencies
                .Concat(frameworkInfo.Dependencies)
                .Select(d => d.Name)
                .Contains(dependency.Name, StringComparer.OrdinalIgnoreCase))
            {
                frameworkInfo.Dependencies.Add(dependency);

                return(true);
            }

            return(false);
        }
Beispiel #29
0
        private static void InitializeProjectDependencies(
            LockFile assetsFile,
            IDictionary <NuGetFramework, HashSet <LibraryDependency> > dependenciesByFramework,
            IDictionary <string, string> projectRefToVersionMap,
            ISet <NuGetFramework> frameworkWithSuppressedDependencies)
        {
            // From the package spec, all we know is each absolute path to the project reference the the target
            // framework that project reference applies to.

            if (assetsFile.PackageSpec.RestoreMetadata == null)
            {
                return;
            }

            // Using the libraries section of the assets file, the library name and version for the project path.
            var projectPathToLibraryIdentities = assetsFile
                                                 .Libraries
                                                 .Where(library => library.MSBuildProject != null)
                                                 .ToLookup(
                library => Path.GetFullPath(Path.Combine(
                                                Path.GetDirectoryName(assetsFile.PackageSpec.RestoreMetadata.ProjectPath),
                                                PathUtility.GetPathWithDirectorySeparator(library.MSBuildProject))),
                library => new PackageIdentity(library.Name, library.Version),
                PathUtility.GetStringComparerBasedOnOS());

            // Consider all of the project references, grouped by target framework.
            foreach (var framework in assetsFile.PackageSpec.RestoreMetadata.TargetFrameworks)
            {
                var target = assetsFile.GetTarget(framework.FrameworkName, runtimeIdentifier: null);
                if (target == null || frameworkWithSuppressedDependencies.Contains(framework.FrameworkName))
                {
                    continue;
                }

                HashSet <LibraryDependency> dependencies;
                if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
                {
                    dependencies = new HashSet <LibraryDependency>();
                    dependenciesByFramework[framework.FrameworkName] = dependencies;
                }

                // For the current target framework, create a map from library identity to library model. This allows
                // us to be sure we have picked the correct library (name and version) for this target framework.
                var libraryIdentityToTargetLibrary = target
                                                     .Libraries
                                                     .ToLookup(library => new PackageIdentity(library.Name, library.Version));

                foreach (var projectReference in framework.ProjectReferences)
                {
                    var libraryIdentities = projectPathToLibraryIdentities[projectReference.ProjectPath];

                    var targetLibrary = libraryIdentities
                                        .Select(identity => libraryIdentityToTargetLibrary[identity].FirstOrDefault())
                                        .FirstOrDefault(library => library != null);

                    if (targetLibrary == null)
                    {
                        continue;
                    }

                    var versionToUse = new VersionRange(targetLibrary.Version);

                    // Use the project reference version obtained at build time if it exists, otherwise fallback to the one in assets file.
                    if (projectRefToVersionMap.TryGetValue(projectReference.ProjectPath, out var projectRefVersion))
                    {
                        versionToUse = VersionRange.Parse(projectRefVersion, allowFloating: false);
                    }
                    // TODO: Implement <TreatAsPackageReference>false</TreatAsPackageReference>
                    //   https://github.com/NuGet/Home/issues/3891
                    //
                    // For now, assume the project reference is a package dependency.
                    var projectDependency = new LibraryDependency
                    {
                        LibraryRange = new LibraryRange(
                            targetLibrary.Name,
                            versionToUse,
                            LibraryDependencyTarget.All),
                        IncludeType    = projectReference.IncludeAssets & ~projectReference.ExcludeAssets,
                        SuppressParent = projectReference.PrivateAssets
                    };

                    PackCommandRunner.AddLibraryDependency(projectDependency, dependencies);
                }
            }
        }
        private static PackageSpec CreatePackageSpec(bool withRestoreSettings, WarningProperties warningProperties = null)
        {
            var unsortedArray                = new[] { "b", "a", "c" };
            var unsortedReadOnlyList         = new List <string>(unsortedArray).AsReadOnly();
            var libraryRange                 = new LibraryRange("library", new VersionRange(new NuGetVersion("1.2.3")), LibraryDependencyTarget.Package);
            var libraryRangeWithNoWarn       = new LibraryRange("libraryWithNoWarn", new VersionRange(new NuGetVersion("1.2.3")), LibraryDependencyTarget.Package);
            var libraryRangeWithNoWarnGlobal = new LibraryRange("libraryRangeWithNoWarnGlobal", new VersionRange(new NuGetVersion("1.2.3")), LibraryDependencyTarget.Package);
            var libraryDependency            = new LibraryDependency()
            {
                IncludeType  = LibraryIncludeFlags.Build,
                LibraryRange = libraryRange
            };

            var libraryDependencyWithNoWarn = new LibraryDependency()
            {
                IncludeType  = LibraryIncludeFlags.Build,
                LibraryRange = libraryRangeWithNoWarn,
                NoWarn       = new List <NuGetLogCode> {
                    NuGetLogCode.NU1500, NuGetLogCode.NU1601
                }
            };

            var libraryDependencyWithNoWarnGlobal = new LibraryDependency()
            {
                IncludeType  = LibraryIncludeFlags.Build,
                LibraryRange = libraryRangeWithNoWarnGlobal,
                NoWarn       = new List <NuGetLogCode> {
                    NuGetLogCode.NU1500, NuGetLogCode.NU1608
                }
            };

            var nugetFramework           = new NuGetFramework("frameworkIdentifier", new Version("1.2.3"), "frameworkProfile");
            var nugetFrameworkWithNoWarn = new NuGetFramework("frameworkIdentifierWithNoWarn", new Version("1.2.5"), "frameworkProfileWithNoWarn");

            var packageSpec = new PackageSpec()
            {
                Authors      = unsortedArray,
                BuildOptions = new BuildOptions()
                {
                    OutputName = "outputName"
                },
                ContentFiles = new List <string>(unsortedArray),
                Copyright    = "copyright",
                Dependencies = new List <LibraryDependency>()
                {
                    libraryDependency, libraryDependencyWithNoWarnGlobal
                },
                Description        = "description",
                FilePath           = "filePath",
                HasVersionSnapshot = true,
                IconUrl            = "iconUrl",
                IsDefaultVersion   = false,
                Language           = "language",
                LicenseUrl         = "licenseUrl",
                Name        = "name",
                Owners      = unsortedArray,
                PackOptions = new PackOptions()
                {
                    IncludeExcludeFiles = new IncludeExcludeFiles()
                    {
                        Exclude      = unsortedReadOnlyList,
                        ExcludeFiles = unsortedReadOnlyList,
                        Include      = unsortedReadOnlyList,
                        IncludeFiles = unsortedReadOnlyList
                    }
                },
                ProjectUrl               = "projectUrl",
                ReleaseNotes             = "releaseNotes",
                RequireLicenseAcceptance = true,
                RestoreMetadata          = new ProjectRestoreMetadata()
                {
                    CrossTargeting           = true,
                    FallbackFolders          = unsortedReadOnlyList,
                    ConfigFilePaths          = unsortedReadOnlyList,
                    LegacyPackagesDirectory  = false,
                    OriginalTargetFrameworks = unsortedReadOnlyList,
                    OutputPath        = "outputPath",
                    ProjectStyle      = ProjectStyle.PackageReference,
                    PackagesPath      = "packagesPath",
                    ProjectJsonPath   = "projectJsonPath",
                    ProjectName       = "projectName",
                    ProjectPath       = "projectPath",
                    ProjectUniqueName = "projectUniqueName",
                    Sources           = new List <PackageSource>()
                    {
                        new PackageSource("source", "name", isEnabled: true, isOfficial: false, isPersistable: true)
                    },
                    TargetFrameworks = new List <ProjectRestoreMetadataFrameworkInfo>()
                    {
                        new ProjectRestoreMetadataFrameworkInfo(nugetFramework)
                    }
                },
                Summary = "summary",
                Tags    = unsortedArray,
                Title   = "title",
                Version = new NuGetVersion("1.2.3")
            };

            if (withRestoreSettings)
            {
                packageSpec.RestoreSettings = new ProjectRestoreSettings()
                {
                    HideWarningsAndErrors = true
                };
            }

            if (warningProperties != null)
            {
                packageSpec.RestoreMetadata.ProjectWideWarningProperties = warningProperties;
            }

            packageSpec.PackInclude.Add("b", "d");
            packageSpec.PackInclude.Add("a", "e");
            packageSpec.PackInclude.Add("c", "f");

            var runtimeDependencySet = new RuntimeDependencySet("id", new[]
            {
                new RuntimePackageDependency("id", new VersionRange(new NuGetVersion("1.2.3")))
            });
            var runtimes = new List <RuntimeDescription>()
            {
                new RuntimeDescription("runtimeIdentifier", unsortedArray, new [] { runtimeDependencySet })
            };
            var compatibilityProfiles = new List <CompatibilityProfile>()
            {
                new CompatibilityProfile("name", new[] { new FrameworkRuntimePair(nugetFramework, "runtimeIdentifier") })
            };

            packageSpec.RuntimeGraph = new RuntimeGraph(runtimes, compatibilityProfiles);

            packageSpec.Scripts.Add("b", unsortedArray);
            packageSpec.Scripts.Add("a", unsortedArray);
            packageSpec.Scripts.Add("c", unsortedArray);

            packageSpec.TargetFrameworks.Add(new TargetFrameworkInformation()
            {
                Dependencies  = new List <LibraryDependency>(),
                FrameworkName = nugetFramework,
                Imports       = new List <NuGetFramework>()
                {
                    nugetFramework
                },
            });

            packageSpec.TargetFrameworks.Add(new TargetFrameworkInformation()
            {
                Dependencies = new List <LibraryDependency>()
                {
                    libraryDependencyWithNoWarn
                },
                FrameworkName = nugetFrameworkWithNoWarn,
                Imports       = new List <NuGetFramework>()
                {
                    nugetFrameworkWithNoWarn
                },
                Warn = true
            });

            return(packageSpec);
        }