示例#1
0
        /// <summary>
        /// Locates the best framework folder match for the current framework and returns the assemblies
        /// and documentation files contained within the package.
        /// </summary>
        /// <param name="dependency">Dependency to be located in the packages folder.</param>
        /// <returns>Returns an array of <see cref="PackageReference"/> containing the located files.</returns>
        public PackageReference[] GetPackageReferences(Dependency dependency)
        {
            var identity        = dependency.ToPackageIdentity();
            var packageFilePath = _packageFolder.GetInstalledPackageFilePath(identity);

            if (!packageFilePath.HasValue())
            {
                return(new PackageReference[0]);
            }

            var archiveReader  = new PackageArchiveReader(packageFilePath, null, null);
            var referenceGroup = GetMostCompatibleGroup(_currentFramework, archiveReader.GetReferenceItems());
            var references     = new List <PackageReference>();

            if (referenceGroup != null)
            {
                foreach (var group in referenceGroup.Items)
                {
                    var qualified     = _packageFolder.GetInstalledPath(identity);
                    var combined      = Path.Combine(qualified, group.Replace("/", "\\"));
                    var directory     = Path.GetDirectoryName(combined);
                    var filename      = Path.GetFileNameWithoutExtension(combined);
                    var documentation = Path.Combine(directory, string.Concat(filename, ".xml"));
                    var reference     = new PackageReference
                    {
                        AssemblyPath      = combined,
                        DocumentationPath = File.Exists(documentation) ? documentation : null
                    };

                    references.Add(reference);
                }
            }

            return(references.ToArray());
        }
        public string GetPackageInstallPath(NuGetProject nugetProject, PackageIdentity package)
        {
            if (nugetProject is INuGetIntegratedProject)
            {
                return(pathResolver.GetPackageDirectory(package.Id, package.Version) ??
                       globalPackagesFolderResolver.GetInstallPath(package.Id, package.Version));
            }

            return(folderNuGetProject.GetInstalledPath(package));
        }
示例#3
0
        public List <DllInfo> GetInstallPackagesDllPath(PackageWrapper packageWrapper, ref FolderNuGetProject project)
        {
            var dllInfos = new List <DllInfo>();

            var packageIdentity = packageWrapper.rootPackageIdentity;
            var packageFilePath = project.GetInstalledPackageFilePath(packageIdentity);

            if (!string.IsNullOrWhiteSpace(packageFilePath))
            {
                Logger.LogInformation(packageFilePath);


                var archiveReader  = new PackageArchiveReader(packageFilePath, null, null);
                var referenceGroup =
                    NugetHelper.Instance.GetMostCompatibleGroup(archiveReader.GetReferenceItems());
                if (referenceGroup != null)
                {
                    foreach (var group in referenceGroup.Items)
                    {
                        var installedPackagedFolder = project.GetInstalledPath(packageIdentity);
                        var installedDllPath        = Path.Combine(installedPackagedFolder, group);

                        var installedDllFolder = Path.GetDirectoryName(installedDllPath);
                        var dllName            = Path.GetFileName(installedDllPath);
                        var extension          = Path.GetExtension(installedDllPath).ToLower();
                        var processor          = group.GetProcessor();

                        Logger.LogInformation($"dll Path: {installedDllPath}");

                        //check if file path exist , then only add
                        if (File.Exists(installedDllPath) && extension == ".dll")
                        {
                            dllInfos.Add(
                                new DllInfo()
                            {
                                name        = dllName,
                                path        = installedDllPath,
                                framework   = referenceGroup.TargetFramework.DotNetFrameworkName,
                                processor   = processor,
                                rootPackage = packageIdentity.Id
                            }
                                );
                        }

                        //also , try to cross refer this with expected folder name to avoid version mismatch
                    }
                }
            }


            return(dllInfos);
        }
示例#4
0
        public string GetPackagePathInOutputDirectory(PackageIdentity identity)
        {
            var project = new FolderNuGetProject(OutputPackagesPath);

            var path = project.GetInstalledPath(identity);

            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }

            return(path);
        }
        public async Task DeletePackage_DeletesPackage()
        {
            // Arrange
            using (var randomTestSourcePath = TestDirectory.Create())
                using (var randomTestDestinationPath = TestDirectory.Create())
                {
                    var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
                    var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyContentPackage(
                        randomTestSourcePath,
                        packageIdentity.Id,
                        packageIdentity.Version.ToNormalizedString());
                    var folderNuGetProject      = new FolderNuGetProject(randomTestDestinationPath);
                    var packagePathResolver     = new PackagePathResolver(randomTestDestinationPath);
                    var packageInstallPath      = packagePathResolver.GetInstallPath(packageIdentity);
                    var nupkgFilePath           = Path.Combine(packageInstallPath, packagePathResolver.GetPackageFileName(packageIdentity));
                    var testNuGetProjectContext = new TestNuGetProjectContext();
                    var token = CancellationToken.None;
                    using (var packageStream = GetDownloadResourceResult(packageFileInfo))
                    {
                        // Act
                        await folderNuGetProject.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
                    }

                    var unNormalizedPackageIdentity = new PackageIdentity(packageIdentity.Id,
                                                                          new NuGetVersion(packageIdentity.Version + ".0"));

                    // Assert
                    Assert.True(File.Exists(nupkgFilePath));
                    Assert.True(File.Exists(Path.Combine(packageInstallPath, "Content/Scripts/test1.js")));
                    using (var packageStream = File.OpenRead(nupkgFilePath))
                    {
                        var zipArchive = new ZipArchive(packageStream);
                        Assert.Equal(6, zipArchive.Entries.Count);
                    }
                    Assert.True(folderNuGetProject.PackageExists(packageIdentity));
                    var packageDirectoryPath = folderNuGetProject.GetInstalledPath(unNormalizedPackageIdentity);
                    Assert.True(!string.IsNullOrEmpty(packageDirectoryPath));
                    Assert.True(Directory.Exists(packageDirectoryPath));

                    // Main Act
                    await folderNuGetProject.DeletePackage(packageIdentity, testNuGetProjectContext, CancellationToken.None);

                    // Assert
                    Assert.False(folderNuGetProject.PackageExists(unNormalizedPackageIdentity));
                    // Check that the package directories are deleted
                    Assert.False(Directory.Exists(packageDirectoryPath));
                }
        }
        public async Task GetInstalledPath_ReturnsInstalledPath()
        {
            // Arrange
            using (var randomTestSourcePath = TestDirectory.Create())
                using (var randomTestDestinationPath = TestDirectory.Create())
                {
                    var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
                    var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(
                        randomTestSourcePath,
                        packageIdentity.Id,
                        packageIdentity.Version.ToNormalizedString());
                    var folderNuGetProject      = new FolderNuGetProject(randomTestDestinationPath);
                    var packagePathResolver     = new PackagePathResolver(randomTestDestinationPath);
                    var packageInstallPath      = packagePathResolver.GetInstallPath(packageIdentity);
                    var nupkgFilePath           = Path.Combine(packageInstallPath, packagePathResolver.GetPackageFileName(packageIdentity));
                    var testNuGetProjectContext = new TestNuGetProjectContext();
                    var token = CancellationToken.None;
                    using (var packageStream = GetDownloadResourceResult(packageFileInfo))
                    {
                        // Act
                        await folderNuGetProject.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
                    }

                    // Assert
                    Assert.True(File.Exists(nupkgFilePath));
                    Assert.True(File.Exists(Path.Combine(packageInstallPath, "lib/test.dll")));
                    using (var packageStream = File.OpenRead(nupkgFilePath))
                    {
                        var zipArchive = new ZipArchive(packageStream);
                        Assert.Equal(5, zipArchive.Entries.Count);
                    }

                    // Main Act
                    var installedPath = folderNuGetProject.GetInstalledPath(
                        new PackageIdentity(
                            packageIdentity.Id,
                            new NuGetVersion(packageIdentity.Version + ".0")));

                    // Assert
                    Assert.NotNull(installedPath);
                    Assert.True(Directory.Exists(installedPath));
                    Assert.True(string.Equals(packageInstallPath, installedPath));
                }
        }
        private void ExtractPackageAssemblies(IEnumerable <PackageIdentity> identities)
        {
            if (!Extract)
            {
                return;
            }

            var project = new FolderNuGetProject(_downloadDir);

            if (!Directory.Exists(_extractDir))
            {
                Directory.CreateDirectory(_extractDir);
            }

            foreach (PackageIdentity identity in identities)
            {
                string packageFilePath = project.GetInstalledPackageFilePath(identity);
                if (string.IsNullOrWhiteSpace(packageFilePath))
                {
                    continue;
                }

                FrameworkSpecificGroup?referenceGroup;
                using (var archiveReader = new PackageArchiveReader(packageFilePath, null, null))
                    referenceGroup = GetMostCompatibleGroup(_framework, archiveReader.GetReferenceItems());

                if (referenceGroup is null || referenceGroup.Items is null || !referenceGroup.Items.Any())
                {
                    continue;
                }

                string nugetPackagePath = project.GetInstalledPath(identity);
                Parallel.ForEach(referenceGroup.Items, x =>
                {
                    string sourceAssemblyPath = Path.Combine(nugetPackagePath, x);

                    string assemblyName            = Path.GetFileName(sourceAssemblyPath);
                    string destinationAssemblyPath = Path.Combine(_extractDir, assemblyName);

                    File.Copy(sourceAssemblyPath, destinationAssemblyPath, true);
                });
            }
        }
示例#8
0
        private async Task <IVsPathContext> GetPathContextForPackagesConfigAsync(
            IVsProjectAdapter vsProjectAdapter, CancellationToken token)
        {
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var props = new Dictionary <string, object>();

            props.Add(NuGetProjectMetadataKeys.Name, Path.GetFileNameWithoutExtension(vsProjectAdapter.FullProjectPath));
            props.Add(NuGetProjectMetadataKeys.TargetFramework, await vsProjectAdapter.GetTargetFrameworkAsync());

            var packagesProject = new PackagesConfigNuGetProject(vsProjectAdapter.ProjectDirectory, props);

            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(_solutionManager.Value, _settings.Value);
            var folderProject      = new FolderNuGetProject(packagesFolderPath);

            // switch to a background thread to process packages data
            await TaskScheduler.Default;

            var packageReferences = await packagesProject.GetInstalledPackagesAsync(token);

            var trie = new PathLookupTrie <string>();

            foreach (var pid in packageReferences.Select(pr => pr.PackageIdentity))
            {
                var packageInstallPath = folderProject.GetInstalledPath(pid);
                if (string.IsNullOrEmpty(packageInstallPath))
                {
                    throw new KeyNotFoundException(string.Format(CultureInfo.CurrentCulture, VsResources.PathContext_PackageDirectoryNotFound, pid));
                }

                trie[packageInstallPath] = packageInstallPath;
            }

            var pathContext = GetSolutionPathContext();

            return(new VsIndexedPathContext(
                       pathContext.UserPackageFolder,
                       pathContext.FallbackPackageFolders.Cast <string>(),
                       trie));
        }
示例#9
0
        public static string GetInstallPath(ISolutionManager solution, ISettings settings, Project project, PackageIdentity identity)
        {
            string installPath = string.Empty;

            NuGetProject       nuGetProject  = GetProject(solution, project);
            FolderNuGetProject folderProject = nuGetProject as FolderNuGetProject;

            if (folderProject != null)
            {
                installPath = folderProject.GetInstalledPath(identity);
            }
            else if (solution != null && settings != null)
            {
                string packagesFolder = PackagesFolderPathUtility.GetPackagesFolderPath(solution, settings);

                FolderNuGetProject solutionLevel = new FolderNuGetProject(packagesFolder);
                installPath = solutionLevel.GetInstalledPath(identity);
            }

            Debug.Fail("unable to get install path");

            return(installPath);
        }
示例#10
0
        public async Task DownloadPackage(PackageWrapper packageWrapper)
        {
            try
            {
                //this will prevent install to look in all repos
                _sourceRepos = new List <SourceRepository>();
                _sourceRepos.Add(packageWrapper.sourceRepository);

                var packageIdentity = packageWrapper.rootPackageIdentity;
                var providers       = new List <Lazy <INuGetResourceProvider> >();
                providers.AddRange(Repository.Provider.GetCoreV3()); // Add v3 API s

                var rootPath = NugetHelper.Instance.GetNugetSettings()
                               .NugetFolder;

                //var settings = Settings.LoadDefaultSettings(@"C:\Program Files (x86)\NuGet\Config", "Microsoft.VisualStudio.Offline.config", new MachineWideSettings());
                var machineWideSettings      = new MachineWideSettings();
                var settings                 = new Settings(rootPath);
                var packageSourceProvider    = new PackageSourceProvider(settings);
                var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);
                var project = new FolderNuGetProject(rootPath);

                var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, rootPath)
                {
                    PackagesFolderNuGetProject = project
                };

                var allowPrereleaseVersions         = true;
                var allowUnlisted                   = false;
                INuGetProjectContext projectContext = new ProjectContext();

                var resolutionContext = new ResolutionContext(DependencyBehavior.Lowest, allowPrereleaseVersions, allowUnlisted, VersionConstraints.None);

                if (NugetHelper.Instance.GetNugetSettings()
                    .DisableCache)
                {
                    resolutionContext.SourceCacheContext.NoCache        = true;
                    resolutionContext.SourceCacheContext.DirectDownload = true;
                }

                var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext, rootPath, resolutionContext.SourceCacheContext.DirectDownload);

                var packageAlreadyExists = packageManager.PackageExistsInPackagesFolder(packageIdentity, PackageSaveMode.None);

                if (!packageAlreadyExists)
                {
                    await packageManager.InstallPackageAsync(project, packageIdentity, resolutionContext, projectContext, downloadContext, _sourceRepos, new List <SourceRepository>(), CancellationToken.None);

                    var packageDeps = packageManager.GetInstalledPackagesDependencyInfo(project, CancellationToken.None, true);
                    _logger.LogDebug($"Package {packageIdentity.Id} is got Installed at 【 {project.GetInstalledPath(packageIdentity)}】 ");
                }
                else
                {
                    var packageDeps = packageManager.GetInstalledPackagesDependencyInfo(project, CancellationToken.None, true);
                    _logger.LogDebug($"Package {packageIdentity.Id} is Already Installed at 【 {project.GetInstalledPath(packageIdentity)} 】" + " | skipping instalation !!");
                }

                #region GetDll paths

                var dllstoAdd = NugetHelper.Instance.GetInstallPackagesDllPath(packageWrapper, ref project);

                if (dllstoAdd.Count > 0)
                {
                    downloadedDllPaths.AddRange(dllstoAdd);
                }

                #endregion

                _logger.LogDebug($"done for package {packageIdentity.Id} , with total Dlls {downloadedDllPaths.Count}");
            }
            catch (Exception e)
            {
                NugetHelper.Instance.logger.LogDebug(e.Message);

                throw;
            }
        }
示例#11
0
 /// <summary>Returns the package directory path if it exists, null otherwise</summary>
 public static DirectoryPath GetPackageDirectoryPath(this NuGetPackage pkg, FolderNuGetProject project)
 {
     return(project.GetInstalledPath(pkg.Identity));
 }
示例#12
0
        public async Task UninstallAsync(PackageIdentity package, IExtensibleProject project, IEnumerable <PackageReference> installedPackageReferences,
                                         CancellationToken cancellationToken = default)
        {
            List <string> failedEntries = null;
            ICollection <PackageIdentity> uninstalledPackages;

            var targetFramework = FrameworkParser.TryParseFrameworkName(project.Framework, _frameworkNameProvider);

#if NET5_0_OR_GREATER
            var reducer      = new FrameworkReducer();
            var mostSpecific = reducer.ReduceUpwards(project.SupportedPlatforms).FirstOrDefault();
            targetFramework = mostSpecific;
#endif

            var projectConfig         = _nuGetProjectConfigurationProvider.GetProjectConfig(project);
            var uninstallationContext = new UninstallationContext(false, false);

            _nugetLogger.LogInformation($"Uninstall package {package}, Target framework: {targetFramework}");

            if (projectConfig is null)
            {
                _nugetLogger.LogWarning($"Project {project.Name} doesn't implement any configuration for own packages");
            }

            using (var cacheContext = new SourceCacheContext()
            {
                NoCache = false,
                DirectDownload = false,
            })
            {
                var dependencyInfoResource = await project.AsSourceRepository(_sourceRepositoryProvider)
                                             .GetResourceAsync <DependencyInfoResource>(cancellationToken);

                var dependencyInfoResourceCollection = new DependencyInfoResourceCollection(dependencyInfoResource);

                var resolverContext = await ResolveDependenciesAsync(package, targetFramework, PackageIdentity.Comparer, dependencyInfoResourceCollection, cacheContext, project, true, cancellationToken);

                var packageReferences = installedPackageReferences.ToList();

                if (uninstallationContext.RemoveDependencies)
                {
                    uninstalledPackages = await GetPackagesCanBeUninstalledAsync(resolverContext.AvailablePackages, packageReferences.Select(x => x.PackageIdentity));
                }
                else
                {
                    uninstalledPackages = new List <PackageIdentity>()
                    {
                        package
                    };
                }
            }

            try
            {
                foreach (var removedPackage in uninstalledPackages)
                {
                    if (removedPackage.Version is null)
                    {
                        _nugetLogger.LogWarning($"Skip package {removedPackage.Id} uninstall. Check your package.config for references of this packages");
                        continue;
                    }

                    var folderProject = new FolderNuGetProject(project.ContentPath);

                    if (folderProject.PackageExists(removedPackage))
                    {
                        _directoryService.ForceDeleteDirectory(_fileService, folderProject.GetInstalledPath(removedPackage), out failedEntries);
                    }

                    if (projectConfig is null)
                    {
                        continue;
                    }

                    var result = await projectConfig.UninstallPackageAsync(removedPackage, _nuGetProjectContextProvider.GetProjectContext(FileConflictAction.PromptUser), cancellationToken);

                    if (!result)
                    {
                        _nugetLogger.LogError($"Saving package configuration failed in project {project} when installing package {package}");
                    }
                }
            }
            catch (IOException ex)
            {
                Log.Error(ex);
                _nugetLogger.LogError("Package files cannot be complete deleted by unexpected error (may be directory in use by another process?");
            }
            finally
            {
                LogHelper.LogUnclearedPaths(failedEntries, Log);
            }
        }
示例#13
0
 /// <summary>Returns the package directory path if it exists, null otherwise</summary>
 public DirectoryPath GetPackageDirectoryPath(FolderNuGetProject project)
 {
     return(project.GetInstalledPath(Identity));
 }