/// <summary> /// Return the resolve package actions /// </summary> private async Task <IReadOnlyList <ResolvedAction> > GetActionsAsync( INuGetUI uiService, IEnumerable <NuGetProject> targets, UserAction userAction, bool removeDependencies, bool forceRemove, ResolutionContext resolutionContext, INuGetProjectContext projectContext, CancellationToken token) { var results = new List <ResolvedAction>(); Debug.Assert(userAction.PackageId != null, "Package id can never be null in a User action"); if (userAction.Action == NuGetProjectActionType.Install) { foreach (var target in targets) { var actions = await _packageManager.PreviewInstallPackageAsync( target, new PackageIdentity(userAction.PackageId, userAction.Version), resolutionContext, projectContext, uiService.ActiveSources, null, token); results.AddRange(actions.Select(a => new ResolvedAction(target, a))); } } else { var uninstallationContext = new UninstallationContext( removeDependencies: removeDependencies, forceRemove: forceRemove); foreach (var target in targets) { IEnumerable <NuGetProjectAction> actions; actions = await _packageManager.PreviewUninstallPackageAsync( target, userAction.PackageId, uninstallationContext, projectContext, token); results.AddRange(actions.Select(a => new ResolvedAction(target, a))); } } return(results); }
public async Task DoWithProject(string nugetSource, 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(nugetSource); 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 settings = Settings.LoadDefaultSettings(project.ProjectConfig.RootPath, null, null); 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 actions = await packageManager.PreviewInstallPackageAsync(packageManager.PackagesFolderNuGetProject, identity, resolutionContext, projectContext, sourceRepository, sourceRepositoryProvider.GetRepositories(), CancellationToken.None); project.NuGetProjectActions = actions; await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject, identity, resolutionContext, projectContext, sourceRepository, sourceRepositoryProvider.GetRepositories(), CancellationToken.None); NuGetPackageManager.ClearDirectInstall(projectContext); }
public Task <IEnumerable <NuGetProjectAction> > PreviewInstallPackageAsync( NuGetProject nuGetProject, PackageIdentity packageIdentity, ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext, IEnumerable <SourceRepository> primarySources, IEnumerable <SourceRepository> secondarySources, CancellationToken token) { return(packageManager.PreviewInstallPackageAsync( nuGetProject, packageIdentity, resolutionContext, nuGetProjectContext, primarySources, secondarySources, token )); }
protected async Task <IReadOnlyList <ResolvedAction> > GetActionsForInstallAsync(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); foreach (NuGetProject target in targets) { if (!((await target.GetInstalledPackagesAsync(token))?.Any(t => t.PackageIdentity.Id.Equals(packageIdentity.Id, StringComparison.InvariantCultureIgnoreCase) && t.PackageIdentity.Version == packageIdentity.Version) ?? false)) { try { var actions = await _packageManager.PreviewInstallPackageAsync(target, packageIdentity, resolutionContext, projectContext, PrimarySourcesRepository, SecondarySourcesRepository, token); results.AddRange(actions.Select(a => new ResolvedAction(target, a))); } catch (Exception ex) { Debug.WriteLine(ex); throw; } } } return(results); }
/// <summary> /// Устанавливает пакет. /// </summary> /// <param name="packageId">ID пакета.</param> /// <param name="packageVersion">Версия пакета.</param> /// <param name="allowPrerelease">Разрешена ли установка предварительного релиза.</param> /// <returns>Содержимое установленного пакета.</returns> public async Task <PackageContent> InstallPackage(string packageId, string packageVersion = null, bool allowPrerelease = false) { NuGetVersion packageNuGetVersion = null; if (!string.IsNullOrWhiteSpace(packageVersion)) { packageNuGetVersion = NuGetVersion.Parse(packageVersion); } // Конфигурационный файл NuGet.config по умолчанию var settings = new NuGet.Configuration.Settings(_packagesPath, "NuGet.config"); // Фабрика источников пактов на основе конфигурационного файла var packageSourceProvider = new PackageSourceProvider(settings); // Добавление в фабрику источников пакетов дополнительных источников packageSourceProvider.SavePackageSources(_packageSources.Select(i => new PackageSource(i))); // Фабрика хранилищ пакетов на основе фабрики источников пакетов var packageRepositoryProvider = new CachingSourceProvider(packageSourceProvider); // Получение всех хранилищ пакетов на основе указанных источников var packageRepositories = packageRepositoryProvider.GetRepositories().ToList(); // Определение возможности установки prerelease-версии пакетов allowPrerelease = allowPrerelease || (packageNuGetVersion != null && packageNuGetVersion.IsPrerelease); // Создание правил разрешения зависимостей при установке пакета var resolutionContext = new ResolutionContext( dependencyBehavior: DependencyBehavior.Lowest, includePrelease: allowPrerelease, includeUnlisted: true, versionConstraints: VersionConstraints.None); // Если версия пакета не указана, поиск последней версии if (packageNuGetVersion == null) { packageNuGetVersion = await NuGetPackageManager.GetLatestVersionAsync( packageId, NuGetFramework.AnyFramework, resolutionContext, packageRepositories, _logger, CancellationToken.None); if (packageNuGetVersion == null) { throw new InvalidOperationException(string.Format(Properties.Resources.PackageNotFound, packageId)); } } // Уникальный идентификатор версии пакета для установки var packageIdentity = new PackageIdentity(packageId, packageNuGetVersion); // Каталог для установки пакетов (каталог packages) NuGetProject folderProject = new InfinniFolderNuGetProject(_packagesPath); // Менеджер для управления пакетами var packageManager = new NuGetPackageManager(packageRepositoryProvider, settings, _packagesPath); // Правила установки пакетов var projectContext = new NuGetLoggerProjectContext(_logger) { PackageExtractionContext = new PackageExtractionContext { PackageSaveMode = PackageSaveMode.Defaultv3 } }; // Определение порядка действий при установке пакета var installActions = (await packageManager.PreviewInstallPackageAsync( folderProject, packageIdentity, resolutionContext, projectContext, packageRepositories, Enumerable.Empty <SourceRepository>(), CancellationToken.None)).ToList(); // Применение действий по установке пакета await packageManager.ExecuteNuGetProjectActionsAsync( folderProject, installActions, projectContext, CancellationToken.None); return(GetPackageContent(packageIdentity, installActions.Select(i => i.PackageIdentity).ToList())); }
/// <summary> /// Install a NuGet package. Returns all newly installed packages. /// </summary> public async Task <IReadOnlyCollection <InteractivePackage> > InstallPackageAsync( InteractivePackage package, SourceRepository sourceRepository, CancellationToken cancellationToken) { if (package == null) { throw new ArgumentNullException(nameof(package)); } if (!package.Identity.HasVersion) { throw new ArgumentException("PackageIdentity.Version must be set"); } // TODO: File upstream issue about exception if primary source repo is offline. // Shouldn't secondary source repos kick in? Our current work around is to // pass the source repo from search to install, but that's not perfect. sourceRepository = sourceRepository ?? SourceRepositories [0]; project.ResetInstallationContext(); // Just need to apply one fixup here if (PackageIdComparer.Equals(package.Identity.Id, FixedXamarinFormsPackageIdentity.Id) && package.Identity.Version != FixedXamarinFormsPackageIdentity.Version) { Log.Warning( TAG, $"Replacing requested Xamarin.Forms version {package.Identity.Version} with " + $"required version {FixedXamarinFormsPackageIdentity.Version}."); package = package.WithVersion( FixedXamarinFormsPackageIdentity.Version, overwriteRange: true); } if (PackageIdComparer.Equals(package.Identity.Id, IntegrationPackageId)) { Log.Warning(TAG, $"Refusing to add integration NuGet package {IntegrationPackageId}."); return(Array.Empty <InteractivePackage> ()); } var resolutionContext = new ResolutionContext( DependencyBehavior.Lowest, // IDEs only use Highest if upgrading includePrelease: true, includeUnlisted: true, versionConstraints: VersionConstraints.None); // Although there is a single repo associated with the package being installed, // dependency resolution will also look into the secondary sources. In some cases, // this can greatly slow down installation. For the primary case of searching for // packages in nuget.org, prevent the package manager from using secondary sources // for resolution. // // It is important to pass an empty enumerable, because if we pass null, the package // manager will determine secondary sources based on the NuGet configuration. var secondarySources = sourceRepository == SourceRepositories [0] ? Enumerable.Empty <SourceRepository> () : SourceRepositories.Where(r => r != sourceRepository).ToArray(); // There does not appear to be a way to hook into or override functionality of the // NuGetPackageManager or PackageResolver classes. In order to mess with package // resolution, we need to either write a lot of code, proxy the sources, or intercede // via preview installation actions. // // Here we do the latter, though it is not the best general-purpose approach. It works // fine for replacing one single package that we know a LOT about. If that package's // dependencies continually changed, we'd be better off with another approach. var previewInstallActions = await packageManager.PreviewInstallPackageAsync( project, package.Identity, resolutionContext, projectContext, sourceRepository, secondarySources, cancellationToken); var installActions = new List <NuGetProjectAction> (); foreach (var action in previewInstallActions) { // If the installed package has a dependency on Xamarin.Forms, make sure the version // that gets installed is our preferred version. Force it to install from the primary // source repository, because we can't assume that version is available everywhere. // // TODO: Consider adding a search or something to see if we can use the specified source // instead. Could be handy if nuget.org is down or the user is offline and using // a local repo. if (action.PackageIdentity.Id == FixedXamarinFormsPackageIdentity.Id) { installActions.Add(NuGetProjectAction.CreateInstallProjectAction( FixedXamarinFormsPackageIdentity, SourceRepositories [0], action.Project)); } else { installActions.Add(action); } } // We follow the modern behavior of .NET Core and do not actually install packages anywhere. // Instead, we ultimately reference them out of the user's global package cache (by default, // ~/.nuget/packages). Our NuGetProject implementation simply collects package assembly // references (and potentially other necessary files) and populates them back into the // InteractiveInstallationContext. using (var sourceCacheContext = new SourceCacheContext()) await packageManager.ExecuteNuGetProjectActionsAsync( project, installActions, projectContext, sourceCacheContext, cancellationToken); // Identify which packages were not already noted as installed, or have been upgraded now var newlyInstalledPackages = new List <InteractivePackage> (); foreach (var newPackage in project.InstallationContext.InstalledPackages) { InteractivePackage finalNewPackage; var foundInstalledMatch = installedPackages.TryGetValue( newPackage, out finalNewPackage); if (!foundInstalledMatch || newPackage.Identity.Version > finalNewPackage.Identity.Version) { // Make sure we have a reference to a matching explicit InteractivePackage if it // exists, so that we can persist the original SupportedVersionRange if (!foundInstalledMatch) { finalNewPackage = PackageIdComparer.Equals(package, newPackage) ? package : newPackage; } finalNewPackage = newPackage .WithIsExplicit(finalNewPackage.IsExplicit) .WithSupportedVersionRange(finalNewPackage.SupportedVersionRange); newlyInstalledPackages.Add(finalNewPackage); installedPackages = installedPackages .Remove(finalNewPackage) .Add(finalNewPackage); UpdateInstalledPackages(); } } return(newlyInstalledPackages); }
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"); }