// Creates the project lists. Also called after a project is added/removed/renamed. private void CreateProjectLists() { // unhook event handler if (Projects != null) { foreach (var project in Projects) { project.SelectedChanged -= Project_SelectedChanged; } } _nugetProjects = _solutionManager.GetNuGetProjects(); Projects = _nugetProjects.Select( nugetProject => new PackageInstallationInfo(nugetProject)) .ToList(); // hook up event handler foreach (var project in Projects) { project.SelectedChanged += Project_SelectedChanged; } UpdateInstalledVersions(); UpdateSelectCheckBoxState(); CanUninstall = false; CanInstall = false; }
public static async Task <DependencyGraphSpec> GetSolutionRestoreSpec( ISolutionManager solutionManager, DependencyGraphCacheContext context) { var dgSpec = new DependencyGraphSpec(); var projects = solutionManager.GetNuGetProjects().OfType <IDependencyGraphProject>(); foreach (var project in projects) { var packageSpecs = await project.GetPackageSpecsAsync(context); foreach (var packageSpec in packageSpecs) { dgSpec.AddProject(packageSpec); if (packageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference || packageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.ProjectJson || packageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.DotnetCliTool || packageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.Standalone) { dgSpec.AddRestore(packageSpec.RestoreMetadata.ProjectUniqueName); } } } // Return dg file return(dgSpec); }
public IEnumerable <IVsPackageMetadata> GetInstalledPackages() { List <IVsPackageMetadata> packages = new List <IVsPackageMetadata>(); // Debug.Assert(_solutionManager.SolutionDirectory != null, "SolutionDir is null"); // Calls may occur in the template wizard before the solution is actually created, in that case return no projects if (_solutionManager != null && !String.IsNullOrEmpty(_solutionManager.SolutionDirectory)) { InitializePackageManagerAndPackageFolderPath(); foreach (var project in _solutionManager.GetNuGetProjects()) { var task = System.Threading.Tasks.Task.Run(async() => await project.GetInstalledPackagesAsync(CancellationToken.None)); task.Wait(); foreach (var package in task.Result) { // find packages using the solution level packages folder string installPath = _packageManager.PackagesFolderNuGetProject.GetInstalledPath(package.PackageIdentity); var metadata = new VsPackageMetadata(package.PackageIdentity, installPath); packages.Add(metadata); } } } return(packages); }
/// <summary> /// Find the list of parent projects which directly or indirectly reference the child project. /// </summary> public static async Task <IReadOnlyList <BuildIntegratedNuGetProject> > GetParentProjectsInClosure( ISolutionManager solutionManager, BuildIntegratedNuGetProject target, ExternalProjectReferenceContext referenceContext) { var projects = solutionManager.GetNuGetProjects().OfType <BuildIntegratedNuGetProject>().ToList(); return(await GetParentProjectsInClosure(projects, target, referenceContext)); }
public static async Task <bool> IsRestoreRequiredAsync( ISolutionManager solutionManager, bool forceRestore, INuGetPathContext pathContext, DependencyGraphCacheContext cacheContext, string oldDependencyGraphSpecHash) { var projects = solutionManager.GetNuGetProjects().OfType <IDependencyGraphProject>().ToArray(); var solutionDgSpec = await GetSolutionRestoreSpec(solutionManager, cacheContext); if (solutionDgSpec.Restore.Count < 1) { // Nothing to restore return(false); } var newDependencyGraphSpecHash = solutionDgSpec.GetHash(); cacheContext.SolutionSpec = solutionDgSpec; cacheContext.SolutionSpecHash = newDependencyGraphSpecHash; // Comment by @emgarten from PR - // Force is only done during a rebuild, all of the work done here to build the dg file is stored in the cache context and used again later on. // The time different should only be the time it takes to create the hash, which @dtivel has perf numbers on. if (forceRestore || (oldDependencyGraphSpecHash != newDependencyGraphSpecHash)) { // A new project has been added return(true); } // Read package folder locations, initializing them in order of priority var packageFolderPaths = new List <string>(); packageFolderPaths.Add(pathContext.UserPackageFolder); packageFolderPaths.AddRange(pathContext.FallbackPackageFolders); var pathResolvers = packageFolderPaths.Select(path => new VersionFolderPathResolver(path)); var packagesChecked = new HashSet <PackageIdentity>(); if ( projects.Select(async p => await p.IsRestoreRequired(pathResolvers, packagesChecked, cacheContext)) .Any(r => r.Result == true)) { // The project.json file does not match the lock file return(true); } if (cacheContext.DeferredPackageSpecs.Where(spec => spec.RestoreMetadata.ProjectJsonPath != null). Select(p => IsRestoreRequired(p, pathResolvers, packagesChecked, cacheContext)) .Any(r => r == true)) { return(true); } return(false); }
public IEnumerable <IVsPackageMetadata> GetInstalledPackages() { var packages = new HashSet <IVsPackageMetadata>(new VsPackageMetadataComparer()); return(ThreadHelper.JoinableTaskFactory.Run(async delegate { // Calls may occur in the template wizard before the solution is actually created, // in that case return no projects if (_solutionManager != null && !string.IsNullOrEmpty(_solutionManager.SolutionDirectory)) { InitializePackageManagerAndPackageFolderPath(); var effectiveGlobalPackagesFolder = BuildIntegratedProjectUtility.GetEffectiveGlobalPackagesFolder( _solutionManager.SolutionDirectory, _settings); foreach (var project in _solutionManager.GetNuGetProjects()) { var installedPackages = await project.GetInstalledPackagesAsync(CancellationToken.None); var buildIntegratedProject = project as BuildIntegratedNuGetProject; foreach (var package in installedPackages) { if (!package.PackageIdentity.HasVersion) { // Currently we are not supporting floating versions // because of that we will skip this package continue; } // find packages using the solution level packages folder string installPath; if (buildIntegratedProject != null) { installPath = BuildIntegratedProjectUtility.GetPackagePathFromGlobalSource( effectiveGlobalPackagesFolder, package.PackageIdentity); } else { installPath = _packageManager.PackagesFolderNuGetProject.GetInstalledPath( package.PackageIdentity); } var metadata = new VsPackageMetadata(package.PackageIdentity, installPath); packages.Add(metadata); } } } return packages; })); }
/// <summary> /// Returns all the versions of the NuGet package used in all projects in the solution /// ordered by latest version first. /// </summary> public static async Task <IEnumerable <NuGetVersion> > GetInstalledVersions( this ISolutionManager solutionManager, string packageId, CancellationToken token = default(CancellationToken)) { var versions = new List <NuGetVersion> (); foreach (NuGetProject project in solutionManager.GetNuGetProjects()) { var packages = await project.GetInstalledPackagesAsync(token); versions.AddRange(packages.Where(p => IsMatch(p, packageId)) .Select(p => p.PackageIdentity.Version)); } return(versions.Distinct().OrderByDescending(version => version)); }
public async Task <IEnumerable <PackageItem> > EnumeratePackagesAsync( NuGetPackageManager packageManager, CancellationToken token) { Assumes.Present(packageManager); // invoke init.ps1 files in the order of package dependency. // if A -> B, we invoke B's init.ps1 before A's. var installedPackages = new List <PackageItem>(); var projects = _solutionManager.GetNuGetProjects().ToList(); // Skip project K projects. projects.RemoveAll(p => p is ProjectKNuGetProjectBase); // Sort projects by type var projectLookup = projects.ToLookup(p => p is BuildIntegratedNuGetProject); // Each id/version should only be executed once var finishedPackages = new HashSet <PackageIdentity>(); // Packages.config projects await ProcessPackagesConfigProjectsAsync( projectLookup[false], packageManager, finishedPackages, installedPackages, token); // build integrated projects foreach (var project in projectLookup[true].Cast <BuildIntegratedNuGetProject>()) { await CollectPackagesForBuildIntegratedProjectAsync( project, finishedPackages, installedPackages, token); } return(installedPackages); }
public static async Task <IEnumerable <IDotNetProject> > GetProjectsWithInstalledPackage( this ISolutionManager solutionManager, string packageId, string version, CancellationToken token = default(CancellationToken)) { var nugetVersion = new NuGetVersion(version); var projects = new List <IDotNetProject> (); foreach (NuGetProject project in solutionManager.GetNuGetProjects()) { var packages = await project.GetInstalledPackagesAsync(token); if (packages.Any(p => IsMatch(p, packageId, nugetVersion))) { projects.Add(project.GetDotNetProject()); } } return(projects); }
/// <summary> /// Checks if package <paramref name="packageIdentity"/> that is installed in /// project <paramref name="nugetProject"/> is also installed in any /// other projects in the solution. /// </summary> public static async Task<bool> PackageExistsInAnotherNuGetProject(NuGetProject nuGetProject, PackageIdentity packageIdentity, ISolutionManager solutionManager, CancellationToken token) { if(nuGetProject == null) { throw new ArgumentNullException("nuGetProject"); } if (packageIdentity == null) { throw new ArgumentNullException("packageIdentity"); } if(solutionManager == null) { throw new ArgumentNullException("solutionManager"); } string nuGetProjectName = NuGetProject.GetUniqueNameOrName(nuGetProject); foreach (var otherNuGetProject in solutionManager.GetNuGetProjects()) { var otherNuGetProjectName = NuGetProject.GetUniqueNameOrName(otherNuGetProject); if (!otherNuGetProjectName.Equals(nuGetProjectName, StringComparison.OrdinalIgnoreCase)) { bool packageExistsInAnotherNuGetProject = (await otherNuGetProject.GetInstalledPackagesAsync(token)).Where(pr => pr.PackageIdentity.Equals(packageIdentity)).Any(); if (packageExistsInAnotherNuGetProject) { return true; } } } return false; }
private void ExecuteInitScripts() { // Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads. lock (_initScriptsLock) { if (!_solutionManager.IsSolutionOpen) { return; } Debug.Assert(_settings != null); if (_settings == null) { return; } try { // invoke init.ps1 files in the order of package dependency. // if A -> B, we invoke B's init.ps1 before A's. IEnumerable <NuGetProject> projects = _solutionManager.GetNuGetProjects(); NuGetPackageManager packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, _solutionManager); List <PackageIdentity> sortedPackages = new List <PackageIdentity>(); foreach (NuGetProject project in projects) { // Skip project K projects. if (project is NuGet.ProjectManagement.Projects.ProjectKNuGetProjectBase) { continue; } IEnumerable <PackageReference> installedRefs = project.GetInstalledPackagesAsync(CancellationToken.None).Result; if (installedRefs != null && installedRefs.Any()) { IEnumerable <PackageIdentity> installedPackages = packageManager.GetInstalledPackagesInDependencyOrder(project, new EmptyNuGetProjectContext(), CancellationToken.None).Result; sortedPackages.AddRange(installedPackages); } } // Get the path to the Packages folder. string packagesFolderPath = packageManager.PackagesFolderSourceRepository.PackageSource.Source; foreach (var package in sortedPackages) { PackagePathResolver packagePathResolver = new PackagePathResolver(packagesFolderPath); string pathToPackage = packagePathResolver.GetInstalledPath(package); string toolsPath = Path.Combine(pathToPackage, "tools"); AddPathToEnvironment(toolsPath); Runspace.ExecuteScript(toolsPath, PowerShellScripts.Init, package); } } catch (Exception ex) { // When Packages folder is not present, NuGetResolverInputException will be thrown // as resolving DependencyInfo requires the presence of Packages folder. if (ex.InnerException is NuGetResolverInputException) { // Silently fail. } else { // if execution of Init scripts fails, do not let it crash our console ReportError(ex); } ExceptionHelper.WriteToActivityLog(ex); } } }
private async Task ExecuteInitScriptsAsync() { // Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads. using (await _initScriptsLock.EnterAsync()) { if (!_solutionManager.IsSolutionOpen) { return; } Debug.Assert(_settings != null); if (_settings == null) { return; } // invoke init.ps1 files in the order of package dependency. // if A -> B, we invoke B's init.ps1 before A's. var sortedPackages = new List <PackageIdentity>(); var packagesFolderPackages = new HashSet <PackageIdentity>(PackageIdentity.Comparer); var globalPackages = new HashSet <PackageIdentity>(PackageIdentity.Comparer); var projects = _solutionManager.GetNuGetProjects().ToList(); var packageManager = new NuGetPackageManager( _sourceRepositoryProvider, _settings, _solutionManager, _deleteOnRestartManager); foreach (var project in projects) { // Skip project K projects. if (project is ProjectKNuGetProjectBase) { continue; } var buildIntegratedProject = project as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { var packages = BuildIntegratedProjectUtility.GetOrderedProjectDependencies(buildIntegratedProject); sortedPackages.AddRange(packages); globalPackages.UnionWith(packages); } else { var installedRefs = await project.GetInstalledPackagesAsync(CancellationToken.None); if (installedRefs != null && installedRefs.Any()) { // This will be an empty list if packages have not been restored var installedPackages = await packageManager.GetInstalledPackagesInDependencyOrder(project, CancellationToken.None); sortedPackages.AddRange(installedPackages); packagesFolderPackages.UnionWith(installedPackages); } } } // Get the path to the Packages folder. var packagesFolderPath = packageManager.PackagesFolderSourceRepository.PackageSource.Source; var packagePathResolver = new PackagePathResolver(packagesFolderPath); var globalFolderPath = SettingsUtility.GetGlobalPackagesFolder(_settings); var globalPathResolver = new VersionFolderPathResolver(globalFolderPath); var finishedPackages = new HashSet <PackageIdentity>(PackageIdentity.Comparer); foreach (var package in sortedPackages) { // Packages may occur under multiple projects, but we only need to run it once. if (!finishedPackages.Contains(package)) { finishedPackages.Add(package); try { string pathToPackage = null; // If the package exists in both the global and packages folder, use the packages folder copy. if (packagesFolderPackages.Contains(package)) { // Local package in the packages folder pathToPackage = packagePathResolver.GetInstalledPath(package); } else { // Global package pathToPackage = globalPathResolver.GetInstallPath(package.Id, package.Version); } if (!string.IsNullOrEmpty(pathToPackage)) { var toolsPath = Path.Combine(pathToPackage, "tools"); var scriptPath = Path.Combine(toolsPath, PowerShellScripts.Init); if (Directory.Exists(toolsPath)) { AddPathToEnvironment(toolsPath); if (File.Exists(scriptPath)) { if (_scriptExecutor.TryMarkVisited( package, PackageInitPS1State.FoundAndExecuted)) { var scriptPackage = new ScriptPackage( package.Id, package.Version.ToString(), pathToPackage); Runspace.ExecuteScript(pathToPackage, scriptPath, scriptPackage); } } else { _scriptExecutor.TryMarkVisited(package, PackageInitPS1State.NotFound); } } } } catch (Exception ex) { // if execution of Init scripts fails, do not let it crash our console ReportError(ex); ExceptionHelper.WriteToActivityLog(ex); } } } } }
private async Task ExecuteInitScriptsAsync() { // Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads. using (await _initScriptsLock.EnterAsync()) { if (!_solutionManager.IsSolutionOpen) { return; } Debug.Assert(_settings != null); if (_settings == null) { return; } // invoke init.ps1 files in the order of package dependency. // if A -> B, we invoke B's init.ps1 before A's. var projects = _solutionManager.GetNuGetProjects().ToList(); var packageManager = new NuGetPackageManager( _sourceRepositoryProvider, _settings, _solutionManager, _deleteOnRestartManager); var packagesByFramework = new Dictionary <NuGetFramework, HashSet <PackageIdentity> >(); var sortedGlobalPackages = new List <PackageIdentity>(); // Sort projects by type foreach (var project in projects) { // Skip project K projects. if (project is ProjectKNuGetProjectBase) { continue; } var buildIntegratedProject = project as BuildIntegratedNuGetProject; if (buildIntegratedProject != null) { var packages = BuildIntegratedProjectUtility.GetOrderedProjectDependencies(buildIntegratedProject); sortedGlobalPackages.AddRange(packages); } else { // Read packages.config var installedRefs = await project.GetInstalledPackagesAsync(CancellationToken.None); if (installedRefs?.Any() == true) { // Index packages.config references by target framework since this affects dependencies NuGetFramework targetFramework; if (!project.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out targetFramework)) { targetFramework = NuGetFramework.AnyFramework; } HashSet <PackageIdentity> fwPackages; if (!packagesByFramework.TryGetValue(targetFramework, out fwPackages)) { fwPackages = new HashSet <PackageIdentity>(); packagesByFramework.Add(targetFramework, fwPackages); } fwPackages.UnionWith(installedRefs.Select(reference => reference.PackageIdentity)); } } } // Each id/version should only be executed once var finishedPackages = new HashSet <PackageIdentity>(); // Packages.config projects if (packagesByFramework.Count > 0) { await ExecuteInitPs1ForPackagesConfig( packageManager, packagesByFramework, finishedPackages); } // build integrated projects if (sortedGlobalPackages.Count > 0) { ExecuteInitPs1ForBuildIntegrated( sortedGlobalPackages, finishedPackages); } } }