コード例 #1
0
        public async override Task ExecuteCommand()
        {
            CalculateEffectivePackageSaveMode();
            string installPath = ResolveInstallPath();

            var packageSourceProvider    = new NuGet.Configuration.PackageSourceProvider(Settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, ResourceProviders);

            IEnumerable <SourceRepository> primarySources;
            IEnumerable <SourceRepository> secondarySources;

            GetEffectiveSources(sourceRepositoryProvider, out primarySources, out secondarySources);

            if (Arguments.Count == 0)
            {
                throw new InvalidOperationException(NuGetResources.InstallCommandPackageIdMustBeProvided);
            }
            string packageId = Arguments[0];
            NuGetPackageManager packageManager    = new NuGetPackageManager(sourceRepositoryProvider, installPath);
            ResolutionContext   resolutionContext = new ResolutionContext(dependencyBehavior: DependencyBehavior, includePrelease: Prerelease);
            FolderNuGetProject  nugetProject      = new FolderNuGetProject(installPath);

            nugetProject.PackageSaveMode = EffectivePackageSaveMode;

            if (Version == null)
            {
                await packageManager.InstallPackageAsync(nugetProject, packageId, resolutionContext, new Common.Console(),
                                                         primarySources, secondarySources, CancellationToken.None);
            }
            else
            {
                await packageManager.InstallPackageAsync(nugetProject, new PackageIdentity(packageId, new NuGetVersion(Version)), resolutionContext,
                                                         new Common.Console(), primarySources, secondarySources, CancellationToken.None);
            }
        }
コード例 #2
0
        /// <summary>
        /// Core install method. All installs from the VS API and template wizard end up here.
        /// This does not check for already installed packages
        /// </summary>
        internal async Task InstallInternalCoreAsync(
            NuGetPackageManager packageManager,
            GatherCache gatherCache,
            NuGetProject nuGetProject,
            PackageIdentity package,
            IEnumerable <SourceRepository> sources,
            VSAPIProjectContext projectContext,
            bool includePrerelease,
            bool ignoreDependencies,
            CancellationToken token)
        {
            await TaskScheduler.Default;

            DependencyBehavior depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest;

            ResolutionContext resolution = new ResolutionContext(
                depBehavior,
                includePrerelease,
                includeUnlisted: false,
                versionConstraints: VersionConstraints.None,
                gatherCache: gatherCache);

            // install the package
            if (package.Version == null)
            {
                await packageManager.InstallPackageAsync(nuGetProject, package.Id, resolution, projectContext, sources, Enumerable.Empty <SourceRepository>(), token);
            }
            else
            {
                await packageManager.InstallPackageAsync(nuGetProject, package, resolution, projectContext, sources, Enumerable.Empty <SourceRepository>(), token);
            }
        }
コード例 #3
0
        public async Task TestPackageRestoredEvent()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
            {
                var projectA = testSolutionManager.AddNewMSBuildProject();
                var projectB = testSolutionManager.AddNewMSBuildProject();

                var packageIdentity          = Packages[0];
                var testNuGetProjectContext  = new TestNuGetProjectContext();
                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                var testSettings             = Configuration.NullSettings.Instance;
                var resolutionContext        = new ResolutionContext();
                var token = CancellationToken.None;

                var deleteOnRestartManager = new TestDeleteOnRestartManager();
                var nuGetPackageManager    = new NuGetPackageManager(
                    sourceRepositoryProvider,
                    testSettings,
                    testSolutionManager,
                    deleteOnRestartManager);

                await nuGetPackageManager.InstallPackageAsync(projectA, packageIdentity,
                                                              resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                await nuGetPackageManager.InstallPackageAsync(projectB, packageIdentity,
                                                              resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                var packageRestoreManager = new PackageRestoreManager(
                    sourceRepositoryProvider,
                    testSettings,
                    testSolutionManager);
                var restoredPackages = new List <PackageIdentity>();
                packageRestoreManager.PackageRestoredEvent += delegate(object sender, PackageRestoredEventArgs args)
                {
                    if (args.Restored)
                    {
                        restoredPackages.Add(args.Package);
                    }
                };

                Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(packageIdentity));

                // Delete packages folder
                TestFileSystemUtility.DeleteRandomTestFolder(Path.Combine(testSolutionManager.SolutionDirectory, "packages"));

                Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));

                // Act
                await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(testSolutionManager.SolutionDirectory,
                                                                                  testNuGetProjectContext,
                                                                                  new TestLogger(),
                                                                                  CancellationToken.None);

                Assert.Equal(1, restoredPackages.Count);
                Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));
            }
        }
コード例 #4
0
        public async void installPackagesFromProvidedAppSettingsFileAsync()
        {
            var serachResult = await _packageSearcher.GetSinglePackageMetaDataAsync();

            var                       identity = serachResult.Identity;
            var                       rootPath = @"myPathToTheFolder";
            ISettings                 settings = Settings.LoadDefaultSettings(rootPath, null, new MachineWideSettings());
            PackageSourceProvider     packageSourceProvider    = new PackageSourceProvider(settings);
            ISourceRepositoryProvider sourceRepositoryProvider =
                new SourceRepositoryProvider(packageSourceProvider, GetV3AndV2Providers());
            var    project      = new FolderNuGetProject(rootPath);
            string packagesPath = "...";
            NuGetPackageManager packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, packagesPath)
            {
                PackagesFolderNuGetProject = project
            };

            bool allowPrereleaseVersions = true;
            bool allowUnlisted           = false;

            ResolutionContext resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest, allowPrereleaseVersions, allowUnlisted, VersionConstraints.None);
            INuGetProjectContext projectContext = new DefaultProjectContext();

            IEnumerable <SourceRepository> sourceRepositories = Enumerable.Repeat(_packageSearcher.GetSourceRepository(), 1);
            await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                     identity, resolutionContext, projectContext, sourceRepositories,
                                                     Array.Empty <SourceRepository>(),
                                                     CancellationToken.None);
        }
コード例 #5
0
        public async Task Install(IReadOnlyList <SourceRepository> remoteRepositories, InstalledPackagesCache installedPackages, NuGetPackageManager packageManager)
        {
            if (_versionMatch == null)
            {
                return;
            }
            IReadOnlyList <SourceRepository> sourceRepositories = GetSourceRepositories(remoteRepositories);

            using (Trace.WithIndent().Verbose($"Installing package {_packageId} {_versionMatch.ToNormalizedString()}"))
            {
                // Check if this package was already installed in a previous run
                PackageIdentity packageIdentity = new PackageIdentity(_packageId, _versionMatch);
                if (installedPackages.VerifyPackage(packageIdentity, packageManager))
                {
                    Trace.Verbose($"Package {_packageId} {_versionMatch.ToNormalizedString()} was already installed");
                    return;
                }

                // If not, go ahead and install it
                using (installedPackages.AddPackage(packageIdentity, _currentFramework))
                {
                    ResolutionContext resolutionContext = new ResolutionContext(
                        DependencyBehavior.Lowest, _allowPrereleaseVersions, _allowUnlisted, VersionConstraints.None);
                    INuGetProjectContext projectContext = new NuGetProjectContext();
                    await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                             packageIdentity, resolutionContext, projectContext,
                                                             sourceRepositories, Array.Empty <SourceRepository>(), CancellationToken.None);

                    Trace.Verbose($"Installed package {_packageId} {_versionMatch.ToNormalizedString()}");
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Installs application package.
        /// </summary>
        /// <remarks>
        /// На текущий момент это вся документация по использованию библиотек Nuget:
        ///  https://daveaglick.com/posts/exploring-the-nuget-v3-libraries-part-1
        ///  https://daveaglick.com/posts/exploring-the-nuget-v3-libraries-part-2
        ///  https://daveaglick.com/posts/exploring-the-nuget-v3-libraries-part-3
        /// </remarks>
        /// <returns></returns>
        public async Task Install(AppInfo appInfo)
        {
            var sourceRepository         = new SourceRepository(_nugetSettings.PackageSource.Value, _nugetSettings.ResourceProviders);
            var sourceRepositoryProvider = new SourceRepositoryProvider(_nugetSettings.Configuration.Value, _nugetSettings.ResourceProviders);
            var project = new FolderNuGetProject(_appSettings.InstallDirectoryPath);

            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, _nugetSettings.Configuration.Value, PackagesFolderPath)
            {
                PackagesFolderNuGetProject = project
            };

            var resolutionContext        = new ResolutionContext(DependencyBehavior.Lowest, true, false, VersionConstraints.None);
            var emptyNuGetProjectContext = new EmptyNuGetProjectContext();
            var sourceRepositories       = Array.Empty <SourceRepository>();

            await nuGetPackageManager.InstallPackageAsync(project, new PackageIdentity(appInfo.PackageId, NuGetVersion.Parse(appInfo.Version)), resolutionContext, emptyNuGetProjectContext, sourceRepository, sourceRepositories, CancellationToken.None);

            if (appInfo.HasInstance())
            {
                var directoryName            = Path.Combine(_appSettings.InstallDirectoryPath, $"{appInfo.PackageId}.{appInfo.Version}");
                var directoryForInstanceName = Path.Combine(_appSettings.InstallDirectoryPath, appInfo.ToString());

                var directoryInfo = new DirectoryInfo(directoryName);

                if (directoryInfo.Exists && !Directory.Exists(directoryForInstanceName))
                {
                    directoryInfo.MoveTo(directoryForInstanceName);
                }
            }
        }
コード例 #7
0
ファイル: NugetService.cs プロジェクト: anthrax3/subroute.io
        /// <summary>
        /// Downloads and extracts the specified dependency to the NuGet package folder.
        /// </summary>
        /// <param name="dependency">Dependency indicating the specific Id and Version of the package to download.</param>
        public async Task DownloadPackageAsync(Dependency dependency)
        {
            // Use V3 providers to get an instance of the NuGetPackageManager. We'll use
            // defaults for everything as we are doing a simple package download to a folder.
            var identity       = dependency.ToPackageIdentity();
            var settings       = NuGet.Configuration.Settings.LoadDefaultSettings(Settings.NugetPackageDirectory);
            var cores          = Repository.Provider.GetPageableCoreV3().Select(p => new Lazy <INuGetResourceProvider>(() => p));
            var provider       = new SourceRepositoryProvider(settings, cores);
            var packageManager = new NuGetPackageManager(provider, settings, Settings.NugetPackageDirectory)
            {
                PackagesFolderNuGetProject = _packageFolder
            };

            // When the package already exists in the package folder, there is nothing to do.
            if (packageManager.PackageExistsInPackagesFolder(identity))
            {
                return;
            }

            // We'll create an instance of ResolutionContext using the standard resolution behavior.
            var resolutionContext  = new ResolutionContext(NuGet.Resolver.DependencyBehavior.Lowest, true, true, VersionConstraints.None);
            var projectContext     = new NuGetProjectContext();
            var sourceRepositories = provider.GetRepositories();

            // Use the package manager to download an install the specified dependencies.
            await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                     identity, resolutionContext, projectContext, sourceRepositories,
                                                     Array.Empty <SourceRepository>(),
                                                     CancellationToken.None);
        }
コード例 #8
0
        public static async Task InstallPackage(string packageId, string version, ILogger logger = null, int chmodFileMode = DefaultFilePermissions)
        {
            if (logger == null)
            {
                logger = new ConsoleNuGetLogger(IoC.Get <IConsole>());
            }

            PackageIdentity identity = new PackageIdentity(packageId, new NuGet.Versioning.NuGetVersion(version));

            var settings = NuGet.Configuration.Settings.LoadDefaultSettings(Platform.ReposDirectory, null, new MachineWideSettings(), false, true);

            ISourceRepositoryProvider sourceRepositoryProvider = new SourceRepositoryProvider(settings, s_providers);  // See part 2

            using (var installedPackageCache = GetCache())
            {
                var project = new AvalonStudioExtensionsFolderProject(GetFramework(), installedPackageCache, Platform.ReposDirectory);

                if (!project.PackageExists(identity))
                {
                    var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, Platform.ReposDirectory)
                    {
                        PackagesFolderNuGetProject = project,
                    };

                    bool allowPrereleaseVersions = true;
                    bool allowUnlisted           = false;

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

                    INuGetProjectContext projectContext = new ProjectContext(logger);

                    await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                             identity, resolutionContext, projectContext, s_sourceRepositories,
                                                             Array.Empty <SourceRepository>(), // This is a list of secondary source respositories, probably empty
                                                             CancellationToken.None);

                    var packageDir = GetPackageDirectory(identity);

                    var files = Directory.EnumerateFiles(packageDir, "*.*", SearchOption.AllDirectories);

                    if (Platform.PlatformIdentifier != Platforms.PlatformID.Win32NT)
                    {
                        logger.LogInformation("Applying file attributes.");

                        foreach (var file in files)
                        {
                            Platform.Chmod(file, chmodFileMode);
                        }
                    }

                    await LoadAssetsFromFilesAsync(packageId, version, files);
                }
                else
                {
                    logger.LogInformation("Package is already installed.");
                }
            }
        }
コード例 #9
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);

            sourceRepositoryProvider.CreateRepository(packageRoot);
            var packageIdentity = GetPackageId(package, sourceRepositoryProvider, targetFramework, _nugetLogger);

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

            if (!_projects.TryGetValue(type, out var project))
            {
                var pathResolver = new PackagePathResolver(packageRoot);
                project = new NugetFolderProject(_fileSystem, _contentResolver, _config, _log, pathResolver, packageRoot, targetFramework);
                _projects.Add(type, project);

                if (!project.Root.Equals(packageRoot))
                {
                    // This should not happen since all addins/tools are installed to same directory.
                    throw new ArgumentException($"Path is not same as previous package of type: {type}", nameof(path));
                }
            }
            var packageManager = new NuGetPackageManager(sourceRepositoryProvider, _nugetSettings, project.Root)
            {
                PackagesFolderNuGetProject = project
            };

            var sourceRepositories = sourceRepositoryProvider.GetRepositories();
            var includePrerelease  = false;

            if (package.Parameters.ContainsKey("prerelease"))
            {
                bool.TryParse(package.Parameters["prerelease"].FirstOrDefault() ?? bool.TrueString, out includePrerelease);
            }
            var resolutionContext = new ResolutionContext(DependencyBehavior.Lowest, includePrerelease, false, VersionConstraints.None, project.GatherCache);
            var projectContext    = new NuGetProjectContext(_log);

            packageManager.InstallPackageAsync(project, packageIdentity, resolutionContext, projectContext,
                                               sourceRepositories, Array.Empty <SourceRepository>(),
                                               CancellationToken.None).Wait();

            return(project.GetFiles(path, package, type));
        }
コード例 #10
0
        /// <summary>
        /// Core install method. All installs from the VS API and template wizard end up here.
        /// </summary>
        internal async Task InstallInternal(Project project, List <PackageIdentity> packages, ISourceRepositoryProvider repoProvider, VSAPIProjectContext projectContext, bool ignoreDependencies, CancellationToken token)
        {
            // store expanded node state
            IDictionary <string, ISet <VsHierarchyItem> > expandedNodes = VsHierarchyHelper.GetAllExpandedNodes(_solutionManager);

            try
            {
                DependencyBehavior depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest;

                bool includePrerelease = false;

                ResolutionContext resolution = new ResolutionContext(depBehavior, includePrerelease, false);

                NuGetPackageManager packageManager = new NuGetPackageManager(repoProvider, _settings, _solutionManager);

                // find the project
                NuGetProject nuGetProject = PackageManagementHelpers.GetProject(_solutionManager, project, projectContext);

                // install the package
                foreach (PackageIdentity package in packages)
                {
                    if (package.Version == null)
                    {
                        if (!_packageServices.IsPackageInstalled(project, package.Id))
                        {
                            await packageManager.InstallPackageAsync(nuGetProject, package.Id, resolution, projectContext, repoProvider.GetRepositories(), Enumerable.Empty <SourceRepository>(), token);
                        }
                    }
                    else
                    {
                        if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToString()))
                        {
                            await packageManager.InstallPackageAsync(nuGetProject, package, resolution, projectContext, repoProvider.GetRepositories(), Enumerable.Empty <SourceRepository>(), token);
                        }
                    }
                }
            }
            finally
            {
                // collapse nodes
                VsHierarchyHelper.CollapseAllNodes(_solutionManager, expandedNodes);
            }
        }
コード例 #11
0
        public async Task InstallingPackageShouldCreateLockFile_CustomLockFileName()
        {
            // Arrange
            using (var packageSource = TestDirectory.Create())
                using (var testSolutionManager = new TestSolutionManager())
                {
                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(
                        new List <PackageSource>()
                    {
                        new PackageSource(packageSource.Path)
                    });

                    var testSettings           = NullSettings.Instance;
                    var token                  = CancellationToken.None;
                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);
                    var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

                    var packageContext = new SimpleTestPackageContext("packageA");
                    packageContext.AddFile("lib/net45/a.dll");
                    SimpleTestPackageUtility.CreateOPCPackage(packageContext, packageSource);

                    var msBuildNuGetProject       = testSolutionManager.AddNewMSBuildProject();
                    var msBuildNuGetProjectSystem = msBuildNuGetProject.ProjectSystem as TestMSBuildNuGetProjectSystem;
                    msBuildNuGetProjectSystem.SetPropertyValue("RestorePackagesWithLockFile", "true");
                    msBuildNuGetProjectSystem.SetPropertyValue("NuGetLockFilePath", "my.lock.json");
                    var packagesConfigPath = msBuildNuGetProject.PackagesConfigNuGetProject.FullPath;
                    var packagesLockPath   = packagesConfigPath.Replace("packages.config", "my.lock.json");
                    var packageIdentity    = packageContext.Identity;

                    // Pre-Assert
                    // Check that the packages.lock.json file does not exist
                    Assert.False(File.Exists(packagesLockPath));

                    // Act
                    await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                                                                  new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                    // Assert
                    // Check that the packages.lock.json file exists after the installation
                    Assert.True(File.Exists(packagesLockPath));
                    Assert.True(msBuildNuGetProjectSystem.FileExistsInProject("my.lock.json"));
                    // Check the number of target frameworks and dependencies in the lock file
                    var lockFile = PackagesLockFileFormat.Read(packagesLockPath);
                    Assert.Equal(1, lockFile.Targets.Count);
                    Assert.Equal(1, lockFile.Targets[0].Dependencies.Count);
                }
        }
コード例 #12
0
        public async Task Do(string package, string version, string rootPath, string mainFile, bool skipSha256)
        {
            if (rootPath == null)
            {
                rootPath = Directory.GetCurrentDirectory();
            }

            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(rootPath, null, new MachineWideSettings());
            var project  = new ProjectBazel(rootPath, mainFile, skipSha256);
            var sourceRepositoryProvider = new SourceRepositoryProvider(settings, providers);
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, settings, rootPath)
            {
                PackagesFolderNuGetProject = project
            };

            const bool allowPrereleaseVersions = false;
            const bool allowUnlisted           = false;
            var        resolutionContext       = new ResolutionContext(
                DependencyBehavior.HighestMinor, allowPrereleaseVersions, allowUnlisted, VersionConstraints.None);

            var projectContext = new ProjectContext();

            var actions = await packageManager.PreviewInstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                                          identity, resolutionContext, projectContext, sourceRepository,
                                                                          Array.Empty <SourceRepository>(), // This is a list of secondary source respositories, probably empty
                                                                          CancellationToken.None);

            project.NuGetProjectActions = actions;

            await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                     identity, resolutionContext, projectContext, sourceRepository,
                                                     Array.Empty <SourceRepository>(), // This is a list of secondary source respositories, probably empty
                                                     CancellationToken.None);

            NuGetPackageManager.ClearDirectInstall(projectContext);
        }
コード例 #13
0
        public async Task TestRestoreMissingPackages()
        {
            // Arrange
            var testSolutionManager = new TestSolutionManager();
            var projectA            = testSolutionManager.AddNewMSBuildProject();
            var projectB            = testSolutionManager.AddNewMSBuildProject();

            var packageIdentity          = Packages[0];
            var testNuGetProjectContext  = new TestNuGetProjectContext();
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSettings             = NullSettings.Instance;
            var resolutionContext        = new ResolutionContext();
            var token = CancellationToken.None;

            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);

            await nuGetPackageManager.InstallPackageAsync(projectA, packageIdentity,
                                                          resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            await nuGetPackageManager.InstallPackageAsync(projectB, packageIdentity,
                                                          resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            var packageRestoreManager = new PackageRestoreManager(sourceRepositoryProvider, testSettings, testSolutionManager);

            Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(packageIdentity));

            // Delete packages folder
            Directory.Delete(Path.Combine(testSolutionManager.SolutionDirectory, "packages"), recursive: true);

            Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));

            // Act
            await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(CancellationToken.None);

            Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));
        }
コード例 #14
0
        public async Task UnzippedPackageInstall_Basic()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();

            using (var testSolutionManager = new TestSolutionManager(true))
                using (var randomPackagesConfigFolderPath = TestDirectory.Create())
                {
                    var testSettings           = new Configuration.NullSettings();
                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);

                    var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

                    var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
                    var token = CancellationToken.None;

                    var projectTargetFramework    = NuGetFramework.Parse("net45");
                    var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
                    var msBuildNuGetProject       = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigFolderPath);
                    var packageIdentity           = NoDependencyLibPackages[0];

                    // Pre-Assert
                    // Check that the packages.config file does not exist
                    Assert.False(File.Exists(randomPackagesConfigPath));
                    // Check that there are no packages returned by PackagesConfigProject
                    var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
                    Assert.Equal(0, packagesInPackagesConfig.Count);
                    Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

                    // Act
                    await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                                                                  new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                    // Assert
                    // Check that the packages.config file exists after the installation
                    Assert.True(File.Exists(randomPackagesConfigPath));
                    // Check the number of packages and packages returned by PackagesConfigProject after the installation
                    packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
                    Assert.Equal(1, packagesInPackagesConfig.Count);
                    Assert.Equal(packageIdentity, packagesInPackagesConfig[0].PackageIdentity);
                    Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
                }
        }
コード例 #15
0
        public async Task DoNotCreateLockFileWhenFeatureDisabled()
        {
            // Arrange
            using (var packageSource = TestDirectory.Create())
                using (var testSolutionManager = new TestSolutionManager())
                {
                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(
                        new List <PackageSource>()
                    {
                        new PackageSource(packageSource.Path)
                    });

                    var testSettings           = NullSettings.Instance;
                    var token                  = CancellationToken.None;
                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);
                    var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

                    var packageContext = new SimpleTestPackageContext("packageA");
                    packageContext.AddFile("lib/net45/a.dll");
                    SimpleTestPackageUtility.CreateOPCPackage(packageContext, packageSource);

                    var msBuildNuGetProject       = testSolutionManager.AddNewMSBuildProject();
                    var msBuildNuGetProjectSystem = msBuildNuGetProject.ProjectSystem as TestMSBuildNuGetProjectSystem;
                    msBuildNuGetProjectSystem.SetPropertyValue("RestorePackagesWithLockFile", "false");
                    var packagesConfigPath = msBuildNuGetProject.PackagesConfigNuGetProject.FullPath;
                    var packagesLockPath   = packagesConfigPath.Replace("packages.config", "packages.lock.json");
                    var packageIdentity    = packageContext.Identity;

                    // Pre-Assert
                    // Check that the packages.lock.json file does not exist
                    Assert.False(File.Exists(packagesLockPath));

                    // Act
                    await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                                                                  new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                    // Assert
                    // Check that the packages.lock.json still does not exist after the installation
                    Assert.False(File.Exists(packagesLockPath));
                }
        }
コード例 #16
0
        public async Task Install(IReadOnlyList <SourceRepository> remoteRepositories, NuGetPackageManager packageManager)
        {
            if (_versionMatch == null)
            {
                return;
            }
            IReadOnlyList <SourceRepository> sourceRepositories = GetSourceRepositories(remoteRepositories);

            Trace.Verbose($"Installing package {_packageId} {_versionMatch.Version}");
            ResolutionContext resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest, _allowPrereleaseVersions, _allowUnlisted, VersionConstraints.None);
            INuGetProjectContext projectContext = new NuGetProjectContext();
            await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                     new PackageIdentity(_packageId, _versionMatch), resolutionContext, projectContext, sourceRepositories,
                                                     Array.Empty <SourceRepository>(), CancellationToken.None);

            Trace.Verbose($"Installed package {_packageId} {_versionMatch.Version}");
        }
コード例 #17
0
ファイル: AddCommand.cs プロジェクト: samhowes/rules_dotnet
        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);
        }
コード例 #18
0
        public async Task InstallAsync(string packageId, string source)
        {
            ResolutionContext       resolutionContext;
            List <SourceRepository> sourceRepositorySet;

            resolutionContext   = new ResolutionContext(DependencyBehavior.Lowest, includePrelease: true, includeUnlisted: false, VersionConstraints.None);
            sourceRepositorySet = this.PackageSourceSet.Select(packageSource => _sourceRepositoryProvider.CreateRepository(new PackageSource(packageSource.Source))).ToList();

            await _packageManager.InstallPackageAsync(
                _project,
                packageId,
                resolutionContext,
                _projectContext,
                sourceRepositorySet,
                null,
                CancellationToken.None);

            this.OnInstalledPackagesChanged();
        }
コード例 #19
0
        private static async Task InstallPackage(PackageIdentity packageIdentity, string packageRoot, NuGetFramework framework)
        {
            var packagesPath             = Path.Combine(packageRoot, "packages");
            var settings                 = Settings.LoadDefaultSettings(packageRoot, null, new XPlatMachineWideSetting());
            var sourceRepositoryProvider = new SourceRepositoryProvider(settings);
            var folder         = new FolderNuGetProject(packageRoot, new PackagePathResolver(packageRoot), framework ?? FrameworkConstants.CommonFrameworks.NetStandard20);
            var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, packagesPath)
            {
                PackagesFolderNuGetProject = folder
            };

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrelease: false,
                includeUnlisted: false,
                VersionConstraints.None);
            var projectContext = new NuGetProjectContext(settings);

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetryAsync(
                5,
                retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                (exception, _, __) =>
            {
                Log.Warning(
                    "An exception was thrown whilst retrieving or installing {0}: {1}",
                    packageIdentity,
                    exception);
            });

            await retryPolicy.ExecuteAsync(async() =>
            {
                await packageManager.InstallPackageAsync(
                    packageManager.PackagesFolderNuGetProject,
                    packageIdentity,
                    resolutionContext,
                    projectContext,
                    sourceRepositoryProvider.GetDefaultRepositories(),
                    Array.Empty <SourceRepository>(),
                    CancellationToken.None).ConfigureAwait(false);
            }).ConfigureAwait(false);
        }
コード例 #20
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 sourceRepositoryProvider = new NuGetSourceRepositoryProvider(_nugetSettings, _config, package);
            var packageIdentity          = GetPackageId(package, sourceRepositoryProvider);

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

            var packageRoot    = path.MakeAbsolute(_environment).FullPath;
            var pathResolver   = new PackagePathResolver(packageRoot);
            var nuGetProject   = new NugetFolderProject(_fileSystem, _contentResolver, _config, _log, pathResolver, packageRoot);
            var packageManager = new NuGetPackageManager(sourceRepositoryProvider, _nugetSettings, packageRoot)
            {
                PackagesFolderNuGetProject = nuGetProject
            };

            var sourceRepositories = sourceRepositoryProvider.GetRepositories();
            var includePrerelease  = false;

            if (package.Parameters.ContainsKey("prerelease"))
            {
                bool.TryParse(package.Parameters["prerelease"].FirstOrDefault() ?? bool.TrueString, out includePrerelease);
            }
            var resolutionContext = new ResolutionContext(DependencyBehavior.Lowest, includePrerelease, false, VersionConstraints.None);
            var projectContext    = new NuGetProjectContext(_log);

            packageManager.InstallPackageAsync(nuGetProject, packageIdentity, resolutionContext, projectContext,
                                               sourceRepositories, Array.Empty <SourceRepository>(),
                                               CancellationToken.None).Wait();

            return(nuGetProject.GetFiles(path, package, type));
        }
コード例 #21
0
ファイル: Restorer.cs プロジェクト: HavenDV/H.Dependencies
        public static async Task <PackageIdentity> RestoreAsync(
            string folder,
            string packageName,
            string?version = default,
            CancellationToken cancellationToken = default)
        {
            Directory.CreateDirectory(folder);

            var providers = new List <Lazy <INuGetResourceProvider> >();

            providers.AddRange(Repository.Provider.GetCoreV3());

            var packageSource    = new PackageSource("https://api.nuget.org/v3/index.json");
            var sourceRepository = new SourceRepository(packageSource, providers);

            var settings = Settings.LoadDefaultSettings(folder);
            var packageSourceProvider    = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);

            var identity = await NuGetUtilities.GetIdentityAsync(sourceRepository, packageName, version, cancellationToken);

            var project        = new FolderNuGetProject(folder);
            var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, folder)
            {
                PackagesFolderNuGetProject = project
            };
            await packageManager.InstallPackageAsync(
                project,
                identity,
                new ResolutionContext(
                    DependencyBehavior.Ignore,
                    true,
                    true,
                    VersionConstraints.None),
                new EmptyNuGetProjectContext(),
                sourceRepository,
                new List <SourceRepository>(),
                cancellationToken);

            return(identity);
        }
コード例 #22
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);

            sourceRepositoryProvider.CreateRepository(packageRoot);
            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 sourceRepositories = sourceRepositoryProvider.GetRepositories();
            var includePrerelease  = package.IsPrerelease();
            var dependencyBehavior = GetDependencyBehavior(type, package);
            var resolutionContext  = new ResolutionContext(dependencyBehavior, includePrerelease, false, VersionConstraints.None, _gatherCache);
            var projectContext     = new NuGetProjectContext(_log);

            packageManager.InstallPackageAsync(project, packageIdentity, resolutionContext, projectContext,
                                               sourceRepositories, Array.Empty <SourceRepository>(),
                                               CancellationToken.None).Wait();

            return(project.GetFiles(path, package, type));
        }
コード例 #23
0
        /// <summary>
        /// Downloads and extracts the absolute latest pre-release version of a nuget package
        /// </summary>
        /// <param name="packageName">nuget package name</param>
        /// <returns>The directory where the downloaded assembly is extracted</returns>
        internal DirectoryInfo DownloadAndExtractPackage(string packageName)
        {
            // find the absolute latest pre-release version of the given package
            PackageIdentity latestPackage = _searchResource.SearchAsync(packageName, _searchFilter, 0, 1, _logger, CancellationToken.None).Result.First().Identity;

            // install the package
            _packageManager.InstallPackageAsync(_project, latestPackage, _resolutionContext, _projectContext, _sourceRepository, _secondarySources, CancellationToken.None).GetAwaiter().GetResult();
            // find the lib subdirectory in the extracted package
            DirectoryInfo extractedFilesDirectory = new DirectoryInfo(Path.Combine(_project.Root, latestPackage.ToString(), "lib"));

            if (extractedFilesDirectory.Exists)
            {
                // is below the "lib" subdirectory another subdirectory? (only one!)
                DirectoryInfo[] subDirectories = extractedFilesDirectory.GetDirectories();
                // then the extracted assemblies are in this subdirectory; otherwise the assemblies are in the "lib" subdirectory
                return((subDirectories != null && subDirectories.Length == 1) ? subDirectories[0] : extractedFilesDirectory);
            }
            else
            {
                // "lib" subdirectory not found
                return(null);
            }
        }
コード例 #24
0
        public async Task <string[]> DownloadAsync(IPackageSearchMetadata packageIdentity, SourceRepository repository,
                                                   string downloadFolder, bool onlyDownload = false)
        {
            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

            var providers                = GetNugetResourceProviders();
            var settings                 = Settings.LoadDefaultSettings(downloadFolder, null, new MachineWideSettings());
            var packageSourceProvider    = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);

            var dotNetFramework = Assembly
                                  .GetEntryAssembly()
                                  .GetCustomAttribute <TargetFrameworkAttribute>()?
                                  .FrameworkName;

            var frameworkNameProvider = new FrameworkNameProvider(
                new[] { DefaultFrameworkMappings.Instance },
                new[] { DefaultPortableFrameworkMappings.Instance });

            var nuGetFramework = NuGetFramework.ParseFrameworkName(dotNetFramework, frameworkNameProvider);

            var project = new PluginFolderNugetProject(downloadFolder, packageIdentity, nuGetFramework, onlyDownload);

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

            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, _logger);

            var projectContext = new FolderProjectContext(_logger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    clientPolicyContext,
                    _logger)
            };

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                true,
                includeUnlisted: false,
                VersionConstraints.None);

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

            await packageManager.InstallPackageAsync(
                project,
                packageIdentity.Identity,
                resolutionContext,
                projectContext,
                downloadContext,
                repository,
                new List <SourceRepository>(),
                CancellationToken.None);

            var versionFolder = Path.Combine(downloadFolder, packageIdentity.Identity.ToString());

            return(Directory.GetFiles(versionFolder, "*.*", SearchOption.AllDirectories));
        }
コード例 #25
0
ファイル: InstallCommand.cs プロジェクト: An575/NuGet.Client
        private async Task InstallPackage(
            string packageId,
            NuGetVersion version,
            string installPath)
        {
            if (version == null)
            {
                NoCache = true;
            }

            var folderProject = new FolderNuGetProject(
                installPath,
                new PackagePathResolver(installPath, !ExcludeVersion));

            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath);

            var packageSources = GetPackageSources(Settings);

            Console.PrintPackageSources(packageSources);

            var primaryRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);

            var allowPrerelease = Prerelease || (version != null && version.IsPrerelease);

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrelease: allowPrerelease,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            if (version == null)
            {
                // Find the latest version using NuGetPackageManager
                version = await NuGetPackageManager.GetLatestVersionAsync(
                    packageId,
                    folderProject,
                    resolutionContext,
                    primaryRepositories,
                    Console,
                    CancellationToken.None);

                if (version == null)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("InstallCommandUnableToFindPackage"),
                        packageId);

                    throw new CommandLineException(message);
                }
            }

            var packageIdentity = new PackageIdentity(packageId, version);

            if (folderProject.PackageExists(packageIdentity))
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandPackageAlreadyExists"),
                    packageIdentity);

                Console.LogMinimal(message);
            }
            else
            {
                var projectContext = new ConsoleProjectContext(Console)
                {
                    PackageExtractionContext = new PackageExtractionContext(Console)
                };

                if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
                {
                    projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
                }

                await packageManager.InstallPackageAsync(
                    folderProject,
                    packageIdentity,
                    resolutionContext,
                    projectContext,
                    primaryRepositories,
                    Enumerable.Empty <SourceRepository>(),
                    CancellationToken.None);
            }
        }
コード例 #26
0
        public async Task Test_PackageRestoreFailure_WithRaisedEvents()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
                using (var randomTestPackageSourcePath = TestFileSystemUtility.CreateRandomTestFolder())
                {
                    var projectA = testSolutionManager.AddNewMSBuildProject("projectA");
                    var projectB = testSolutionManager.AddNewMSBuildProject("projectB");
                    var projectC = testSolutionManager.AddNewMSBuildProject("projectC");

                    var jQuery144                = Packages[0];
                    var jQueryValidation         = Packages[2];
                    var testNuGetProjectContext  = new TestNuGetProjectContext();
                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                    var testSettings             = Configuration.NullSettings.Instance;
                    var resolutionContext        = new ResolutionContext();
                    var token = CancellationToken.None;

                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);

                    await nuGetPackageManager.InstallPackageAsync(projectA, jQueryValidation,
                                                                  resolutionContext, testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

                    await nuGetPackageManager.InstallPackageAsync(projectB, jQueryValidation,
                                                                  resolutionContext, testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

                    var testPackage1 = new PackageIdentity("package1A", new NuGetVersion("1.0.0"));
                    var testPackage2 = new PackageIdentity("package1B", new NuGetVersion("1.0.0"));

                    var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestPackageSourcePath,
                                                                                           testPackage1.Id, testPackage1.Version.ToNormalizedString());
                    using (var packageStream = GetDownloadResult(packageFileInfo))
                    {
                        // Act
                        await projectB.InstallPackageAsync(testPackage1, packageStream, testNuGetProjectContext, token);

                        await projectC.InstallPackageAsync(testPackage1, packageStream, testNuGetProjectContext, token);
                    }

                    packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestPackageSourcePath,
                                                                                       testPackage2.Id, testPackage2.Version.ToNormalizedString());
                    using (var packageStream = GetDownloadResult(packageFileInfo))
                    {
                        // Act
                        await projectA.InstallPackageAsync(testPackage2, packageStream, testNuGetProjectContext, token);

                        await projectC.InstallPackageAsync(testPackage2, packageStream, testNuGetProjectContext, token);
                    }

                    var packageRestoreManager = new PackageRestoreManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager);
                    var restoredPackages = new List <PackageIdentity>();
                    packageRestoreManager.PackageRestoredEvent += delegate(object sender, PackageRestoredEventArgs args) { restoredPackages.Add(args.Package); };

                    var restoreFailedPackages = new ConcurrentDictionary <Packaging.PackageReference, IEnumerable <string> >(new PackageReferenceComparer());
                    packageRestoreManager.PackageRestoreFailedEvent += delegate(object sender, PackageRestoreFailedEventArgs args)
                    {
                        restoreFailedPackages.AddOrUpdate(args.RestoreFailedPackageReference,
                                                          args.ProjectNames,
                                                          (Packaging.PackageReference packageReference, IEnumerable <string> oldValue) => { return(oldValue); });
                    };

                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));

                    // Delete packages folder
                    TestFileSystemUtility.DeleteRandomTestFolder(Path.Combine(testSolutionManager.SolutionDirectory, "packages"));

                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(jQuery144));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage1));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage2));

                    // Act
                    await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(testSolutionManager.SolutionDirectory,
                                                                                      testNuGetProjectContext,
                                                                                      CancellationToken.None);

                    // Assert
                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQuery144));
                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage1));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage2));

                    Assert.Equal(4, restoredPackages.Count);
                    // The ordering is not guaranteed and can vary. Do not assert based on that
                    Assert.True(restoredPackages.Contains(jQuery144));
                    Assert.True(restoredPackages.Contains(jQueryValidation));
                    Assert.True(restoredPackages.Contains(testPackage1));
                    Assert.True(restoredPackages.Contains(testPackage2));

                    Assert.Equal(2, restoreFailedPackages.Count);

                    // The ordering is not guaranteed and can vary. Do not assert based on that
                    var restoreFailedPackageKeys = restoreFailedPackages.Keys;
                    var testPackage1Key          = restoreFailedPackageKeys.Where(r => r.PackageIdentity.Equals(testPackage1)).First();
                    var testPackage1ProjectNames = restoreFailedPackages[testPackage1Key].ToList();

                    Assert.Equal(2, testPackage1ProjectNames.Count);
                    Assert.True(testPackage1ProjectNames.Contains("projectB", StringComparer.OrdinalIgnoreCase));
                    Assert.True(testPackage1ProjectNames.Contains("projectC", StringComparer.OrdinalIgnoreCase));

                    var testPackage2Key          = restoreFailedPackageKeys.Where(r => r.PackageIdentity.Equals(testPackage2)).First();
                    var testPackage2ProjectNames = restoreFailedPackages[testPackage2Key].ToList();

                    Assert.Equal(2, testPackage2ProjectNames.Count);
                    Assert.True(testPackage2ProjectNames.Contains("projectA", StringComparer.OrdinalIgnoreCase));
                    Assert.True(testPackage2ProjectNames.Contains("projectC", StringComparer.OrdinalIgnoreCase));
                }
        }
コード例 #27
0
        private async Task InstallPackageAsync(
            string packageId,
            NuGetVersion version,
            string installPath)
        {
            if (version == null)
            {
                // Avoid searching for the highest version in the global packages folder,
                // it needs to come from the feeds instead. Once found it may come from
                // the global packages folder unless NoCache is true.
                ExcludeCacheAsSource = true;
            }

            var framework = GetTargetFramework();

            // Create the project and set the framework if available.
            var project = new InstallCommandProject(
                root: installPath,
                packagePathResolver: new PackagePathResolver(installPath, !ExcludeVersion),
                targetFramework: framework);

            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath);

            var packageSources      = GetPackageSources(Settings);
            var primaryRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);

            Console.PrintPackageSources(packageSources);

            var allowPrerelease = Prerelease || (version != null && version.IsPrerelease);

            var dependencyBehavior = DependencyBehaviorHelper.GetDependencyBehavior(DependencyBehavior.Lowest, DependencyVersion, Settings);

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var resolutionContext = new ResolutionContext(
                    dependencyBehavior,
                    includePrelease: allowPrerelease,
                    includeUnlisted: false,
                    versionConstraints: VersionConstraints.None,
                    gatherCache: new GatherCache(),
                    sourceCacheContext: sourceCacheContext);

                if (version == null)
                {
                    // Write out a helpful message before the http messages are shown
                    Console.Log(LogLevel.Minimal, string.Format(
                                    CultureInfo.CurrentCulture,
                                    LocalizedResourceManager.GetString("InstallPackageMessage"), packageId, installPath));

                    // Find the latest version using NuGetPackageManager
                    var resolvePackage = await NuGetPackageManager.GetLatestVersionAsync(
                        packageId,
                        project,
                        resolutionContext,
                        primaryRepositories,
                        Console,
                        CancellationToken.None);

                    if (resolvePackage == null || resolvePackage.LatestVersion == null)
                    {
                        var message = string.Format(
                            CultureInfo.CurrentCulture,
                            LocalizedResourceManager.GetString("InstallCommandUnableToFindPackage"),
                            packageId);

                        throw new CommandException(message);
                    }

                    version = resolvePackage.LatestVersion;
                }

                // Get a list of packages already in the folder.
                var installedPackages = await project.GetFolderPackagesAsync(CancellationToken.None);

                // Find existing versions of the package
                var alreadyInstalledVersions = new HashSet <NuGetVersion>(installedPackages
                                                                          .Where(e => StringComparer.OrdinalIgnoreCase.Equals(packageId, e.PackageIdentity.Id))
                                                                          .Select(e => e.PackageIdentity.Version));

                var packageIdentity = new PackageIdentity(packageId, version);

                // Check if the package already exists or a higher version exists already.
                var skipInstall = project.PackageExists(packageIdentity);

                // For SxS allow other versions to install. For non-SxS skip if a higher version exists.
                skipInstall |= (ExcludeVersion && alreadyInstalledVersions.Any(e => e >= version));

                if (skipInstall)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("InstallCommandPackageAlreadyExists"),
                        packageIdentity);

                    Console.LogMinimal(message);
                }
                else
                {
                    var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, Console);

                    var projectContext = new ConsoleProjectContext(Console)
                    {
                        PackageExtractionContext = new PackageExtractionContext(
                            Packaging.PackageSaveMode.Defaultv2,
                            PackageExtractionBehavior.XmlDocFileSaveMode,
                            clientPolicyContext,
                            Console)
                    };

                    if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
                    {
                        projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
                    }

                    resolutionContext.SourceCacheContext.NoCache        = NoCache;
                    resolutionContext.SourceCacheContext.DirectDownload = DirectDownload;

                    var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext, installPath, DirectDownload)
                    {
                        ClientPolicyContext = clientPolicyContext
                    };

                    await packageManager.InstallPackageAsync(
                        project,
                        packageIdentity,
                        resolutionContext,
                        projectContext,
                        downloadContext,
                        primaryRepositories,
                        Enumerable.Empty <SourceRepository>(),
                        CancellationToken.None);

                    if (downloadContext.DirectDownload)
                    {
                        GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                    }
                }
            }
        }
コード例 #28
0
        public async Task <string[]> DownloadAsync(string packageFolder, string packageName, string packageVersion = null, bool includePrerelease = false,
                                                   NuGetFeed packageFeed = null, bool onlyDownload = false)
        {
            if (!Directory.Exists(packageFolder))
            {
                Directory.CreateDirectory(packageFolder);
            }

            var providers                = GetNugetResourceProviders();
            var settings                 = Settings.LoadDefaultSettings(packageFolder, null, new MachineWideSettings());
            var packageSourceProvider    = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);

            var dotNetFramework = Assembly
                                  .GetEntryAssembly()
                                  .GetCustomAttribute <TargetFrameworkAttribute>()?
                                  .FrameworkName;

            var frameworkNameProvider = new FrameworkNameProvider(
                new[] { DefaultFrameworkMappings.Instance },
                new[] { DefaultPortableFrameworkMappings.Instance });

            var nuGetFramework = NuGetFramework.ParseFrameworkName(dotNetFramework, frameworkNameProvider);

            IPackageSearchMetadata package    = null;
            SourceRepository       sourceRepo = null;

            if (!string.IsNullOrWhiteSpace(packageFeed?.Feed))
            {
                sourceRepo = GetSourceRepo(packageFeed, providers);

                package = await SearchPackageAsync(packageName, packageVersion, includePrerelease, sourceRepo);
            }
            else
            {
                foreach (var repo in sourceRepositoryProvider.GetRepositories())
                {
                    if (packageFeed != null && repo.PackageSource.Name != packageFeed.Name)
                    {
                        continue;
                    }

                    package = await SearchPackageAsync(packageName, packageVersion, includePrerelease, repo);

                    if (package != null)
                    {
                        sourceRepo = repo;

                        break;
                    }
                }
            }

            if (package == null)
            {
                throw new PackageNotFoundException($"Couldn't find package '{packageVersion}'.{packageVersion}.");
            }

            var project        = new PluginFolderNugetProject(packageFolder, package, nuGetFramework, onlyDownload);
            var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, packageFolder)
            {
                PackagesFolderNuGetProject = project
            };

            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, _logger);

            var projectContext = new FolderProjectContext(_logger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    clientPolicyContext,
                    _logger)
            };

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrerelease,
                includeUnlisted: false,
                VersionConstraints.None);

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

            // We are waiting here instead of await as await actually doesn't seem to work correctly.
            packageManager.InstallPackageAsync(
                project,
                package.Identity,
                resolutionContext,
                projectContext,
                downloadContext,
                sourceRepo,
                new List <SourceRepository>(),
                CancellationToken.None).Wait();

            if (onlyDownload)
            {
                var versionFolder = Path.Combine(packageFolder, package.Identity.ToString());

                return(Directory.GetFiles(versionFolder, "*.*", SearchOption.AllDirectories));
            }

            return(await project.GetPluginAssemblyFilesAsync());
        }
コード例 #29
0
        private static void Main(string[] args)
        {
            try
            {
                var       curDir   = System.IO.Directory.GetCurrentDirectory();
                ISettings settings = Settings.LoadSpecificSettings(curDir, Settings.DefaultSettingsFileName);

                List <Lazy <INuGetResourceProvider> > resourceProviders = new List <Lazy <INuGetResourceProvider> >();
                resourceProviders.AddRange(NuGet.Protocol.Core.Types.Repository.Provider.GetCoreV3());  // Add v3 API support

                IPackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings);

                SourceRepositoryProvider _sourceRepositories = new SourceRepositoryProvider(packageSourceProvider, resourceProviders);

                string projectRoot = System.IO.Path.GetFullPath("ProjectRoot");
                if (!System.IO.Directory.Exists(projectRoot))
                {
                    System.IO.Directory.CreateDirectory(projectRoot);
                }

                FolderNuGetProject nuGetProject = new FolderNuGetProject(projectRoot);

                string packagesFolderPath = System.IO.Path.GetFullPath("Packages");
                if (!System.IO.Directory.Exists(packagesFolderPath))
                {
                    System.IO.Directory.CreateDirectory(packagesFolderPath);
                }

                NuGetPackageManager packageManager = new NuGetPackageManager(_sourceRepositories, settings, packagesFolderPath)
                {
                    PackagesFolderNuGetProject = nuGetProject
                };

                bool allowPrereleaseVersions          = true;
                bool allowUnlisted                    = true;
                DependencyBehavior dependencyBehavior = DependencyBehavior.Lowest;

                ResolutionContext resolutionContext = new ResolutionContext(
                    dependencyBehavior, allowPrereleaseVersions, allowUnlisted, VersionConstraints.None);

                INuGetProjectContext projectContext = new ConsoleProjectContext(NullLogger.Instance);

                IEnumerable <SourceRepository> primarySourceRepositories = _sourceRepositories.GetRepositories();

                //packageIdentity
                string          packageId       = "Newtonsoft.Json";
                string          packageVersion  = "12.0.3";
                PackageIdentity packageIdentity = new PackageIdentity(packageId, new NuGet.Versioning.NuGetVersion(packageVersion));

                var installPackageAsyncTask = packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
                                                                                 packageIdentity, resolutionContext, projectContext,
                                                                                 primarySourceRepositories, Array.Empty <SourceRepository>(), CancellationToken.None);

                installPackageAsyncTask.GetAwaiter().GetResult();
            }
            catch (Exception exp)
            {
                using (var sw = new System.IO.StreamWriter("error.txt"))
                {
                    sw.Write(exp.ToString());
                }

                Console.WriteLine(exp.ToString());
                throw;
            }
        }
コード例 #30
0
        public async Task DownloadPackage(PackageWrapper packageWrapper)
        {
            try
            {
                //this will prevent install to look in all repos
                _sourceRepos = new List <SourceRepository>();
                _sourceRepos.Add(packageWrapper.sourceRepository);

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

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

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

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

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

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

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

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

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

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

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

                #region GetDll paths

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

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

                #endregion

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

                throw;
            }
        }