private List <LocalPackageInfo> GetPackages(string id)
        {
            var packages = new List <LocalPackageInfo>();

            var packageIdRoot = PathResolver.GetVersionListPath(id);

            if (!Directory.Exists(packageIdRoot))
            {
                return(packages);
            }

            foreach (var fullVersionDir in Directory.EnumerateDirectories(packageIdRoot))
            {
                LocalPackageInfo package;
                if (!_packageCache.TryGetValue(fullVersionDir, out package))
                {
                    var versionPart = fullVersionDir.Substring(packageIdRoot.Length).TrimStart(Path.DirectorySeparatorChar);

                    // Get the version part and parse it
                    NuGetVersion version;
                    if (!NuGetVersion.TryParse(versionPart, out version))
                    {
                        continue;
                    }

                    var hashPath = PathResolver.GetHashPath(id, version);

                    // The hash file is written last. If this file does not exist then the package is
                    // incomplete and should not be used.
                    if (_packageFileCache.Sha512Exists(hashPath))
                    {
                        var manifestPath = PathResolver.GetManifestFilePath(id, version);
                        var zipPath      = PathResolver.GetPackageFilePath(id, version);
                        var sha512Path   = PathResolver.GetHashPath(id, version);

                        var nuspec       = _packageFileCache.GetOrAddNuspec(manifestPath, fullVersionDir);
                        var files        = _packageFileCache.GetOrAddFiles(fullVersionDir);
                        var sha512       = _packageFileCache.GetOrAddSha512(hashPath);
                        var runtimeGraph = _packageFileCache.GetOrAddRuntimeGraph(fullVersionDir);

                        package = new LocalPackageInfo(id, version, fullVersionDir, manifestPath, zipPath, sha512Path, nuspec, files, sha512, runtimeGraph);

                        // Cache the package, if it is valid it will not change
                        // for the life of this restore.
                        // Locking is done at a higher level around the id
                        _packageCache.TryAdd(fullVersionDir, package);
                    }
                }

                // Add the package if it is valid
                if (package != null)
                {
                    packages.Add(package);
                }
            }

            return(packages);
        }
        public LocalPackageInfo FindPackage(string packageId, NuGetVersion version)
        {
            LocalPackageInfo package = null;

            var packages = FindPackagesByIdImpl(packageId);
            var count    = packages.Count;

            for (var i = 0; i < count; i++)
            {
                var candidatePackage = packages[i];
                if (candidatePackage.Version == version)
                {
                    package = candidatePackage;
                    break;
                }
            }

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

            // Check for an exact match on casing
            if (StringComparer.Ordinal.Equals(packageId, package.Id) &&
                EqualityUtility.SequenceEqualWithNullCheck(version.ReleaseLabels, package.Version.ReleaseLabels, StringComparer.Ordinal))
            {
                return(package);
            }

            // nuspec
            var nuspec = _packageFileCache.GetOrAddNuspec(package.ManifestPath, package.ExpandedPath);

            // files
            var files = _packageFileCache.GetOrAddFiles(package.ExpandedPath);

            // sha512
            var sha512 = _packageFileCache.GetOrAddSha512(package.Sha512Path);

            // Create a new info to match the given id/version
            return(new LocalPackageInfo(
                       packageId,
                       version,
                       package.ExpandedPath,
                       package.ManifestPath,
                       package.ZipPath,
                       package.Sha512Path,
                       nuspec,
                       files,
                       sha512));
        }
Example #3
0
        public LocalPackageSourceInfo(NuGetv3LocalRepository repository, LocalPackageInfo package)
        {
            if (repository == null)
            {
                throw new ArgumentNullException(nameof(repository));
            }

            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            Repository = repository;
            Package    = package;
        }
Example #4
0
        public async Task <PackageReaderBase> GetPackageAsync(string packageId, NuGetVersion version, bool includePrerelease, CancellationToken cancellationToken = default)
        {
            // if a version is specified, check locally, otherwise check all sources for the latest
            LocalPackageInfo package = null;

            if (version != null)
            {
                package = m_localRepository.FindPackage(packageId, version);
            }

            if (package != null)
            {
                return(GetLocalPackage(package.ZipPath));
            }

            using (var context = new SourceCacheContext())
            {
                var repoVersions = await Task.WhenAll(m_repositories.Select(async repo =>
                {
                    var metadata = await repo.GetResourceAsync <MetadataResource>(cancellationToken).ConfigureAwait(false);
                    var ver      = await metadata.GetLatestVersion(packageId, includePrerelease, includeUnlisted: false, context, Logger, cancellationToken).ConfigureAwait(false);
                    return(repository: repo, version: ver);
                })).ConfigureAwait(false);

                var(repository, latestVersion) = repoVersions.OrderByDescending(x => x.version).FirstOrDefault();

                if (latestVersion != null)
                {
                    var packageIdentity = new PackageIdentity(packageId, latestVersion);

                    var downloadResource = await repository.GetResourceAsync <DownloadResource>(cancellationToken).ConfigureAwait(false);

                    var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                        packageIdentity,
                        new PackageDownloadContext(context),
                        m_globalPackagesFolder,
                        Logger,
                        cancellationToken).ConfigureAwait(false);

                    return(downloadResult.PackageReader);
                }
            }

            return(null);
        }
Example #5
0
        /// <summary>
        /// Take the first match on id and version.
        /// </summary>
        public static LocalPackageSourceInfo GetPackage(
            IReadOnlyList <NuGetv3LocalRepository> repositories,
            string id,
            NuGetVersion version)
        {
            LocalPackageInfo package = null;

            foreach (var repository in repositories)
            {
                package = repository.FindPackage(id, version);

                if (package != null)
                {
                    return(new LocalPackageSourceInfo(repository, package));
                }
            }

            return(null);
        }
        public LocalPackageInfo FindPackage(string packageId, NuGetVersion version)
        {
            LocalPackageInfo package = null;

            var packages = FindPackagesByIdImpl(packageId);
            var count    = packages.Count;

            for (var i = 0; i < count; i++)
            {
                var candidatePackage = packages[i];
                if (candidatePackage.Version == version)
                {
                    package = candidatePackage;
                    break;
                }
            }

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

            // Check for an exact match on casing
            if (StringComparer.Ordinal.Equals(packageId, package.Id) &&
                StringComparer.Ordinal.Equals(version.ToNormalizedString(), package.Version.ToNormalizedString()))
            {
                return(package);
            }

            // nuspec
            var nuspec = _nuspecCache.GetOrAdd(package.ExpandedPath, new Lazy <NuspecReader>(() => GetNuspec(package.ManifestPath, package.ExpandedPath)));

            // Create a new info to match the given id/version
            return(new LocalPackageInfo(
                       packageId,
                       version,
                       package.ExpandedPath,
                       package.ManifestPath,
                       package.ZipPath,
                       nuspec));
        }
        /// <summary>
        /// Take the first match on id and version.
        /// </summary>
        public static LocalPackageSourceInfo GetPackage(
            IReadOnlyList <NuGetv3LocalRepository> repositories,
            string id,
            NuGetVersion version)
        {
            LocalPackageInfo package = null;

            for (var i = 0; i < repositories.Count; i++)
            {
                var repository = repositories[i];

                package = repository.FindPackage(id, version);

                if (package != null)
                {
                    return(new LocalPackageSourceInfo(repository, package));
                }
            }

            return(null);
        }
Example #8
0
 private RuntimeGraph LoadRuntimeGraph(LocalPackageInfo package)
 {
     var runtimeGraphFile = Path.Combine(package.ExpandedPath, RuntimeGraph.RuntimeGraphFileName);
     if (File.Exists(runtimeGraphFile))
     {
         using (var stream = File.OpenRead(runtimeGraphFile))
         {
             return JsonRuntimeFormat.ReadRuntimeGraph(stream);
         }
     }
     return null;
 }
Example #9
0
        private LockFileTargetLibrary CreateLockFileTargetLibrary(LocalPackageInfo package, RestoreTargetGraph targetGraph, DefaultPackagePathResolver defaultPackagePathResolver, string correctedPackageName)
        {
            var lockFileLib = new LockFileTargetLibrary();

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

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

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

                contentItems.Load(files);

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

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

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

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

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

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

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

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

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

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

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

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

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

            return lockFileLib;
        }
Example #10
0
        private LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, SHA512 sha512, 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;

            using (var nupkgStream = File.OpenRead(package.ZipPath))
            {
                lockFileLib.Sha512 = Convert.ToBase64String(sha512.ComputeHash(nupkgStream));
                nupkgStream.Seek(0, SeekOrigin.Begin);

                var packageReader = new PackageReader(nupkgStream);

                // Get package files, excluding directory entries
                lockFileLib.Files = packageReader.GetFiles().Where(x => !x.EndsWith("/")).ToList();
            }

            return lockFileLib;
        }