Beispiel #1
0
        public void GetDescriptionShouldNotModifyTarget()
        {
            var provider = new PackageDependencyProvider(
                NuGetPathContext.Create("/foo/packages"),
                new FrameworkReferenceResolver("/foo/references"));
            var package = new LockFileLibrary();

            package.Name    = "Something";
            package.Version = NuGetVersion.Parse("1.0.0");
            package.Files.Add("lib/dotnet/_._");
            package.Files.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");

            var target = new LockFileTargetLibrary();

            target.Name    = "Something";
            target.Version = package.Version;

            target.RuntimeAssemblies.Add("lib/dotnet/_._");
            target.CompileTimeAssemblies.Add("lib/dotnet/_._");
            target.NativeLibraries.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");

            var p1 = provider.GetDescription(NuGetFramework.Parse("netcoreapp1.0"), package, target);
            var p2 = provider.GetDescription(NuGetFramework.Parse("netcoreapp1.0"), package, target);

            Assert.True(p1.Compatible);
            Assert.True(p2.Compatible);

            Assert.Empty(p1.CompileTimeAssemblies);
            Assert.Empty(p1.RuntimeAssemblies);

            Assert.Empty(p2.CompileTimeAssemblies);
            Assert.Empty(p2.RuntimeAssemblies);
        }
        public void ConvertLockFileToOriginalCase_ConvertsPackagesPathsInLockFile()
        {
            // Arrange
            var logger         = new TestLogger();
            var request        = GetRestoreRequest("fake", logger);
            var packageLibrary = new LockFileLibrary
            {
                Name    = "PackageA",
                Version = NuGetVersion.Parse("1.0.0-Beta"),
                Path    = "packagea/1.0.0-beta",
                Type    = LibraryType.Package
            };
            var projectLibrary = new LockFileLibrary
            {
                Name    = "Project",
                Version = NuGetVersion.Parse("1.0.0-Beta"),
                Path    = "project",
                Type    = LibraryType.Project
            };
            var lockFile = new LockFile
            {
                Libraries = { packageLibrary, projectLibrary }
            };

            var target = new OriginalCaseGlobalPackageFolder(request);

            // Act
            target.ConvertLockFileToOriginalCase(lockFile);

            // Assert
            Assert.Equal("PackageA/1.0.0-Beta", packageLibrary.Path);
            Assert.Equal("project", projectLibrary.Path);
        }
Beispiel #3
0
        public void HasCompileTimePlaceholderChecksAllCompileTimeAssets()
        {
            var provider = new PackageDependencyProvider(
                NuGetPathContext.Create("/foo/packages"),
                new FrameworkReferenceResolver("/foo/references"));
            var package = new LockFileLibrary();

            package.Name    = "Something";
            package.Version = NuGetVersion.Parse("1.0.0");
            package.Files.Add("lib/net46/_._");
            package.Files.Add("lib/net46/Something.dll");

            var target = new LockFileTargetLibrary();

            target.Name    = "Something";
            target.Version = package.Version;

            target.RuntimeAssemblies.Add("lib/net46/_._");
            target.RuntimeAssemblies.Add("lib/net46/Something.dll");
            target.CompileTimeAssemblies.Add("lib/net46/_._");
            target.CompileTimeAssemblies.Add("lib/net46/Something.dll");

            var p1 = provider.GetDescription(NuGetFramework.Parse("net46"), package, target);

            Assert.False(p1.HasCompileTimePlaceholder);
            Assert.Equal(1, p1.CompileTimeAssemblies.Count());
            Assert.Equal(1, p1.RuntimeAssemblies.Count());
            Assert.Equal("lib/net46/Something.dll", p1.CompileTimeAssemblies.First().Path);
            Assert.Equal("lib/net46/Something.dll", p1.RuntimeAssemblies.First().Path);
        }
        /// <summary>
        /// Get a ContentItemCollection of the package files.
        /// </summary>
        /// <remarks>Library is optional.</remarks>
        public ContentItemCollection GetContentItems(LockFileLibrary library, LocalPackageInfo package)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

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

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

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

                _contentItems.Add(identity, collection);
            }

            return(collection);
        }
        private Dictionary <string, string> GetPackageReferenceItemMetadata(LockFileLibrary library, LibraryDependency libraryDependency = null)
        {
            if (library == null)
            {
                throw new ArgumentNullException(nameof(library));
            }

            Dictionary <string, string> metadata = new Dictionary <string, string>
            {
                { VersionMetadataName, $"[{library.Version}]" },
                { Sha512MetadataName, library.Sha512 },
                { PackagePathMetadataName, library.Path },
                { HashfileMetadataName, library.Files.First(i => i.EndsWith("nupkg.sha512", StringComparison.OrdinalIgnoreCase)).ToLowerInvariant() },
            };

            if (libraryDependency != null)
            {
                if (libraryDependency.IncludeType != LibraryIncludeFlags.All)
                {
                    metadata.Add(IncludeAssetsMetadataName, libraryDependency.IncludeType.ToString("F").Replace(", ", ";"));
                }

                if (libraryDependency.SuppressParent != LibraryIncludeFlagUtils.DefaultSuppressParent)
                {
                    metadata.Add(PrivateAssetsMetdataName, libraryDependency.SuppressParent.ToString("F").Replace(", ", ";"));
                }

                if (libraryDependency.AutoReferenced)
                {
                    metadata.Add(IsImplicitlyDefinedMetadataName, "true");
                }
            }

            return(metadata);
        }
Beispiel #6
0
        public void LockFileLibrary_CloneIsEqual()
        {
            // Arrange
            var original = new LockFileLibrary
            {
                Name           = "SomeLibrary",
                Version        = new NuGetVersion("1.0.0"),
                Path           = "SomeLibrary/1.0.0",
                IsServiceable  = true,
                MSBuildProject = "MSBuildProject",
                Sha512         = "FAKE-HASH",
                Type           = LibraryType.Package,
                Files          = new List <string>
                {
                    "file/a.txt",
                    "file/b.txt"
                }
            };

            // Act
            var clone = original.Clone();

            // Assert
            Assert.Equal(original, clone);
        }
Beispiel #7
0
        public void LockFileLibrary_ComparesDifferentCaseFiles()
        {
            // Arrange
            var libraryA = new LockFileLibrary
            {
                Files = new List <string>
                {
                    "path/a.txt",
                    "path/b.txt"
                }
            };

            // different case
            var libraryB = new LockFileLibrary
            {
                Files = new List <string>
                {
                    "path/a.txt",
                    "PATH/b.txt"
                }
            };

            // Act & Assert
            Assert.False(libraryA.Equals(libraryB), "The two libraries should not be equal.");
        }
Beispiel #8
0
        // return true if package exists, but retry logic is based on what value is expected so there is enough time for assets file to be updated.
        private static bool PackageExistsInLockFile(string pathToAssetsFile, string packageName, string packageVersion, bool expected)
        {
            var             numAttempts     = 0;
            LockFileLibrary lockFileLibrary = null;

            while (numAttempts++ < 3)
            {
                var version  = NuGetVersion.Parse(packageVersion);
                var lockFile = GetAssetsFileWithRetry(pathToAssetsFile);
                lockFileLibrary = lockFile.Libraries
                                  .SingleOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(p.Name, packageName) &&
                                                   p.Version.Equals(version));
                if (expected && lockFileLibrary != null)
                {
                    return(true);
                }
                if (!expected && lockFileLibrary == null)
                {
                    return(false);
                }

                Thread.Sleep(2000);
            }

            return(lockFileLibrary != null);
        }
Beispiel #9
0
        public void LockFileLibrary_CloneIncludesAllProperties()
        {
            // Arrange
            var original = new LockFileLibrary
            {
                Name           = "SomeLibrary",
                Version        = new NuGetVersion("1.0.0"),
                Path           = "SomeLibrary/1.0.0",
                IsServiceable  = true,
                MSBuildProject = "MSBuildProject",
                Sha512         = "FAKE-HASH",
                Type           = LibraryType.Package,
                Files          = new List <string>
                {
                    "file/a.txt",
                    "file/b.txt"
                }
            };

            // Use Newtonsoft.Json to enumerate all properties.
            var originalSerialized = JsonConvert.SerializeObject(original, Formatting.Indented);

            // Act
            var clone = original.Clone();

            // Assert
            var cloneSerialized = JsonConvert.SerializeObject(original, Formatting.Indented);

            Assert.Equal(originalSerialized, cloneSerialized);
        }
Beispiel #10
0
        private static LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, string sha512, string path)
        {
            var lockFileLib = new LockFileLibrary();

            lockFileLib.Name    = package.Id;
            lockFileLib.Version = package.Version;
            lockFileLib.Type    = LibraryType.Package;
            lockFileLib.Sha512  = sha512;

            // This is the relative path, appended to the global packages folder path. All
            // of the paths in the in the Files property should be appended to this path along
            // with the global packages folder path to get the absolute path to each file in the
            // package.
            lockFileLib.Path = path;

            using (var packageReader = new PackageFolderReader(package.ExpandedPath))
            {
                // Get package files, excluding directory entries and OPC files
                // This is sorted before it is written out
                lockFileLib.Files = packageReader
                                    .GetFiles()
                                    .Where(file => IsAllowedLibraryFile(file))
                                    .ToList();
            }

            return(lockFileLib);
        }
        private static LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, string sha512, string path)
        {
            var lockFileLib = new LockFileLibrary
            {
                Name    = package.Id,
                Version = package.Version,
                Type    = LibraryType.Package,
                Sha512  = sha512,

                // This is the relative path, appended to the global packages folder path. All
                // of the paths in the in the Files property should be appended to this path along
                // with the global packages folder path to get the absolute path to each file in the
                // package.
                Path = path
            };

            foreach (var file in package.Files)
            {
                if (!lockFileLib.HasTools && HasTools(file))
                {
                    lockFileLib.HasTools = true;
                }
                lockFileLib.Files.Add(file);
            }

            return(lockFileLib);
        }
Beispiel #12
0
        public void GetDescriptionShouldGenerateHashFileName()
        {
            // Arrange
            var provider = new PackageDependencyProvider(
                NuGetPathContext.Create("/foo/packages"),
                new FrameworkReferenceResolver("/foo/references"));
            var package = new LockFileLibrary();

            package.Name    = "Something";
            package.Version = NuGetVersion.Parse("1.0.0-Beta");
            package.Files.Add("lib/dotnet/_._");
            package.Files.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");
            package.Path = "SomePath";

            var target = new LockFileTargetLibrary();

            target.Name    = "Something";
            target.Version = package.Version;

            target.RuntimeAssemblies.Add("lib/dotnet/_._");
            target.CompileTimeAssemblies.Add("lib/dotnet/_._");
            target.NativeLibraries.Add("runtimes/any/native/Microsoft.CSharp.CurrentVersion.targets");

            // Act
            var p = provider.GetDescription(NuGetFramework.Parse("netcoreapp1.0"), package, target);

            // Assert
            p.PackageLibrary.Path.Should().Be("SomePath");
            p.HashPath.Should().Be("something.1.0.0-beta.nupkg.sha512");
        }
Beispiel #13
0
        private static LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, string sha512, string path, string correctedPackageName)
        {
            var lockFileLib = new LockFileLibrary();

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

            // This is the relative path, appended to the global packages folder path. All
            // of the paths in the in the Files property should be appended to this path along
            // with the global packages folder path to get the absolute path to each file in the
            // package.
            lockFileLib.Path = path;

            using (var packageReader = new PackageFolderReader(package.ExpandedPath))
            {
                // Get package files, excluding directory entries and OPC files
                // This is sorted before it is written out
                lockFileLib.Files = packageReader
                                    .GetFiles()
                                    .Where(file => IsAllowedLibraryFile(file))
                                    .ToList();
            }

            return(lockFileLib);
        }
Beispiel #14
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);
        }
Beispiel #15
0
        public void LockFileLibrary_EqualityEmpty()
        {
            // Arrange
            var library1 = new LockFileLibrary();
            var library2 = new LockFileLibrary();

            // Act & Assert
            Assert.True(library1.Equals(library2));
        }
 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));
 }
Beispiel #17
0
        private string GetMSBuildProjectFilePath(LockFileLibrary projectLibrary)
        {
            if (_rootProject == null)
            {
                throw new InvalidOperationException("Root xproj project does not exist. Cannot compute the path of its referenced csproj projects.");
            }

            var rootProjectPath        = Path.GetDirectoryName(_rootProject.ProjectFilePath);
            var msbuildProjectFilePath = Path.Combine(rootProjectPath, projectLibrary.MSBuildProject);

            return(Path.GetFullPath(msbuildProjectFilePath));
        }
Beispiel #18
0
 private PackageDescription CreateDescription(
     LockFileTargetLibrary target = null,
     LockFileLibrary package      = null,
     string hashPath = null)
 {
     return(new PackageDescription(
                PackagePath,
                hashPath ?? HashPath,
                package ?? new LockFileLibrary(),
                target ?? new LockFileTargetLibrary(),
                new List <ProjectLibraryDependency>(), compatible: true, resolved: true));
 }
Beispiel #19
0
        private void AddPackage(List <PackageIdentityWithPath> packages, LockFileLibrary installedPackage, VersionFolderPathResolver versionFolderPathResolver)
        {
            string installPath = versionFolderPathResolver.GetInstallPath(installedPackage.Name, installedPackage.Version);

            if (!String.IsNullOrWhiteSpace(installPath))
            {
                packages.Add(new PackageIdentityWithPath(installedPackage.Name, installedPackage.Version, Path.GetFullPath(installPath)));
            }
            else
            {
                Log.LogWarning($"The package '{installedPackage.Name}' was not found in the repository.");
            }
        }
Beispiel #20
0
 public PackageInfo(
     IFileSystem repositoryRoot,
     string packageId,
     SemanticVersion version,
     string versionDir,
     LockFileLibrary lockFileLibrary = null)
 {
     _repositoryRoot = repositoryRoot;
     Id              = packageId;
     Version         = version;
     _versionDir     = versionDir;
     LockFileLibrary = lockFileLibrary;
 }
Beispiel #21
0
        public static bool IsMSBuildProjectLibrary(LockFileLibrary projectLibrary)
        {
            var msbuildProjectPath = projectLibrary.MSBuildProject;

            if (msbuildProjectPath == null)
            {
                return(false);
            }

            var extension = Path.GetExtension(msbuildProjectPath);

            return(!string.Equals(extension, ".xproj", StringComparison.OrdinalIgnoreCase));
        }
Beispiel #22
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 PackageDescription GetDescription(
            NuGetFramework targetFramework,
            LockFileLibrary package,
            LockFileTargetLibrary targetLibrary)
        {
            // If a NuGet dependency is supposed to provide assemblies but there is no assembly compatible with
            // current target framework, we should mark this dependency as unresolved
            var containsAssembly = package.Files
                                   .Select(f => f.Replace('/', Path.DirectorySeparatorChar))
                                   .Any(x => x.StartsWith($"ref{Path.DirectorySeparatorChar}") ||
                                        x.StartsWith($"lib{Path.DirectorySeparatorChar}"));

            var compatible = targetLibrary.FrameworkAssemblies.Any() ||
                             targetLibrary.CompileTimeAssemblies.Any() ||
                             targetLibrary.RuntimeAssemblies.Any() ||
                             !containsAssembly;

            var dependencies =
                new List <ProjectLibraryDependency>(targetLibrary.Dependencies.Count + targetLibrary.FrameworkAssemblies.Count);

            PopulateDependencies(dependencies, targetLibrary, targetFramework);

            var  path   = _packagePathResolver?.GetPackageDirectory(package.Name, package.Version);
            bool exists = path != null;

            string hashPath = null;

            if (_versionFolderPathResolver != null)
            {
                hashPath = _versionFolderPathResolver.GetHashFileName(package.Name, package.Version);
            }

            if (exists)
            {
                // If the package's compile time assemblies is for a portable profile then, read the assembly metadata
                // and turn System.* references into reference assembly dependencies
                PopulateLegacyPortableDependencies(targetFramework, dependencies, path, targetLibrary);
            }

            var packageDescription = new PackageDescription(
                path,
                hashPath,
                package,
                targetLibrary,
                dependencies,
                compatible,
                resolved: compatible && exists);

            return(packageDescription);
        }
Beispiel #24
0
        private JProperty WriteLibrary(LockFileLibrary library)
        {
            var json = new JObject();

            if (library.IsServiceable)
            {
                WriteBool(json, "serviceable", library.IsServiceable);
            }
            json["sha512"] = WriteString(library.Sha512);
            WritePathArray(json, "files", library.Files.OrderBy(f => f), WriteString);
            return(new JProperty(
                       library.Name + "/" + library.Version.ToString(),
                       json));
        }
Beispiel #25
0
        private LockFileLibrary ReadLibrary(string property, JToken json)
        {
            var library = new LockFileLibrary();
            var parts   = property.Split(new[] { '/' }, 2);

            library.Name = parts[0];
            if (parts.Length == 2)
            {
                library.Version = SemanticVersion.Parse(parts[1]);
            }
            library.IsServiceable = ReadBool(json, "serviceable", defaultValue: false);
            library.Sha512        = ReadString(json["sha512"]);
            library.Files         = ReadPathArray(json["files"] as JArray, ReadString);
            return(library);
        }
Beispiel #26
0
        public bool TryGetLibrary(LockFileTargetLibrary targetLibrary, out LockFileLibrary library)
        {
            var libraryType = LibraryType.Parse(targetLibrary.Type);

            if (libraryType == LibraryType.Package)
            {
                library = GetPackage(targetLibrary.Name, targetLibrary.Version);
            }
            else
            {
                library = GetProject(targetLibrary.Name);
            }

            return(library != null);
        }
Beispiel #27
0
        public void LockFileLibrary_EqualitySameMSBuildPath()
        {
            // Arrange
            var library1 = new LockFileLibrary()
            {
                MSBuildProject = "b"
            };

            var library2 = new LockFileLibrary()
            {
                MSBuildProject = "b"
            };

            // Act & Assert
            Assert.True(library1.Equals(library2));
        }
Beispiel #28
0
        public void LockFileLibrary_EqualityDiffersOnMSBuildPath()
        {
            // Arrange
            var library1 = new LockFileLibrary()
            {
                MSBuildProject = "a"
            };

            var library2 = new LockFileLibrary()
            {
                MSBuildProject = "b"
            };

            // Act & Assert
            Assert.False(library1.Equals(library2));
        }
Beispiel #29
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));
 }
Beispiel #30
0
        public static LockFileLibrary CreateLockFileLibrary(LockFileLibrary previousLibrary, IPackagePathResolver resolver, IPackage package, string correctedPackageName = null)
        {
            var lockFileLib = new LockFileLibrary();

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

            // If the shas are equal then do nothing
            if (previousLibrary?.Sha512 == lockFileLib.Sha512)
            {
                lockFileLib.Files         = previousLibrary.Files;
                lockFileLib.IsServiceable = previousLibrary.IsServiceable;
            }
            else
            {
                lockFileLib.Files = package.GetFiles().Select(p => p.Path).ToList();
                var installPath = resolver.GetInstallPath(package.Id, package.Version);
                foreach (var filePath in lockFileLib.Files)
                {
                    if (!string.Equals(Path.GetExtension(filePath), ".dll", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var assemblyPath = Path.Combine(installPath, filePath);
                    try
                    {
                        if (IsAssemblyServiceable(assemblyPath))
                        {
                            lockFileLib.IsServiceable = true;
                            break;
                        }
                    }
                    catch
                    {
                        // Just move on to the next file
                    }
                }
            }

            return(lockFileLib);
        }