protected async Task <IReadOnlyList <ResolvedAction> > GetActionsForUpdateAsync(IEnumerable <NuGetProject> targets, PackageIdentity packageIdentity, INuGetProjectContext projectContext, SourceCacheContext sourceCacheContext, CancellationToken token) { GatherCache gatherCache = new GatherCache(); bool includePrerelease = packageIdentity.Version.IsPrerelease; List <ResolvedAction> results = new List <ResolvedAction>(); ResolutionContext resolutionContext = new ResolutionContext(_dependencyBehavior, includePrerelease, includeUnlisted: true, VersionConstraints.None, gatherCache, sourceCacheContext); try { var actions = await _packageManager.PreviewUpdatePackagesAsync(packageIdentity, targets, resolutionContext, projectContext, PrimarySourcesRepository, SecondarySourcesRepository, token); results.AddRange(actions.Select(a => new ResolvedAction(a.Project, a))); } catch (Exception ex) { Debug.WriteLine(ex); throw; } return(results); }
public Task <IEnumerable <NuGetProjectAction> > PreviewUpdatePackagesAsync( string packageId, NuGetProject nuGetProject, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable <SourceRepository> primarySources, IEnumerable <SourceRepository> secondarySources, CancellationToken token) { return(packageManager.PreviewUpdatePackagesAsync( packageId, new [] { nuGetProject }, resolutionContext, nuGetProjectContext, primarySources, secondarySources, token )); }
/// <summary> /// Calculates the list of actions needed to perform packages updates. /// </summary> /// <param name="uiService">ui service.</param> /// <param name="packagesToUpdate">The list of packages to update.</param> /// <param name="token">Cancellation token.</param> /// <returns>The list of actions.</returns> private async Task <IReadOnlyList <ResolvedAction> > ResolveActionsForUpdate( INuGetUI uiService, List <PackageIdentity> packagesToUpdate, CancellationToken token) { var resolvedActions = new List <ResolvedAction>(); // Keep a single gather cache across projects var gatherCache = new GatherCache(); foreach (var project in uiService.Projects) { var installedPackages = await project.GetInstalledPackagesAsync(token); HashSet <string> packageIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (var p in installedPackages) { packageIds.Add(p.PackageIdentity.Id); } // We need to filter out packages from packagesToUpdate that are not installed // in the current project. Otherwise, we'll incorrectly install a // package that is not installed before. var packagesToUpdateInProject = packagesToUpdate.Where( package => packageIds.Contains(package.Id)).ToList(); if (packagesToUpdateInProject.Any()) { var includePrerelease = packagesToUpdateInProject.Where( package => package.Version.IsPrerelease).Any(); var resolutionContext = new ResolutionContext( uiService.DependencyBehavior, includePrelease: includePrerelease, includeUnlisted: true, versionConstraints: VersionConstraints.None, gatherCache: gatherCache); var actions = await _packageManager.PreviewUpdatePackagesAsync( packagesToUpdateInProject, project, resolutionContext, uiService.ProgressWindow, uiService.ActiveSources, uiService.ActiveSources, token); resolvedActions.AddRange(actions.Select(action => new ResolvedAction(project, action)) .ToList()); } } return(resolvedActions); }
public async Task DoWithProject(string package, string version, ProjectBazelManipulator project, bool lowest) { var logger = new Logger(); var providers = new List <Lazy <INuGetResourceProvider> >(); providers.AddRange(Repository.Provider.GetCoreV3()); // Add v3 API support var packageSource = new PackageSource("https://api.nuget.org/v3/index.json"); var sourceRepository = new SourceRepository(packageSource, providers); var packageMetadataResource = await sourceRepository.GetResourceAsync <PackageMetadataResource>(); var verParsed = NuGetVersion.Parse(version); var identity = new NuGet.Packaging.Core.PackageIdentity(package, verParsed); var content = new SourceCacheContext(); var found = await packageMetadataResource.GetMetadataAsync(identity, content, logger, CancellationToken.None); var settings = Settings.LoadDefaultSettings(project.ProjectConfig.RootPath, null, new MachineWideSettings()); var sourceRepositoryProvider = new SourceRepositoryProvider(settings, providers); var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, project.ProjectConfig.RootPath) { PackagesFolderNuGetProject = project }; const bool allowPrereleaseVersions = true; const bool allowUnlisted = false; var resolutionContext = new ResolutionContext( lowest ? DependencyBehavior.Lowest : DependencyBehavior.HighestMinor, allowPrereleaseVersions, allowUnlisted, VersionConstraints.None); var projectContext = new ProjectContext(settings); var projects = new ProjectBazelManipulator[] { project }; var actions = await packageManager.PreviewUpdatePackagesAsync(identity, projects, resolutionContext, projectContext, new SourceRepository[] { sourceRepository }, Array.Empty <SourceRepository>(), // This is a list of secondary source respositories, probably empty CancellationToken.None); project.NuGetProjectActions = actions; var sourceCacheContext = new SourceCacheContext(); await packageManager.ExecuteNuGetProjectActionsAsync(project, actions, projectContext, sourceCacheContext, CancellationToken.None); NuGetPackageManager.ClearDirectInstall(projectContext); }
async Task <IEnumerable <NuGetProjectAction> > PreviewUpdateAllPackagesAsync( SourceCacheContext sourceCacheContext, CancellationToken token) { solutionManager = projects.FirstOrDefault().GetSolutionManager(); nugetProjects = projects .Select(project => project.CreateNuGetProject(solutionManager)) .ToList(); var repositoryProvider = solutionManager.CreateSourceRepositoryProvider(); packageManager = new NuGetPackageManager( repositoryProvider, solutionManager.Settings, solutionManager, new DeleteOnRestartManager()); var repositories = repositoryProvider.GetRepositories(message.PackageSources); projectContext = new ConsoleHostNuGetProjectContext( solutionManager.Settings, message.FileConflictAction.ToFileConflictActionEnum()); var resolutionContext = new ResolutionContext( message.DependencyBehavior.ToDependencyBehaviorEnum(), message.AllowPrerelease, false, message.VersionConstraints.ToVersionContrainsEnum(), new GatherCache(), sourceCacheContext ); return(await packageManager.PreviewUpdatePackagesAsync( nugetProjects, resolutionContext, projectContext, repositories, repositories, // Update-Package does not use all enabled package sources. token ).ConfigureAwait(false)); }
/// <summary> /// Calculates the list of actions needed to perform packages updates. /// </summary> /// <param name="uiService">ui service.</param> /// <param name="packagesToUpdate">The list of packages to update.</param> /// <param name="token">Cancellation token.</param> /// <returns>The list of actions.</returns> private async Task <IReadOnlyList <ResolvedAction> > ResolveActionsForUpdateAsync( INuGetUI uiService, List <PackageIdentity> packagesToUpdate, CancellationToken token) { var resolvedActions = new List <ResolvedAction>(); // Keep a single gather cache across projects var gatherCache = new GatherCache(); var includePrerelease = packagesToUpdate.Where( package => package.Version.IsPrerelease).Any(); using (var sourceCacheContext = new SourceCacheContext()) { var resolutionContext = new ResolutionContext( uiService.DependencyBehavior, includePrelease: includePrerelease, includeUnlisted: true, versionConstraints: VersionConstraints.None, gatherCache: gatherCache, sourceCacheContext: sourceCacheContext); var secondarySources = _sourceProvider.GetRepositories().Where(e => e.PackageSource.IsEnabled); var actions = await _packageManager.PreviewUpdatePackagesAsync( packagesToUpdate, uiService.Projects, resolutionContext, uiService.ProjectContext, uiService.ActiveSources, secondarySources, token); resolvedActions.AddRange(actions.Select(action => new ResolvedAction(action.Project, action)) .ToList()); } return(resolvedActions); }
public async Task UpdateAsync(string packageId, string source) { ResolutionContext resolutionContext; PackageDownloadContext packageDownloadContext; List <SourceRepository> sourceRepositorySet; IEnumerable <NuGetProjectAction> actionSet; resolutionContext = new ResolutionContext(DependencyBehavior.Lowest, includePrelease: true, includeUnlisted: false, VersionConstraints.None); packageDownloadContext = new PackageDownloadContext(NullSourceCacheContext.Instance); sourceRepositorySet = this.PackageSourceSet.Select(packageSource => _sourceRepositoryProvider.CreateRepository(new PackageSource(packageSource.Source))).ToList(); actionSet = await _packageManager.PreviewUpdatePackagesAsync( packageId, new List <NuGetProject>() { _project }, resolutionContext, _projectContext, sourceRepositorySet, sourceRepositorySet, CancellationToken.None); await _packageManager.ExecuteNuGetProjectActionsAsync(_project, actionSet, _projectContext, packageDownloadContext, CancellationToken.None); this.OnInstalledPackagesChanged(); }
private async Task UpdatePackagesAsync(MSBuildProjectSystem project, string packagesDirectory) { var sourceRepositoryProvider = GetSourceRepositoryProvider(); var packageManager = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesDirectory); var nugetProject = new MSBuildNuGetProject(project, packagesDirectory, project.ProjectFullPath); if (!nugetProject.PackagesConfigNuGetProject.PackagesConfigExists()) { throw new CommandLineException(LocalizedResourceManager.GetString("NoPackagesConfig")); } var versionConstraints = Safe ? VersionConstraints.ExactMajor | VersionConstraints.ExactMinor : VersionConstraints.None; var projectActions = new List <NuGetProjectAction>(); using (var sourceCacheContext = new SourceCacheContext()) { var resolutionContext = new ResolutionContext( Resolver.DependencyBehavior.Highest, Prerelease, includeUnlisted: false, versionConstraints: versionConstraints, gatherCache: new GatherCache(), sourceCacheContext: sourceCacheContext); var packageSources = GetPackageSources(); Console.PrintPackageSources(packageSources); var sourceRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository); if (Id.Count > 0) { var targetIds = new HashSet <string>(Id, StringComparer.OrdinalIgnoreCase); var installed = await nugetProject.GetInstalledPackagesAsync(CancellationToken.None); // If -Id has been specified and has exactly one package, use the explicit version requested var targetVersion = Version != null && Id != null && Id.Count == 1 ? new NuGetVersion(Version) : null; var targetIdentities = installed .Select(pr => pr.PackageIdentity.Id) .Where(id => targetIds.Contains(id)) .Select(id => new PackageIdentity(id, targetVersion)) .ToList(); if (targetIdentities.Any()) { var actions = await packageManager.PreviewUpdatePackagesAsync( targetIdentities, new[] { nugetProject }, resolutionContext, project.NuGetProjectContext, sourceRepositories, Enumerable.Empty <SourceRepository>(), CancellationToken.None); projectActions.AddRange(actions); } } else { var actions = await packageManager.PreviewUpdatePackagesAsync( new[] { nugetProject }, resolutionContext, project.NuGetProjectContext, sourceRepositories, Enumerable.Empty <SourceRepository>(), CancellationToken.None); projectActions.AddRange(actions); } await packageManager.ExecuteNuGetProjectActionsAsync( nugetProject, projectActions, project.NuGetProjectContext, sourceCacheContext, CancellationToken.None); } project.Save(); }
async Task <IEnumerable <NuGetProjectAction> > PreviewUpdatePackagesAsync( SourceCacheContext sourceCacheContext, CancellationToken token) { solutionManager = projects.FirstOrDefault().GetSolutionManager(); nugetProjects = projects .Select(project => project.CreateNuGetProject(solutionManager)) .ToList(); IsPackageInstalled = await CheckPackageInstalled(token); if (!IsPackageInstalled) { return(Enumerable.Empty <NuGetProjectAction> ()); } var repositoryProvider = solutionManager.CreateSourceRepositoryProvider(); packageManager = new NuGetPackageManager( repositoryProvider, solutionManager.Settings, solutionManager, new DeleteOnRestartManager()); var enabledRepositories = repositoryProvider.GetEnabledRepositories(); var repositories = repositoryProvider.GetRepositories(message.PackageSources); projectContext = new ConsoleHostNuGetProjectContext( solutionManager.Settings, message.FileConflictAction.ToFileConflictActionEnum()); var resolutionContext = new ResolutionContext( message.DependencyBehavior.ToDependencyBehaviorEnum(), message.AllowPrerelease, false, message.VersionConstraints.ToVersionContrainsEnum(), new GatherCache(), sourceCacheContext ); if (!string.IsNullOrEmpty(message.PackageVersion)) { var packageVersion = NuGetVersion.Parse(message.PackageVersion); return(await packageManager.PreviewUpdatePackagesAsync( new PackageIdentity (message.PackageId, packageVersion), nugetProjects, resolutionContext, projectContext, repositories, enabledRepositories, token ).ConfigureAwait(false)); } else { return(await packageManager.PreviewUpdatePackagesAsync( message.PackageId, nugetProjects, resolutionContext, projectContext, repositories, enabledRepositories, token ).ConfigureAwait(false)); } }
public async ValueTask <IReadOnlyList <ProjectAction> > GetUpdateActionsAsync( IReadOnlyCollection <string> projectIds, IReadOnlyCollection <PackageIdentity> packageIdentities, VersionConstraints versionConstraints, bool includePrelease, DependencyBehavior dependencyBehavior, IReadOnlyList <string> packageSourceNames, CancellationToken cancellationToken) { Assumes.NotNullOrEmpty(projectIds); Assumes.NotNullOrEmpty(packageIdentities); Assumes.NotNullOrEmpty(packageSourceNames); Assumes.NotNull(_state.SourceCacheContext); Assumes.NotNull(_state.ResolvedActions); Assumes.Null(_state.PackageIdentity); return(await CatchAndRethrowExceptionAsync(async() => { var primarySources = new List <SourceRepository>(); var secondarySources = new List <SourceRepository>(); IEnumerable <SourceRepository> sourceRepositories = _sharedState.SourceRepositoryProvider.GetRepositories(); var packageSourceNamesSet = new HashSet <string>(packageSourceNames, StringComparer.OrdinalIgnoreCase); foreach (SourceRepository sourceRepository in sourceRepositories) { if (packageSourceNamesSet.Contains(sourceRepository.PackageSource.Name)) { primarySources.Add(sourceRepository); } if (sourceRepository.PackageSource.IsEnabled) { secondarySources.Add(sourceRepository); } } INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync <INuGetProjectContext>(); IReadOnlyList <NuGetProject> projects = await GetProjectsAsync(projectIds, cancellationToken); var resolutionContext = new ResolutionContext( dependencyBehavior, includePrelease, includeUnlisted: true, versionConstraints, new GatherCache(), _state.SourceCacheContext); NuGetPackageManager packageManager = await _sharedState.GetPackageManagerAsync(cancellationToken); IEnumerable <NuGetProjectAction> actions = await packageManager.PreviewUpdatePackagesAsync( packageIdentities.ToList(), projects, resolutionContext, projectContext, primarySources, secondarySources, cancellationToken); var projectActions = new List <ProjectAction>(); foreach (NuGetProjectAction action in actions) { var resolvedAction = new ResolvedAction(action.Project, action); ProjectAction projectAction = CreateProjectAction(resolvedAction); _state.ResolvedActions[projectAction.Id] = resolvedAction; projectActions.Add(projectAction); } return projectActions; })); }
private static async Task MainAsync(string[] args) { CustomNuGetLogger logger = new CustomNuGetLogger(); DefaultFrameworkNameProvider frameworkNameProvider = new DefaultFrameworkNameProvider(); string testAppFrameworkName = Assembly.GetExecutingAssembly().GetCustomAttributes(true) .OfType <System.Runtime.Versioning.TargetFrameworkAttribute>() .Select(x => x.FrameworkName) .FirstOrDefault(); //string folderName = "netstandard1.1"; //NuGetFramework currentFramework = folderName == null // ? NuGetFramework.AnyFramework // : NuGetFramework.ParseFolder(folderName, frameworkNameProvider); NuGetFramework currentFramework = testAppFrameworkName == null ? NuGetFramework.AnyFramework : NuGetFramework.ParseFrameworkName(testAppFrameworkName, frameworkNameProvider); List <Lazy <INuGetResourceProvider> > resourceProviders = new List <Lazy <INuGetResourceProvider> >(); resourceProviders.AddRange(Repository.Provider.GetCoreV3()); PackageSource packageSource = new PackageSource("https://api.nuget.org/v3/index.json"); SourceRepository sourceRepository = new SourceRepository(packageSource, resourceProviders); //Console.WriteLine("Getting metadata resource..."); //PackageMetadataResource metadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource>(); //Console.WriteLine("Getting search resource..."); //PackageSearchResource searchResource = await sourceRepository.GetResourceAsync<PackageSearchResource>(); //Console.WriteLine("Getting auto complete resource..."); //AutoCompleteResource autoCompleteResource = await sourceRepository.GetResourceAsync<AutoCompleteResource>(); //Console.WriteLine("Getting dependency info resource..."); //DependencyInfoResource dependencyInfoResource = await sourceRepository.GetResourceAsync<DependencyInfoResource>(); //Console.WriteLine("Getting download resource..."); //DownloadResource downloadResource = await sourceRepository.GetResourceAsync<DownloadResource>(); // //Console.WriteLine(); //Console.WriteLine("-----------------------------------------------------------------------------"); //Console.WriteLine(); //Console.WriteLine("Getting metadata..."); //IEnumerable<IPackageSearchMetadata> metadata = await metadataResource.GetMetadataAsync("Newtonsoft.Json", false, false, logger, CancellationToken.None); //metadata.Dump(); // //Console.WriteLine(); //Console.WriteLine("-----------------------------------------------------------------------------"); //Console.WriteLine(); //Console.WriteLine("Searching metadata..."); //SearchFilter searchFilter = new SearchFilter(false, null); //metadata = await searchResource.SearchAsync("Newtonsoft.Json", searchFilter, 0, 10, logger, CancellationToken.None); //metadata.Dump(); // //Console.WriteLine(); //Console.WriteLine("-----------------------------------------------------------------------------"); //Console.WriteLine(); //Console.WriteLine("Resolving dependencies..."); //IEnumerable<RemoteSourceDependencyInfo> dependencyInfo = await dependencyInfoResource.ResolvePackages("Newtonsoft.Json", logger, CancellationToken.None); //dependencyInfo.Dump(); // //Console.WriteLine(); //Console.WriteLine("-----------------------------------------------------------------------------"); //Console.WriteLine(); //Console.WriteLine("Resolving for target framework {0}...", currentFramework); //IEnumerable<SourcePackageDependencyInfo> dependencyInfo2 = await dependencyInfoResource.ResolvePackages("Newtonsoft.Json", currentFramework, logger, CancellationToken.None); //dependencyInfo2.Dump(); Console.WriteLine(); Console.WriteLine("-----------------------------------------------------------------------------"); Console.WriteLine(); Console.WriteLine("Installing for target framework {0}...", currentFramework); string rootPath = "ProjectRoot"; string targetPath = Path.Combine(rootPath, "Packages"); if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } ISettings settings = new CustomNuGetSettings(rootPath); PackageSourceProvider sourceProvider = new PackageSourceProvider(settings); SourceRepositoryProvider repoProvider = new SourceRepositoryProvider(sourceProvider, resourceProviders); CustomNuGetProject project = new CustomNuGetProject(targetPath, currentFramework); CustomSolutionManager solutionManager = new CustomSolutionManager(rootPath, project); NuGetPackageManager manager = new NuGetPackageManager(repoProvider, settings, solutionManager, new CustomDeleteManager()); bool allowPrereleaseVersions = true; bool allowUnlisted = false; ResolutionContext resolutionContext = new ResolutionContext( DependencyBehavior.Lowest, allowPrereleaseVersions, allowUnlisted, VersionConstraints.ExactMajor); UninstallationContext uninstallContext = new UninstallationContext( true, false); INuGetProjectContext projectContext = new CustomNuGetProjectContext(); List <SourceRepository> sourceRepositories = new List <SourceRepository>(); sourceRepositories.Add(sourceRepository); Console.WriteLine("Preview for package install..."); IEnumerable <NuGetProjectAction> installActions = await manager.PreviewInstallPackageAsync( project, new PackageIdentity("Newtonsoft.Json", new NuGetVersion(10, 0, 2)), resolutionContext, projectContext, sourceRepositories, Enumerable.Empty <SourceRepository>(), CancellationToken.None); Console.WriteLine("Execute package install..."); await manager.ExecuteNuGetProjectActionsAsync( project, installActions, projectContext, CancellationToken.None); Console.WriteLine("Preview for package update..."); IEnumerable <NuGetProjectAction> updateActions = await manager.PreviewUpdatePackagesAsync( new PackageIdentity("Newtonsoft.Json", new NuGetVersion(10, 0, 3)), new[] { project }, resolutionContext, projectContext, sourceRepositories, Enumerable.Empty <SourceRepository>(), CancellationToken.None); Console.WriteLine("Execute package update..."); await manager.ExecuteNuGetProjectActionsAsync( project, updateActions, projectContext, CancellationToken.None); Console.WriteLine("Preview for package uninstall..."); IEnumerable <NuGetProjectAction> uninstallActions = await manager.PreviewUninstallPackageAsync( project, new PackageIdentity("Newtonsoft.Json", new NuGetVersion(10, 0, 3)), uninstallContext, projectContext, CancellationToken.None); Console.WriteLine("Execute package uninstall..."); await manager.ExecuteNuGetProjectActionsAsync( project, uninstallActions, projectContext, CancellationToken.None); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Done"); }
public async ValueTask <IReadOnlyList <ProjectAction> > GetUpdateActionsAsync( IReadOnlyCollection <string> projectIds, IReadOnlyCollection <PackageIdentity> packageIdentities, VersionConstraints versionConstraints, bool includePrelease, DependencyBehavior dependencyBehavior, IReadOnlyList <string> packageSourceNames, CancellationToken cancellationToken) { Assumes.NotNullOrEmpty(projectIds); Assumes.NotNullOrEmpty(packageIdentities); Assumes.NotNullOrEmpty(packageSourceNames); Assumes.NotNull(_state.SourceCacheContext); Assumes.NotNull(_state.ResolvedActions); Assumes.Null(_state.PackageIdentity); var primarySources = new List <SourceRepository>(); var secondarySources = new List <SourceRepository>(); ISourceRepositoryProvider sourceRepositoryProvider = await _sharedState.SourceRepositoryProvider.GetValueAsync(cancellationToken); IEnumerable <SourceRepository> sourceRepositories = sourceRepositoryProvider.GetRepositories(); var packageSourceNamesSet = new HashSet <string>(packageSourceNames, StringComparer.OrdinalIgnoreCase); foreach (SourceRepository sourceRepository in sourceRepositories) { if (packageSourceNamesSet.Contains(sourceRepository.PackageSource.Name)) { primarySources.Add(sourceRepository); } if (sourceRepository.PackageSource.IsEnabled) { secondarySources.Add(sourceRepository); } } INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync <INuGetProjectContext>(); var projects = new List <NuGetProject>(); foreach (string projectId in projectIds) { (bool success, NuGetProject? project) = await TryGetNuGetProjectMatchingProjectIdAsync(projectId); Assumes.True(success); Assumes.NotNull(project); projects.Add(project); } var resolutionContext = new ResolutionContext( dependencyBehavior, includePrelease, includeUnlisted: true, versionConstraints, new GatherCache(), _state.SourceCacheContext); NuGetPackageManager packageManager = await _sharedState.PackageManager.GetValueAsync(cancellationToken); IEnumerable <NuGetProjectAction> actions = await packageManager.PreviewUpdatePackagesAsync( packageIdentities.ToList(), projects, resolutionContext, projectContext, primarySources, secondarySources, cancellationToken); var projectActions = new List <ProjectAction>(); foreach (NuGetProjectAction action in actions) { string projectId = action.Project.GetMetadata <string>(NuGetProjectMetadataKeys.ProjectId); var resolvedAction = new ResolvedAction(action.Project, action); var projectAction = new ProjectAction( CreateProjectActionId(), projectId, action.PackageIdentity, action.NuGetProjectActionType, implicitActions: null); _state.ResolvedActions[projectAction.Id] = resolvedAction; projectActions.Add(projectAction); } return(projectActions); }