private async Task <bool> InstallPackageAsync(RemoteMatch installItem, NuGetv3LocalRepository userPackageFolder, PackageExtractionContext packageExtractionContext, CancellationToken token)
        {
            var packageIdentity = new PackageIdentity(installItem.Library.Name, installItem.Library.Version);

            // Check if the package has already been installed.
            if (!userPackageFolder.Exists(packageIdentity.Id, packageIdentity.Version))
            {
                var versionFolderPathResolver = new VersionFolderPathResolver(_request.PackagesDirectory);

                try
                {
                    using (var packageDependency = await installItem.Provider.GetPackageDownloaderAsync(
                               packageIdentity,
                               _request.CacheContext,
                               _logger,
                               token))
                    {
                        // Install, returns true if the package was actually installed.
                        // Returns false if the package was a noop once the lock
                        // was acquired.
                        var installed = await PackageExtractor.InstallFromSourceAsync(
                            packageIdentity,
                            packageDependency,
                            versionFolderPathResolver,
                            packageExtractionContext,
                            token,
                            ParentId);

                        // 1) If another project in this process installs the package this will return false but userPackageFolder will contain the package.
                        // 2) If another process installs the package then this will also return false but we still need to update the cache.
                        // For #2 double check that the cache has the package now otherwise clear
                        if (installed || !userPackageFolder.Exists(packageIdentity.Id, packageIdentity.Version))
                        {
                            // If the package was added, clear the cache so that the next caller can see it.
                            // Avoid calling this for packages that were not actually installed.
                            userPackageFolder.ClearCacheForIds(new string[] { packageIdentity.Id });
                        }
                    }
                }
                catch (SignatureException e)
                {
                    if (!string.IsNullOrEmpty(e.Message))
                    {
                        await _logger.LogAsync(e.AsLogMessage());
                    }

                    // If the package is unsigned and unsigned packages are not allowed a SignatureException
                    // will be thrown but it won't have results because it didn't went through any
                    // verification provider.
                    if (e.Results != null)
                    {
                        await _logger.LogMessagesAsync(e.Results.SelectMany(p => p.Issues));
                    }

                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Installs the package.
        /// </summary>
        /// <param name="match">NuGet package match.</param>
        /// <param name="path">Installation path</param>
        /// <returns>Task</returns>
        /// <seealso cref="INuGetEngine.GetPackageTargetPath" />
        public Task InstallPackage(RemoteMatch match, string path)
        {
            var packageIdentity = new PackageIdentity(match.Library.Name, match.Library.Version);

            if (match.Provider == null)
            {
                Console.WriteLine("Invalid match provider!");
                throw new Exception("invalid match provider for " + packageIdentity);
            }
            var versionFolderPathContext = new VersionFolderPathContext(
                packageIdentity,
                path,
                _nuGetLogger,
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.None);

            return(PackageExtractor.InstallFromSourceAsync(
                       stream => match.Provider.CopyToAsync(
                           match.Library,
                           stream,
                           _cache,
                           _nuGetLogger,
                           CancellationToken.None),
                       versionFolderPathContext,
                       CancellationToken.None));
        }
Exemplo n.º 3
0
        private async Task InstallPackageAsync(RemoteMatch installItem, CancellationToken token)
        {
            var packageIdentity = new PackageIdentity(installItem.Library.Name, installItem.Library.Version);

            var verificationProviders = SignatureVerificationProviderFactory.GetSignatureVerificationProviders();
            var signedPackageVerifier = new PackageSignatureVerifier(verificationProviders);

            var versionFolderPathResolver = new VersionFolderPathResolver(_packagesDirectory);
            var packageExtractionContext  = new PackageExtractionContext(
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.None,
                _logger,
                signedPackageVerifier,
                SignedPackageVerifierSettings.GetDefault());

            using (var packageDependency = await installItem.Provider.GetPackageDownloaderAsync(
                       packageIdentity,
                       _cacheContext,
                       _logger,
                       token))
            {
                await PackageExtractor.InstallFromSourceAsync(
                    packageIdentity,
                    packageDependency,
                    versionFolderPathResolver,
                    packageExtractionContext,
                    token);
            }
        }
        private async Task CopyToAsync(RemoteMatch remoteMatch, Stream destination, CancellationToken token)
        {
            var library = remoteMatch.Library;

            // Try to get the package from the local repositories first.
            var localPackage = NuGetv3LocalRepositoryUtility.GetPackage(
                _localRepositories,
                library.Name,
                library.Version);

            if (localPackage != null && File.Exists(localPackage.Package.ZipPath))
            {
                using (var stream = new FileStream(
                           localPackage.Package.ZipPath,
                           FileMode.Open,
                           FileAccess.Read,
                           FileShare.Read,
                           bufferSize: 4096,
                           useAsync: true))
                {
                    await stream.CopyToAsync(destination, bufferSize : 4096, cancellationToken : token);
                }
            }
            else
            {
                // Otherwise, get it from the provider.
                await remoteMatch.Provider.CopyToAsync(
                    remoteMatch.Library,
                    destination,
                    _request.CacheContext,
                    _request.Log,
                    token);
            }
        }
        public async Task <IEnumerable <LibraryDependency> > GetDependencies(RemoteMatch match, NuGetFramework targetFramework)
        {
            using (var stream = await _source.OpenNuspecStreamAsync(new PackageInfo
            {
                Id = match.Library.Name,
                Version = match.Library.Version,
                ContentUri = match.Path
            }))
            {
                var nuspecReader = new NuspecReader(stream);
                var reducer      = new FrameworkReducer();

                var groups = nuspecReader.GetDependencyGroups()
                             .ToDictionary(g => new NuGetFramework(g.TargetFramework),
                                           g => g.Packages);


                var nearest = reducer.GetNearest(targetFramework, groups.Keys);

                if (nearest != null)
                {
                    return(groups[nearest].Select(p => new LibraryDependency
                    {
                        LibraryRange = new LibraryRange
                        {
                            Name = p.Id,
                            VersionRange = new NuGetVersionRange(p.VersionRange)
                        }
                    })
                           .ToList());
                }
            }

            return(Enumerable.Empty <LibraryDependency>());
        }
Exemplo n.º 6
0
        private async Task InstallPackage(RemoteMatch installItem, string packagesDirectory)
        {
            using (var memoryStream = new MemoryStream())
            {
                await installItem.Provider.CopyToAsync(installItem.Library, memoryStream, default(CancellationToken));

                memoryStream.Seek(0, SeekOrigin.Begin);
                await NuGetPackageUtils.InstallFromStream(memoryStream, installItem.Library, packagesDirectory, _log);
            }
        }
 public async Task CopyToAsync(RemoteMatch match, Stream stream)
 {
     using (var nupkgStream = await _source.OpenNupkgStreamAsync(new PackageInfo
     {
         Id = match.Library.Name,
         Version = match.Library.Version,
         ContentUri = match.Path
     }))
     {
         await nupkgStream.CopyToAsync(stream);
     }
 }
Exemplo n.º 8
0
        private async Task InstallPackageAsync(RemoteMatch installItem, string packagesDirectory, CancellationToken token)
        {
            var packageIdentity = new PackageIdentity(installItem.Library.Name, installItem.Library.Version);

            var versionFolderPathContext = new VersionFolderPathContext(
                packageIdentity,
                packagesDirectory,
                _logger,
                packageSaveMode: _request.PackageSaveMode,
                xmlDocFileSaveMode: _request.XmlDocFileSaveMode);

            await PackageExtractor.InstallFromSourceAsync(
                stream => installItem.Provider.CopyToAsync(installItem.Library, stream, token),
                versionFolderPathContext,
                token);
        }
        private LocalPackageSourceInfo GetLocalPackageSourceInfo(RemoteMatch remoteMatch)
        {
            var library = remoteMatch.Library;

            // Try to get the package from the local repositories first.
            var localPackage = NuGetv3LocalRepositoryUtility.GetPackage(
                _localRepositories,
                library.Name,
                library.Version);

            if (localPackage != null && File.Exists(localPackage.Package.ZipPath))
            {
                return(localPackage);
            }

            return(null);
        }
Exemplo n.º 10
0
        public Task InstallPackage(RemoteMatch match, string path)
        {
            var packageIdentity = new PackageIdentity(match.Library.Name, match.Library.Version);

            var versionFolderPathContext = new VersionFolderPathContext(
                packageIdentity,
                path,
                _nuGetLogger,
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.None);

            return(PackageExtractor.InstallFromSourceAsync(
                       stream => match.Provider.CopyToAsync(
                           match.Library,
                           stream,
                           _cache,
                           _nuGetLogger,
                           CancellationToken.None),
                       versionFolderPathContext,
                       CancellationToken.None));
        }
        private async Task InstallPackageAsync(RemoteMatch installItem, CancellationToken token)
        {
            var packageIdentity = new PackageIdentity(installItem.Library.Name, installItem.Library.Version);

            var versionFolderPathContext = new VersionFolderPathContext(
                packageIdentity,
                _request.PackagesDirectory,
                _logger,
                _request.PackageSaveMode,
                _request.XmlDocFileSaveMode);

            using (var packageDependency = await installItem.Provider.GetPackageDownloaderAsync(
                       packageIdentity,
                       _request.CacheContext,
                       _logger,
                       token))
            {
                await PackageExtractor.InstallFromSourceAsync(
                    packageDependency,
                    versionFolderPathContext,
                    token);
            }
        }
Exemplo n.º 12
0
        private async Task InstallPackageAsync(RemoteMatch installItem, NuGetv3LocalRepository userPackageFolder, CancellationToken token)
        {
            var packageIdentity = new PackageIdentity(installItem.Library.Name, installItem.Library.Version);

            // Check if the package has already been installed.
            if (!userPackageFolder.Exists(packageIdentity.Id, packageIdentity.Version))
            {
                var versionFolderPathContext = new VersionFolderPathContext(
                    packageIdentity,
                    _request.PackagesDirectory,
                    _logger,
                    _request.PackageSaveMode,
                    _request.XmlDocFileSaveMode);

                using (var packageDependency = await installItem.Provider.GetPackageDownloaderAsync(
                           packageIdentity,
                           _request.CacheContext,
                           _logger,
                           token))
                {
                    // Install, returns true if the package was actually installed.
                    // Returns false if the package was a noop once the lock
                    // was acquired.
                    var installed = await PackageExtractor.InstallFromSourceAsync(
                        packageDependency,
                        versionFolderPathContext,
                        token);

                    if (installed)
                    {
                        // If the package was added, clear the cache so that the next caller can see it.
                        // Avoid calling this for packages that were not actually installed.
                        userPackageFolder.ClearCacheForIds(new string[] { packageIdentity.Id });
                    }
                }
            }
        }
 private static PackageIdentity ToPackageIdentity(RemoteMatch match)
 {
     return(new PackageIdentity(match.Library.Name, match.Library.Version));
 }
 private static PackageIdentity GetPackageIdentity(RemoteMatch remoteMatch)
 {
     return(new PackageIdentity(
                remoteMatch.Library.Name,
                remoteMatch.Library.Version));
 }
Exemplo n.º 15
0
        public static void InstallPackage(IReadOnlyList <string> packages, bool quiet)
        {
            Init();
            RemoteWalkContext context = new RemoteWalkContext();

            ILogger            logger       = new NullLogger();
            SourceCacheContext cacheContext = new SourceCacheContext
            {
                IgnoreFailedSources = true
            };

            foreach (SourceRepository repo in Repos)
            {
                if (!repo.PackageSource.IsLocal)
                {
                    context.RemoteLibraryProviders.Add(new SourceRepositoryDependencyProvider(repo, logger, cacheContext));
                }
                else
                {
                    context.LocalLibraryProviders.Add(new SourceRepositoryDependencyProvider(repo, logger, cacheContext));
                }
            }

            Paths.User.Content.CreateDirectory();
            RemoteDependencyWalker walker                        = new RemoteDependencyWalker(context);
            HashSet <Package>      remainingPackages             = new HashSet <Package>(packages.Select(x => new Package(x, VersionRange.All)));
            HashSet <Package>      encounteredPackages           = new HashSet <Package>();
            List <string>          templateRoots                 = new List <string>();
            List <KeyValuePair <string, string> > componentRoots = new List <KeyValuePair <string, string> >();

            while (remainingPackages.Count > 0)
            {
                HashSet <Package> nextRound = new HashSet <Package>();

                foreach (Package package in remainingPackages)
                {
                    string name = package.PackageId;
                    GraphNode <RemoteResolveResult> result = walker.WalkAsync(new LibraryRange(name, package.Version, LibraryDependencyTarget.All), NuGetFramework.AnyFramework, "", RuntimeGraph.Empty, true).Result;
                    RemoteMatch     match           = result.Item.Data.Match;
                    PackageIdentity packageIdentity = new PackageIdentity(match.Library.Name, match.Library.Version);

                    nextRound.UnionWith(result.Item.Data.Dependencies.Select(x => new Package(x.Name, x.LibraryRange.VersionRange)));

                    VersionFolderPathContext versionFolderPathContext = new VersionFolderPathContext(
                        packageIdentity,
                        Paths.User.PackageCache,
                        new NullLogger(),
                        packageSaveMode: PackageSaveMode.Defaultv3,
                        xmlDocFileSaveMode: XmlDocFileSaveMode.Skip,
                        fixNuspecIdCasing: true,
                        normalizeFileNames: true);

                    if (match.Library.Version == null)
                    {
                        if (!quiet)
                        {
                            throw new Exception($"Package '{package.PackageId}' version {package.Version} could not be located.");
                        }
                        else
                        {
                            continue;
                        }
                    }

                    string source = Path.Combine(Paths.User.PackageCache, match.Library.Name, match.Library.Version.ToString());

                    if (!source.Exists() && match.Provider != null)
                    {
                        PackageExtractor.InstallFromSourceAsync(
                            stream => match.Provider.CopyToAsync(match.Library, stream, CancellationToken.None),
                            versionFolderPathContext,
                            CancellationToken.None).Wait();

                        string target = Path.Combine(Paths.User.Content, match.Library.Name);
                        target.CreateDirectory();
                        target = Path.Combine(target, match.Library.Version.ToString());
                        target.CreateDirectory();
                        Paths.Copy(source, target);
                        target.Delete("*.nupkg", "*.nupkg.*");

                        string nuspec = target.EnumerateFiles("*.nuspec").FirstOrDefault();

                        //If there's a nuspec, figure out whether this package is a template and walk the dependency graph
                        if (nuspec?.Exists() ?? false)
                        {
                            XDocument doc = XDocument.Load(nuspec);
                            IReadOnlyList <PackageType> types = NuspecUtility.GetPackageTypes(doc.Root.Element(XName.Get("metadata", "http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd")), false);
                            //If the thing we got is a template...
                            if (types.Any(x => string.Equals(x.Name, "template", StringComparison.OrdinalIgnoreCase)))
                            {
                                templateRoots.Add(target);
                            }
                            else
                            {
                                componentRoots.Add(new KeyValuePair <string, string>(match.Library.Name, match.Library.Version.ToString()));
                            }
                        }
                    }
                }

                encounteredPackages.UnionWith(remainingPackages);
                nextRound.ExceptWith(encounteredPackages);
                remainingPackages = nextRound;
            }

            foreach (KeyValuePair <string, string> package in componentRoots)
            {
                foreach (string path in Path.Combine(Paths.User.Content, package.Key, package.Value).EnumerateFiles($"{package.Key}.dll", SearchOption.AllDirectories))
                {
                    if (path.IndexOf($"{Path.DirectorySeparatorChar}lib{Path.DirectorySeparatorChar}", StringComparison.OrdinalIgnoreCase) < 0 ||
                        (path.IndexOf($"{Path.DirectorySeparatorChar}netstandard1.", StringComparison.OrdinalIgnoreCase) < 0 &&
                         path.IndexOf($"{Path.DirectorySeparatorChar}netcoreapp1.", StringComparison.OrdinalIgnoreCase) < 0))
                    {
                        continue;
                    }

#if !NET451
                    Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
#else
                    Assembly asm = Assembly.LoadFile(path);
#endif
                    foreach (Type type in asm.GetTypes())
                    {
                        SettingsLoader.Components.Register(type);
                    }
                }
            }

            TemplateCache.Scan(templateRoots);
        }
Exemplo n.º 16
0
        private async Task InstallPackage(RemoteMatch installItem, string packagesDirectory)
        {
            using (var memoryStream = new MemoryStream())
            {
                await installItem.Provider.CopyToAsync(installItem.Library, memoryStream, default(CancellationToken));

                memoryStream.Seek(0, SeekOrigin.Begin);
                await NuGetPackageUtils.InstallFromStream(memoryStream, installItem.Library, packagesDirectory, _log);
            }
        }