예제 #1
0
 /// <summary>
 /// Perform the multi-package update action.
 /// </summary>
 /// <remarks>This needs to be called from a background thread. It may hang on the UI thread.</remarks>
 public async Task PerformUpdateAsync(
     INuGetUI uiService,
     List <PackageIdentity> packagesToUpdate,
     CancellationToken token)
 {
     await PerformActionImplAsync(
         uiService,
         () =>
     {
         return(ResolveActionsForUpdateAsync(
                    uiService,
                    packagesToUpdate,
                    token));
     },
         async (actions) =>
     {
         // Get all Nuget projects and actions and call ExecuteNugetProjectActions once for all the projects.
         var nugetProjects = actions.Select(action => action.Project);
         var nugetActions  = actions.Select(action => action.Action);
         await _packageManager.ExecuteNuGetProjectActionsAsync(
             nugetProjects,
             nugetActions,
             uiService.ProjectContext,
             token);
     },
         NuGetOperationType.Update,
         token);
 }
예제 #2
0
        public async Task UpdatePackageAsync(CancellationToken token)
        {
            using (var sourceCacheContext = new SourceCacheContext()) {
                var actions = await PreviewUpdatePackagesAsync(sourceCacheContext, token);

                await packageManager.ExecuteNuGetProjectActionsAsync(
                    nugetProjects,
                    actions,
                    projectContext,
                    sourceCacheContext,
                    token);
            }
        }
 public Task ExecuteNuGetProjectActionsAsync(
     NuGetProject nuGetProject,
     IEnumerable <NuGetProjectAction> nuGetProjectActions,
     INuGetProjectContext nuGetProjectContext,
     SourceCacheContext sourceCacheContext,
     CancellationToken token)
 {
     return(packageManager.ExecuteNuGetProjectActionsAsync(
                nuGetProject,
                nuGetProjectActions,
                nuGetProjectContext,
                sourceCacheContext,
                token));
 }
예제 #4
0
        public async ValueTask UninstallPackagesAsync(
            string projectId,
            IReadOnlyList <PackageIdentity> packageIdentities,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectId);
            Assumes.NotNullOrEmpty(packageIdentities);

            cancellationToken.ThrowIfCancellationRequested();

            MSBuildNuGetProject project = await GetMsBuildNuGetProjectAsync(projectId, cancellationToken);

            IEnumerable <NuGetProjectAction>?actions = packageIdentities
                                                       .Select(packageIdentity => NuGetProjectAction.CreateUninstallProjectAction(packageIdentity, project));

            NuGetPackageManager packageManager = await _state.GetPackageManagerAsync(cancellationToken);

            Assumes.NotNull(packageManager);

            INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync <INuGetProjectContext>();

            Assumes.NotNull(projectContext);

            await packageManager.ExecuteNuGetProjectActionsAsync(
                project,
                actions,
                projectContext,
                NullSourceCacheContext.Instance,
                CancellationToken.None);
        }
예제 #5
0
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            var packageRoot              = path.MakeAbsolute(_environment).FullPath;
            var targetFramework          = type == PackageType.Addin ? _currentFramework : NuGetFramework.AnyFramework;
            var sourceRepositoryProvider = new NuGetSourceRepositoryProvider(_nugetSettings, _config, package);
            var packageIdentity          = GetPackageId(package, sourceRepositoryProvider, targetFramework, _nugetLogger);

            if (packageIdentity == null)
            {
                return(Array.Empty <IFile>());
            }

            var pathResolver   = new PackagePathResolver(packageRoot);
            var project        = new NugetFolderProject(_fileSystem, _contentResolver, _config, _log, pathResolver, packageRoot, targetFramework);
            var packageManager = new NuGetPackageManager(sourceRepositoryProvider, _nugetSettings, project.Root)
            {
                PackagesFolderNuGetProject = project
            };
            var includePrerelease  = package.IsPrerelease();
            var dependencyBehavior = GetDependencyBehavior(type, package);
            var resolutionContext  = new ResolutionContext(dependencyBehavior, includePrerelease, false, VersionConstraints.None, _gatherCache);
            var projectContext     = new NuGetProjectContext(_log);

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var downloadContext = new PackageDownloadContext(sourceCacheContext);

                // First get the install actions.
                // This will give us the list of packages to install, and which feed should be used.
                var actions = packageManager.GetInstallProjectActionsAsync(
                    project,
                    packageIdentity,
                    resolutionContext,
                    projectContext,
                    sourceRepositoryProvider.GetRepositories(),
                    CancellationToken.None).Result;

                // Then install the packages.
                packageManager.ExecuteNuGetProjectActionsAsync(
                    project,
                    actions,
                    projectContext,
                    downloadContext,
                    CancellationToken.None).Wait();
            }

            return(project.GetFiles(path, package, type));
        }
예제 #6
0
        public async ValueTask ExecuteActionsAsync(IReadOnlyList <ProjectAction> actions, CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(actions);

            cancellationToken.ThrowIfCancellationRequested();

            await CatchAndRethrowExceptionAsync(async() =>
            {
                INuGetProjectContext?projectContext = null;

                try
                {
                    projectContext = await ServiceLocator.GetComponentModelServiceAsync <INuGetProjectContext>();

                    Assumes.NotNull(projectContext);

                    if (IsDirectInstall(actions))
                    {
                        NuGetPackageManager.SetDirectInstall(_state.PackageIdentity, projectContext);
                    }

                    var nugetProjectActions = new List <NuGetProjectAction>();

                    foreach (ProjectAction action in actions)
                    {
                        if (_state.ResolvedActions.TryGetValue(action.Id, out ResolvedAction resolvedAction))
                        {
                            nugetProjectActions.Add(resolvedAction.Action);
                        }
                    }

                    Assumes.NotNullOrEmpty(nugetProjectActions);

                    NuGetPackageManager packageManager  = await _sharedState.GetPackageManagerAsync(cancellationToken);
                    IEnumerable <NuGetProject> projects = nugetProjectActions.Select(action => action.Project);

                    await packageManager.ExecuteNuGetProjectActionsAsync(
                        projects,
                        nugetProjectActions,
                        projectContext,
                        _state.SourceCacheContext,
                        cancellationToken);
                }
                finally
                {
                    if (projectContext != null)
                    {
                        NuGetPackageManager.ClearDirectInstall(projectContext);
                    }
                }
            });
        }
예제 #7
0
        /// <summary>
        /// Perform the multi-package update action.
        /// </summary>
        /// <remarks>This needs to be called from a background thread. It may hang on the UI thread.</remarks>
        public async Task PerformUpdateAsync(
            INuGetUI uiService,
            List <PackageIdentity> packagesToUpdate,
            DependencyObject windowOwner,
            CancellationToken token)
        {
            var stopWatch = new Stopwatch();

            stopWatch.Start();

            await PerformActionImplAsync(
                uiService,
                () =>
            {
                return(ResolveActionsForUpdate(
                           uiService,
                           packagesToUpdate,
                           token));
            },
                async (actions) =>
            {
                foreach (var projectActions in actions.GroupBy(action => action.Project))
                {
                    await _packageManager.ExecuteNuGetProjectActionsAsync(
                        projectActions.Key,
                        projectActions.Select(action => action.Action),
                        uiService.ProgressWindow,
                        token);
                }
            },
                windowOwner,
                token);

            stopWatch.Stop();
            uiService.ProgressWindow.Log(ProjectManagement.MessageLevel.Info, string.Format(CultureInfo.CurrentCulture, Resources.Operation_TotalTime, stopWatch.Elapsed));
        }
예제 #8
0
        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);
        }
예제 #9
0
        /// <summary>
        /// Execute the installs/uninstalls
        /// </summary>
        /// <param name="actions"></param>
        /// <param name="projectContext"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        protected async Task ExecuteActions(IEnumerable <Tuple <NuGetProject, NuGetProjectAction> > actions,
                                            NuGetUIProjectContext projectContext, UserAction userAction, CancellationToken token)
        {
            HashSet <PackageIdentity> processedDirectInstalls = new HashSet <PackageIdentity>(PackageIdentity.Comparer);

            foreach (var projectActions in actions.GroupBy(e => e.Item1))
            {
                var nuGetProjectActions = projectActions.Select(e => e.Item2);
                var directInstall       = GetDirectInstall(nuGetProjectActions, userAction, projectContext.CommonOperations);
                if (directInstall != null && !processedDirectInstalls.Contains(directInstall))
                {
                    NuGetPackageManager.SetDirectInstall(directInstall, projectContext);
                    processedDirectInstalls.Add(directInstall);
                }
                await _packageManager.ExecuteNuGetProjectActionsAsync(projectActions.Key, nuGetProjectActions, projectContext, token);

                NuGetPackageManager.ClearDirectInstall(projectContext);
            }
        }
예제 #10
0
        private async Task ExecuteActionsAsync(IEnumerable <ResolvedAction> actions,
                                               PackageIdentity packageIdentity,
                                               INuGetProjectContext projectContext,
                                               SourceCacheContext sourceCacheContext,
                                               CancellationToken token)
        {
            NuGetProject[] nuGetProjects = actions.Select(action => action.Project).Distinct().ToArray();

            IEnumerable <NuGetProjectAction> nuGetActions = actions.Select(action => action.Action);

            if (packageIdentity != null)
            {
                NuGetPackageManager.SetDirectInstall(packageIdentity, projectContext);
            }

            await _packageManager.ExecuteNuGetProjectActionsAsync(nuGetProjects, nuGetActions, projectContext, sourceCacheContext, token);

            NuGetPackageManager.ClearDirectInstall(projectContext);
        }
예제 #11
0
        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();
        }
예제 #12
0
        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();
        }
예제 #13
0
        /// <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);
        }
예제 #15
0
        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");
        }