예제 #1
0
        public async Task <IEnumerable <string> > ExtractPackageAsync(string packagePath, DirectoryPath targetFolder)
        {
            await using FileStream packageStream = File.OpenRead(packagePath);
            PackageFolderReader      packageReader            = new PackageFolderReader(targetFolder.Value);
            PackageExtractionContext packageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.None,
                null,
                _verboseLogger);
            NuGetPackagePathResolver packagePathResolver = new NuGetPackagePathResolver(targetFolder.Value);
            CancellationToken        cancellationToken   = CancellationToken.None;

            var allFilesInPackage = await PackageExtractor.ExtractPackageAsync(
                targetFolder.Value,
                packageStream,
                packagePathResolver,
                packageExtractionContext,
                cancellationToken);

            if (!OperatingSystem.IsWindows())
            {
                string workloadUnixFilePermissions = allFilesInPackage.SingleOrDefault(p =>
                                                                                       Path.GetRelativePath(targetFolder.Value, p).Equals("data/UnixFilePermissions.xml",
                                                                                                                                          StringComparison.OrdinalIgnoreCase));

                if (workloadUnixFilePermissions != default)
                {
                    var permissionList = WorkloadUnixFilePermissions.FileList.Deserialize(workloadUnixFilePermissions);
                    foreach (var fileAndPermission in permissionList.File)
                    {
                        _filePermissionSetter
                        .SetPermission(
                            Path.Combine(targetFolder.Value, fileAndPermission.Path),
                            fileAndPermission.Permission);
                    }
                }
                else
                {
                    // https://github.com/dotnet/sdk/issues/18239
                    foreach (FilePath filePath in FindAllFilesNeedExecutablePermission(allFilesInPackage,
                                                                                       targetFolder.Value))
                    {
                        _filePermissionSetter.SetPermission(filePath.Value, "755");
                    }
                }
            }

            return(allFilesInPackage);
        }
        public async Task PackageExpander_ExpandsPackage_WithNupkgCopy()
        {
            // Arrange
            using (var package = TestPackagesCore.GetPackageWithNupkgCopy())
            {
                var version  = new NuGetVersion(package.Version);
                var identity = new PackageIdentity(package.Id, version);

                using (var packagesDir = TestDirectory.Create())
                {
                    var pathResolver = new VersionFolderPathResolver(packagesDir);

                    var token  = CancellationToken.None;
                    var logger = NullLogger.Instance;
                    var packageExtractionContext = new PackageExtractionContext(
                        packageSaveMode: PackageSaveMode.Defaultv3,
                        xmlDocFileSaveMode: XmlDocFileSaveMode.None,
                        clientPolicyContext: null,
                        logger: logger);

                    var versionFolderPathResolver = new VersionFolderPathResolver(packagesDir);

                    // Act
                    using (var packageDownloader = new LocalPackageArchiveDownloader(
                               null,
                               package.File.FullName,
                               identity,
                               logger))
                    {
                        await PackageExtractor.InstallFromSourceAsync(
                            identity,
                            packageDownloader,
                            versionFolderPathResolver,
                            packageExtractionContext,
                            token);
                    }

                    // Assert
                    var packageDir = pathResolver.GetInstallPath(package.Id, identity.Version);
                    AssertDirectoryExists(packageDir, packageDir + " does not exist");

                    var nupkgPath = pathResolver.GetPackageFilePath(package.Id, identity.Version);
                    Assert.True(File.Exists(nupkgPath), nupkgPath + " does not exist");

                    var dllPath = Path.Combine(packageDir, "lib", "net40", "one.dll");
                    Assert.True(File.Exists(dllPath), dllPath + " does not exist");
                }
            }
        }
예제 #3
0
        public virtual async Task <NuGetInstallResult> InstallAsync(PackageIdentity packageIdentity, bool allowPrereleaseVersions = false)
        {
            using var cacheContext = new SourceCacheContext();
            IEnumerable <SourcePackageDependencyInfo> dependencyPackages;

            try
            {
                dependencyPackages = await GetDependenciesAsync(packageIdentity, cacheContext);
            }
            catch (NuGetResolverInputException ex)
            {
                Logger.LogDebug(ex.ToString());
                return(new NuGetInstallResult(NuGetInstallCode.PackageOrVersionNotFound));
            }

            var packageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Nupkg,
                XmlDocFileSaveMode.None,
                ClientPolicyContext.GetClientPolicy(m_NugetSettings, Logger),
                Logger);

            foreach (var dependencyPackage in dependencyPackages)
            {
                var installedPath = m_PackagePathResolver.GetInstalledPath(dependencyPackage);
                if (installedPath == null)
                {
                    Logger.LogInformation($"Downloading: {dependencyPackage.Id} v{dependencyPackage.Version.OriginalVersion}");

                    var downloadResource = await dependencyPackage.Source.GetResourceAsync <DownloadResource>(CancellationToken.None);

                    var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                        dependencyPackage,
                        new PackageDownloadContext(cacheContext),
                        SettingsUtility.GetGlobalPackagesFolder(m_NugetSettings),
                        Logger, CancellationToken.None);

                    await PackageExtractor.ExtractPackageAsync(
                        downloadResult.PackageSource,
                        downloadResult.PackageStream,
                        m_PackagePathResolver,
                        packageExtractionContext,
                        CancellationToken.None);
                }

                await LoadAssembliesFromNuGetPackageAsync(GetNugetPackageFile(dependencyPackage));
            }

            return(new NuGetInstallResult(packageIdentity));
        }
        public static async Task InstallWithDependencies(string packageId, string version, string frameworkVersion, ILogger logger)
        {
            var packageVersion = NuGetVersion.Parse(version);
            var nuGetFramework = NuGetFramework.ParseFolder(frameworkVersion);
            var settings       = Settings.LoadDefaultSettings(root: null);
            var feed           = new Uri("https://api.nuget.org/v3/index.json");
            var repositoryList = new List <SourceRepository>();

            repositoryList.Add(Repository.Factory.GetCoreV3(feed.AbsoluteUri, FeedType.HttpV3));
            var sourceRepositoryProvider = new SourceRepositoryProvider(settings, Repository.Provider.GetCoreV3());

            using (var cacheContext = new SourceCacheContext())
            {
                var availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default);
                await GetPackageDependencies(
                    new PackageIdentity(packageId, packageVersion),
                    nuGetFramework, cacheContext, logger, repositoryList, availablePackages);

                var resolverContext = new PackageResolverContext(
                    DependencyBehavior.Lowest,
                    new[] { packageId },
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <PackageReference>(),
                    Enumerable.Empty <PackageIdentity>(),
                    availablePackages,
                    sourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource),
                    logger);

                var resolver          = new PackageResolver();
                var packagesToInstall = resolver.Resolve(resolverContext, CancellationToken.None)
                                        .Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p)));
                var packagePathResolver      = new PackagePathResolver(Path.GetFullPath("packages"));
                var packageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv3,
                    XmlDocFileSaveMode.None,
                    ClientPolicyContext.GetClientPolicy(settings, logger),
                    logger);
                //new PackageSignatureVerifier(
                //  signatureVerification.GetSignatureVerificationProviders()),
                //SignedPackageVerifierSettings.GetDefault());
                var frameworkReducer = new FrameworkReducer();

                foreach (var packageToInstall in packagesToInstall)
                {
                    InstallPackages(packagePathResolver, packageToInstall, cacheContext, packageExtractionContext,
                                    frameworkReducer, nuGetFramework, settings, logger);
                }
            }
        }
        public async Task Test_ExtractionHonorsFileTimestamp()
        {
            // Arrange
            var packageIdentity   = new PackageIdentity("packageA", new NuGetVersion("2.0.3"));
            var entryModifiedTime = new DateTimeOffset(1985, 11, 20, 12, 0, 0, TimeSpan.FromHours(-7.0)).DateTime;

            using (var packagesDirectory = TestDirectory.Create())
            {
                var pathResolver    = new VersionFolderPathResolver(packagesDirectory);
                var packageFileInfo = await TestPackagesCore.GeneratePackageAsync(
                    packagesDirectory,
                    packageIdentity.Id,
                    packageIdentity.Version.ToNormalizedString(),
                    entryModifiedTime,
                    "lib/net45/A.dll");

                var packageExtractionContext = new PackageExtractionContext(
                    packageSaveMode: PackageSaveMode.Defaultv3,
                    xmlDocFileSaveMode: XmlDocFileSaveMode.None,
                    clientPolicyContext: null,
                    logger: NullLogger.Instance);

                var versionFolderPathResolver = new VersionFolderPathResolver(packagesDirectory);

                // Act
                using (var packageDownloader = new LocalPackageArchiveDownloader(
                           null,
                           packageFileInfo.FullName,
                           packageIdentity,
                           NullLogger.Instance))
                {
                    await PackageExtractor.InstallFromSourceAsync(
                        packageIdentity,
                        packageDownloader,
                        versionFolderPathResolver,
                        packageExtractionContext,
                        CancellationToken.None);
                }

                // Assert
                var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version);
                AssertDirectoryExists(packageVersionDirectory);

                var dllPath     = Path.Combine(packageVersionDirectory, "lib", "net45", "A.dll");
                var dllFileInfo = new FileInfo(dllPath);
                AssertFileExists(dllFileInfo.FullName);
                Assert.Equal(entryModifiedTime, dllFileInfo.LastWriteTime);
            }
        }
        public VSAPIProjectContext(bool skipAssemblyReferences, bool bindingRedirectsDisabled)
        {
            var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

            PackageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv2,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                new LoggerAdapter(this),
                signedPackageVerifier,
                SignedPackageVerifierSettings.GetDefault());

            SourceControlManagerProvider = ServiceLocator.GetInstanceSafe <ISourceControlManagerProvider>();
            SkipAssemblyReferences       = skipAssemblyReferences;
            BindingRedirectsDisabled     = bindingRedirectsDisabled;
        }
예제 #7
0
        private void InitNuGet()
        {
            _nugetSettings = Settings.LoadDefaultSettings(root: null);
            _nugetSourceRepositoryProvider = new SourceRepositoryProvider(_nugetSettings, Repository.Provider.GetCoreV3());
            _nuGetFramework    = NuGetFramework.ParseFolder("netstandard2.0");
            _packagesDirectory = _fileSystemManager.BuildFilePath(Path.Combine(_neonConfig.Plugins.Directory, "packages"));

            _fileSystemManager.CreateDirectory(Path.Combine(_neonConfig.Plugins.Directory, "packages"));
            _packagePathResolver = new PackagePathResolver(_packagesDirectory);

            _packageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.None,
                ClientPolicyContext.GetClientPolicy(_nugetSettings, NullLogger.Instance), NullLogger.Instance);
        }
 public ProjectRestoreRequest(
     RestoreRequest request,
     PackageSpec packageSpec,
     LockFile existingLockFile,
     RestoreCollectorLogger log)
 {
     CacheContext             = request.CacheContext;
     Log                      = log;
     PackagesDirectory        = request.PackagesDirectory;
     ExistingLockFile         = existingLockFile;
     MaxDegreeOfConcurrency   = request.MaxDegreeOfConcurrency;
     PackageSaveMode          = request.PackageSaveMode;
     Project                  = packageSpec;
     XmlDocFileSaveMode       = request.XmlDocFileSaveMode;
     PackageExtractionContext = new PackageExtractionContext(request.PackageSaveMode, request.XmlDocFileSaveMode, log, request.PackageSignatureVerifier);
 }
예제 #9
0
 public TestRestoreRequest(
     PackageSpec project,
     IEnumerable <PackageSource> sources,
     string packagesDirectory,
     PackageExtractionContext extractionContext,
     ILogger log)
     : this(
         project,
         sources.Select(source => Repository.Factory.GetCoreV3(source.Source)),
         packagesDirectory,
         new List <string>(),
         new TestSourceCacheContext(),
         extractionContext,
         log)
 {
 }
예제 #10
0
        private PackageExtractionContext GetExtractionContext()
        {
            // TODO read and check signatures
            var signaturesCerts = Enumerable.Empty <TrustedSignerAllowListEntry>().ToList();

            var policyContextForClient = ClientPolicyContext.GetClientPolicy(Settings.LoadDefaultSettings(null), _nugetLogger);

            var extractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.Skip,
                policyContextForClient,
                _nugetLogger
                );

            return(extractionContext);
        }
예제 #11
0
        public async Task <List <PackageSearchItem> > GetLocal(Project project, PackageIdentity identity)
        {
            var result = new List <PackageSearchItem>();

            using (var cacheContext = new SourceCacheContext())
            {
                var repositories      = DefaultSourceRepositoryProvider.GetRepositories();
                var availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default);
                await GetPackageDependencies(identity, cacheContext, availablePackages);

                var resolverContext = new PackageResolverContext(
                    DependencyBehavior.Lowest,
                    new[] { identity.Id },
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <NuGet.Packaging.PackageReference>(),
                    Enumerable.Empty <PackageIdentity>(),
                    availablePackages,
                    DefaultSourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource),
                    NullLogger.Instance);

                var resolver = new PackageResolver();
                // resolverContext.IncludeUnlisted = true;
                var packagesToInstall = resolver.Resolve(resolverContext, CancellationToken.None)
                                        .Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p)));
                var packagePathResolver      = new NuGet.Packaging.PackagePathResolver(PackagesInstallFolder);
                var clientPolicyContext      = NuGet.Packaging.Signing.ClientPolicyContext.GetClientPolicy(Settings, NullLogger.Instance);
                var packageExtractionContext = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.None, clientPolicyContext, NullLogger.Instance);
                var frameworkReducer         = new FrameworkReducer();

                foreach (var packageToInstall in packagesToInstall)
                {
                    var installedPath = packagePathResolver.GetInstalledPath(packageToInstall);
                    if (installedPath != null)
                    {
                        // per project or joined ?
                        // string TargetFolder = System.IO.Path.Combine(project.Path, "extensions");
                        string TargetFolder = System.IO.Path.Combine(Interfaces.Extensions.ProjectsDirectory, "extensions");

                        PackageReaderBase packageReader;
                        packageReader = new PackageFolderReader(installedPath);

                        result.Add(new PackageSearchItem(project, packageReader));
                    }
                }
            }
            return(result);
        }
예제 #12
0
        public static async Task <DownloadResourceResult> AddPackageAsync(
            string source,
            PackageIdentity packageIdentity,
            Stream packageStream,
            string globalPackagesFolder,
            Guid parentId,
            PackageExtractionContext extractionContext,
            ILogger logger,
            CancellationToken token)
        {
            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

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

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

            // The following call adds it to the global packages folder.
            // Addition is performed using ConcurrentUtils, such that,
            // multiple processes may add at the same time

            var versionFolderPathResolver = new VersionFolderPathResolver(globalPackagesFolder);

            await PackageExtractor.InstallFromSourceAsync(
                source,
                packageIdentity,
                stream => packageStream.CopyToAsync(stream, BufferSize, token),
                versionFolderPathResolver,
                extractionContext,
                token,
                parentId);

            var package = GetPackage(packageIdentity, globalPackagesFolder);

            Debug.Assert(package.PackageStream.CanSeek);
            Debug.Assert(package.PackageReader != null);

            return(package);
        }
예제 #13
0
        private async Task PushPackageToFileSystem(Uri sourceUri,
                                                   string pathToPackage,
                                                   bool skipDuplicate,
                                                   ILogger log,
                                                   CancellationToken token)
        {
            var             root            = sourceUri.LocalPath;
            PackageIdentity packageIdentity = null;

            using (var reader = new PackageArchiveReader(pathToPackage))
            {
                packageIdentity = reader.GetIdentity();
            }

            if (IsV2LocalRepository(root))
            {
                var pathResolver    = new PackagePathResolver(sourceUri.AbsolutePath, useSideBySidePaths: true);
                var packageFileName = pathResolver.GetPackageFileName(packageIdentity);

                var fullPath = Path.Combine(root, packageFileName);
                File.Copy(pathToPackage, fullPath, overwrite: true);

                //Indicate that SkipDuplicate is currently not supported in this scenario.
                if (skipDuplicate)
                {
                    log?.LogWarning(Strings.PushCommandSkipDuplicateNotImplemented);
                }
            }
            else
            {
                var packageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv3,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    ClientPolicyContext.GetClientPolicy(Settings, log),
                    log);

                var context = new OfflineFeedAddContext(pathToPackage,
                                                        root,
                                                        log,
                                                        throwIfSourcePackageIsInvalid: true,
                                                        throwIfPackageExistsAndInvalid: !skipDuplicate,
                                                        throwIfPackageExists: !skipDuplicate,
                                                        extractionContext: packageExtractionContext);

                await OfflineFeedUtility.AddPackageToSource(context, token);
            }
        }
        /// <summary>
        /// Create a packagets.config folder of nupkgs
        /// </summary>
        public static async Task CreateFolderFeedPackagesConfigAsync(string root, params string[] nupkgPaths)
        {
            var resolver = new PackagePathResolver(root);
            var context  = new PackageExtractionContext(
                PackageSaveMode.Defaultv2,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                NullLogger.Instance,
                signedPackageVerifier: null);

            foreach (var path in nupkgPaths)
            {
                using (var stream = File.OpenRead(path))
                {
                    await PackageExtractor.ExtractPackageAsync(stream, resolver, context, CancellationToken.None);
                }
            }
        }
        public static async Task InstallPackages(PackagePathResolver packagePathResolver, SourcePackageDependencyInfo packageToInstall, SourceCacheContext cacheContext,
                                                 PackageExtractionContext packageExtractionContext, FrameworkReducer frameworkReducer, NuGetFramework nuGetFramework, ISettings settings, ILogger logger)
        {
            PackageReaderBase packageReader;
            var installedPath = packagePathResolver.GetInstalledPath(packageToInstall);

            if (installedPath == null)
            {
                var downloadResource =
                    await packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None);

                var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                    packageToInstall,
                    new PackageDownloadContext(cacheContext),
                    SettingsUtility.GetGlobalPackagesFolder(settings),
                    logger, CancellationToken.None);

                await PackageExtractor.ExtractPackageAsync(
                    downloadResult.PackageSource,
                    downloadResult.PackageStream,
                    packagePathResolver,
                    packageExtractionContext,
                    CancellationToken.None);

                packageReader = downloadResult.PackageReader;
            }
            else
            {
                packageReader = new PackageFolderReader(installedPath);
            }

            var libItems = packageReader.GetLibItems();
            var nearest  = frameworkReducer.GetNearest(nuGetFramework, libItems.Select(x => x.TargetFramework));

            Console.WriteLine(string.Join("\n", libItems
                                          .Where(x => x.TargetFramework.Equals(nearest))
                                          .SelectMany(x => x.Items)));

            var frameworkItems = packageReader.GetFrameworkItems();

            nearest = frameworkReducer.GetNearest(nuGetFramework,
                                                  frameworkItems.Select(x => x.TargetFramework));
            Console.WriteLine(string.Join("\n", frameworkItems
                                          .Where(x => x.TargetFramework.Equals(nearest))
                                          .SelectMany(x => x.Items)));
        }
예제 #16
0
        public virtual async Task<NuGetInstallResult> InstallAsync(PackageIdentity packageIdentity, bool allowPrereleaseVersions = false)
        {
            using (var cacheContext = new SourceCacheContext())
            {
                IEnumerable<SourcePackageDependencyInfo> packagesToInstall;
                try
                {
                    packagesToInstall = await GetDependenciesAsync(packageIdentity, cacheContext);
                }
                catch (NuGetResolverInputException ex)
                {
                    logger.LogDebug(ex.ToString());
                    return new NuGetInstallResult(NuGetInstallCode.PackageOrVersionNotFound);
                }

                var packageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Nupkg,
                    XmlDocFileSaveMode.None,
                    ClientPolicyContext.GetClientPolicy(nugetSettings, logger),
                    logger);

                foreach (var packageToInstall in packagesToInstall)
                {
                    var installedPath = packagePathResolver.GetInstalledPath(packageToInstall);
                    if (installedPath == null)
                    {
                        var downloadResource = await packageToInstall.Source.GetResourceAsync<DownloadResource>(CancellationToken.None);
                        var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                            packageToInstall,
                            new PackageDownloadContext(cacheContext),
                            SettingsUtility.GetGlobalPackagesFolder(nugetSettings),
                            logger, CancellationToken.None);

                        await PackageExtractor.ExtractPackageAsync(
                            downloadResult.PackageSource,
                            downloadResult.PackageStream,
                            packagePathResolver,
                            packageExtractionContext,
                            CancellationToken.None);
                    }
                }

                return new NuGetInstallResult(packageIdentity);
            }
        }
예제 #17
0
        public async Task Test_ExtractionDoesNotExtractFiles_IfPackageSaveModeDoesNotIncludeFiles()
        {
            // Arrange
            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("2.0.3"));

            using (var packageFileInfo = TestPackagesCore.GetLegacyTestPackage())
                using (var packagesDirectory = TestDirectory.Create())
                {
                    var pathResolver             = new VersionFolderPathResolver(packagesDirectory);
                    var packageExtractionContext = new PackageExtractionContext(
                        packageSaveMode: PackageSaveMode.Nuspec | PackageSaveMode.Nupkg,
                        xmlDocFileSaveMode: XmlDocFileSaveMode.None,
                        logger: NullLogger.Instance,
                        signedPackageVerifier: null,
                        signedPackageVerifierSettings: null);

                    var versionFolderPathResolver = new VersionFolderPathResolver(packagesDirectory);

                    // Act
                    using (var packageDownloader = new LocalPackageArchiveDownloader(
                               null,
                               packageFileInfo,
                               packageIdentity,
                               NullLogger.Instance))
                    {
                        await PackageExtractor.InstallFromSourceAsync(
                            packageIdentity,
                            packageDownloader,
                            versionFolderPathResolver,
                            packageExtractionContext,
                            CancellationToken.None);
                    }

                    // Assert
                    var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version);

                    AssertDirectoryExists(packageVersionDirectory);
                    AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFileName(packageIdentity.Id, packageIdentity.Version));
                    AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(packageIdentity.Id, packageIdentity.Version));
                    AssertFileExists(packageVersionDirectory, "packagea.2.0.3.nupkg.sha512");

                    Assert.False(File.Exists(Path.Combine(packageVersionDirectory, "lib", "test.dll")));
                }
        }
예제 #18
0
        /// <summary>
        /// Asynchronously copies satellite files.
        /// </summary>
        /// <param name="packageIdentity">A package identity.</param>
        /// <param name="nuGetProjectContext">A NuGet project context.</param>
        /// <param name="token">A cancellation token.</param>
        /// <returns>A task that represents the asynchronous operation.
        /// The task result (<see cref="Task{TResult}.Result" />) returns a <see cref="bool" />
        /// indication successfulness of the operation.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="packageIdentity" />
        /// is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="nuGetProjectContext" />
        /// is <c>null</c>.</exception>
        /// <exception cref="OperationCanceledException">Thrown if <paramref name="token" />
        /// is cancelled.</exception>
        public async Task <bool> CopySatelliteFilesAsync(
            PackageIdentity packageIdentity,
            INuGetProjectContext nuGetProjectContext,
            CancellationToken token)
        {
            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

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

            token.ThrowIfCancellationRequested();

            var packageExtractionContext = nuGetProjectContext.PackageExtractionContext;

            if (packageExtractionContext == null)
            {
                var signedPackageVerifier = new PackageSignatureVerifier(
                    SignatureVerificationProviderFactory.GetSignatureVerificationProviders(),
                    SignedPackageVerifierSettings.Default);

                packageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    new LoggerAdapter(nuGetProjectContext),
                    signedPackageVerifier);
            }

            var copiedSatelliteFiles = await PackageExtractor.CopySatelliteFilesAsync(
                packageIdentity,
                PackagePathResolver,
                GetPackageSaveMode(nuGetProjectContext),
                packageExtractionContext,
                token);

            FileSystemUtility.PendAddFiles(copiedSatelliteFiles, Root, nuGetProjectContext);

            return(copiedSatelliteFiles.Any());
        }
        private async Task PushPackageToFileSystem(Uri sourceUri,
                                                   string pathToPackage,
                                                   ILogger log,
                                                   CancellationToken token)
        {
            var             root            = sourceUri.LocalPath;
            PackageIdentity packageIdentity = null;

            using (var reader = new PackageArchiveReader(pathToPackage))
            {
                packageIdentity = reader.GetIdentity();
            }

            if (IsV2LocalRepository(root))
            {
                var pathResolver    = new PackagePathResolver(root, useSideBySidePaths: true);
                var packageFileName = pathResolver.GetPackageFileName(packageIdentity);

                var fullPath = Path.Combine(root, packageFileName);
                File.Copy(pathToPackage, fullPath, overwrite: true);
            }
            else
            {
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

                var packageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv3,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    log,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(Settings, log));

                var context = new OfflineFeedAddContext(pathToPackage,
                                                        root,
                                                        log,
                                                        throwIfSourcePackageIsInvalid: true,
                                                        throwIfPackageExistsAndInvalid: false,
                                                        throwIfPackageExists: false,
                                                        extractionContext: packageExtractionContext);

                await OfflineFeedUtility.AddPackageToSource(context, token);
            }
        }
예제 #20
0
        public async Task <IEnumerable <string> > ExtractPackageAsync(string packagePath, string targetFolder)
        {
            await using FileStream packageStream = File.OpenRead(packagePath);
            PackageFolderReader      packageReader            = new PackageFolderReader(targetFolder);
            PackageExtractionContext packageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.None,
                null,
                _logger);
            NuGetPackagePathResolver packagePathResolver = new NuGetPackagePathResolver(targetFolder);
            CancellationToken        cancellationToken   = CancellationToken.None;

            return(await PackageExtractor.ExtractPackageAsync(
                       targetFolder,
                       packageStream,
                       packagePathResolver,
                       packageExtractionContext,
                       cancellationToken));
        }
예제 #21
0
        public async Task Test_ExtractPackage()
        {
            // Arrange
            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("2.0.3"));

            using (var packageFileInfo = TestPackagesCore.GetLegacyTestPackage())
                using (var packagesDirectory = TestDirectory.Create())
                {
                    var pathResolver             = new VersionFolderPathResolver(packagesDirectory);
                    var packageExtractionContext = new PackageExtractionContext(
                        packageSaveMode: PackageSaveMode.Defaultv3,
                        xmlDocFileSaveMode: XmlDocFileSaveMode.None,
                        clientPolicyContext: null,
                        logger: NullLogger.Instance);

                    var versionFolderPathResolver = new VersionFolderPathResolver(packagesDirectory);

                    // Act
                    using (var packageDownloader = new LocalPackageArchiveDownloader(
                               null,
                               packageFileInfo,
                               packageIdentity,
                               NullLogger.Instance))
                    {
                        await PackageExtractor.InstallFromSourceAsync(
                            packageIdentity,
                            packageDownloader,
                            versionFolderPathResolver,
                            packageExtractionContext,
                            CancellationToken.None);
                    }

                    // Assert
                    var packageVersionDirectory = pathResolver.GetInstallPath(packageIdentity.Id, packageIdentity.Version);

                    AssertDirectoryExists(packageVersionDirectory);
                    AssertFileExists(packageVersionDirectory, pathResolver.GetPackageFileName(packageIdentity.Id, packageIdentity.Version));
                    AssertFileExists(packageVersionDirectory, pathResolver.GetManifestFileName(packageIdentity.Id, packageIdentity.Version));
                    AssertFileExists(packageVersionDirectory, "packagea.2.0.3.nupkg.sha512");

                    AssertFileExists(packageVersionDirectory, "lib", "test.dll");
                }
        }
예제 #22
0
        public async Task <IEnumerable <string> > ExtractPackageAsync(string packagePath, string targetFolder)
        {
            using var packageStream = File.OpenRead(packagePath);
            var packageReader            = new PackageFolderReader(targetFolder);
            var packageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv3,
                XmlDocFileSaveMode.None,
                clientPolicyContext: null,
                logger: _logger);
            var packagePathResolver = new PackagePathResolver(targetFolder);
            var cancellationToken   = CancellationToken.None;

            return(await PackageExtractor.ExtractPackageAsync(
                       source : targetFolder,
                       packageStream : packageStream,
                       packagePathResolver : packagePathResolver,
                       packageExtractionContext : packageExtractionContext,
                       token : cancellationToken));
        }
예제 #23
0
 public TestRestoreRequest(
     PackageSpec project,
     IEnumerable <PackageSource> sources,
     string packagesDirectory,
     SourceCacheContext cacheContext,
     PackageExtractionContext extractionContext,
     ILogger log) : base(
         project,
         RestoreCommandProviders.Create(
             packagesDirectory,
             fallbackPackageFolderPaths: new List <string>(),
             sources: sources.Select(source => Repository.Factory.GetCoreV3(source.Source)),
             cacheContext: cacheContext,
             packageFileCache: new LocalPackageFileCache(),
             log: log),
         cacheContext,
         extractionContext,
         log)
 {
 }
예제 #24
0
        public async Task AddPackageToSource_ThrowsIfCancelledAsync()
        {
            var extractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv3,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                clientPolicyContext: null,
                logger: NullLogger.Instance);

            await Assert.ThrowsAsync <OperationCanceledException>(
                () => OfflineFeedUtility.AddPackageToSource(
                    new OfflineFeedAddContext(
                        "a",
                        "b",
                        NullLogger.Instance,
                        throwIfSourcePackageIsInvalid: false,
                        throwIfPackageExistsAndInvalid: false,
                        throwIfPackageExists: false,
                        extractionContext: extractionContext),
                    new CancellationToken(canceled: true)));
        }
예제 #25
0
 public TestRestoreRequest(
     PackageSpec project,
     IEnumerable <SourceRepository> sources,
     string packagesDirectory,
     IEnumerable <string> fallbackPackageFolders,
     SourceCacheContext cacheContext,
     PackageExtractionContext extractionContext,
     ILogger log) : base(
         project,
         RestoreCommandProviders.Create(
             packagesDirectory,
             fallbackPackageFolderPaths: fallbackPackageFolders,
             sources: sources,
             cacheContext: cacheContext,
             packageFileCache: new LocalPackageFileCache(),
             log: log),
         cacheContext,
         extractionContext,
         log)
 {
 }
예제 #26
0
        public RestoreRequest(
            PackageSpec project,
            RestoreCommandProviders dependencyProviders,
            SourceCacheContext cacheContext,
            PackageExtractionContext extractionContext,
            ILogger log)
        {
            CacheContext             = cacheContext ?? throw new ArgumentNullException(nameof(cacheContext));
            Log                      = log ?? throw new ArgumentNullException(nameof(log));
            Project                  = project ?? throw new ArgumentNullException(nameof(project));
            DependencyProviders      = dependencyProviders ?? throw new ArgumentNullException(nameof(dependencyProviders));
            PackageExtractionContext = extractionContext ?? throw new ArgumentNullException(nameof(extractionContext));

            ExternalProjects             = new List <ExternalProjectReference>();
            CompatibilityProfiles        = new HashSet <FrameworkRuntimePair>();
            PackagesDirectory            = dependencyProviders.GlobalPackages.RepositoryRoot;
            IsLowercasePackagesDirectory = true;

            // Default to the project folder
            RestoreOutputPath = Path.GetDirectoryName(Project.FilePath);
        }
예제 #27
0
        public static async Task <bool> DownloadPackage(NuGetVersion packageVersion, string installPath)
        {
            ILogger           logger            = NullLogger.Instance;
            CancellationToken cancellationToken = CancellationToken.None;

            SourceCacheContext      cache      = new SourceCacheContext();
            SourceRepository        repository = Repository.Factory.GetCoreV3(ApiNugetUrl);
            FindPackageByIdResource resource   = await repository.GetResourceAsync <FindPackageByIdResource>();

            string packageId       = PackageName;
            var    packageIdentity = new PackageIdentity(packageId, packageVersion);

            var downloader = await resource.GetPackageDownloaderAsync(packageIdentity, cache, logger, cancellationToken);

            var settings = Settings.LoadDefaultSettings(installPath);

            var packageExtractionContext  = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.None, ClientPolicyContext.GetClientPolicy(settings, logger), logger);
            var versionFolderPathResolver = new VersionFolderPathResolver(installPath);

            return(await PackageExtractor.InstallFromSourceAsync(packageIdentity, downloader, versionFolderPathResolver, packageExtractionContext, cancellationToken));
        }
예제 #28
0
        public override async Task ExecuteCommandAsync()
        {
            // Arguments[0] will not be null at this point.
            // Because, this command has MinArgs set to 1.
            var packagePath = Arguments[0];

            if (string.IsNullOrEmpty(Source))
            {
                throw new CommandLineException(
                          LocalizedResourceManager.GetString(nameof(NuGetResources.AddCommand_SourceNotProvided)));
            }

            OfflineFeedUtility.ThrowIfInvalidOrNotFound(
                packagePath,
                isDirectory: false,
                resourceString: LocalizedResourceManager.GetString(nameof(NuGetResources.NupkgPath_NotFound)));

            // If the Source Feed Folder does not exist, it will be created.
            OfflineFeedUtility.ThrowIfInvalid(Source);

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

            var packageExtractionContext = new PackageExtractionContext(
                Expand ? PackageSaveMode.Defaultv3 : PackageSaveMode.Nuspec | PackageSaveMode.Nupkg,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                Console,
                signedPackageVerifier,
                SignedPackageVerifierSettings.GetDefault());

            var offlineFeedAddContext = new OfflineFeedAddContext(
                packagePath,
                Source,
                Console, // IConsole is an ILogger
                throwIfSourcePackageIsInvalid: true,
                throwIfPackageExistsAndInvalid: true,
                throwIfPackageExists: false,
                extractionContext: packageExtractionContext);

            await OfflineFeedUtility.AddPackageToSource(offlineFeedAddContext, CancellationToken.None);
        }
예제 #29
0
        public async Task <(PackageReaderBase package, string installPath)> DownloadPackage(
            SourcePackageDependencyInfo packageToInstall)
        {
            var packagePathResolver      = new PackagePathResolver(Path.GetFullPath("packages"));
            var packageExtractionContext =
                new PackageExtractionContext(
                    PackageSaveMode.Defaultv3,
                    XmlDocFileSaveMode.None,
                    ClientPolicyContext.GetClientPolicy(_settings, _logger),
                    _logger);

            var installedPath = packagePathResolver.GetInstalledPath(packageToInstall);

            if (installedPath != null)
            {
                return(new PackageFolderReader(installedPath), installedPath);
            }

            var downloadResource =
                await packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None);

            var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                packageToInstall,
                new PackageDownloadContext(_sourceCacheContext),
                SettingsUtility.GetGlobalPackagesFolder(_settings),
                _logger,
                CancellationToken.None);

            await PackageExtractor.ExtractPackageAsync(
                downloadResult.PackageSource,
                downloadResult.PackageStream,
                packagePathResolver,
                packageExtractionContext,
                CancellationToken.None);

            installedPath = packagePathResolver.GetInstalledPath(packageToInstall);

            return(downloadResult.PackageReader, installedPath);
        }
예제 #30
0
        public Task <bool> CopySatelliteFilesAsync(PackageIdentity packageIdentity,
                                                   INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            PackageExtractionContext packageExtractionContext = nuGetProjectContext.PackageExtractionContext;

            if (packageExtractionContext == null)
            {
                packageExtractionContext = new PackageExtractionContext(new LoggerAdapter(nuGetProjectContext));
            }

            var copiedSatelliteFiles = PackageExtractor.CopySatelliteFiles(
                packageIdentity,
                PackagePathResolver,
                GetPackageSaveMode(nuGetProjectContext),
                packageExtractionContext,
                token);

            FileSystemUtility.PendAddFiles(copiedSatelliteFiles, Root, nuGetProjectContext);

            return(Task.FromResult(copiedSatelliteFiles.Any()));
        }