Beispiel #1
0
        protected override void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                foreach (var pair in _fileStreams)
                {
                    if (pair.Value.Value.Status == TaskStatus.RanToCompletion)
                    {
                        var fileStream = pair.Value.Value.Result;

                        if (fileStream != null)
                        {
                            fileStream.Dispose();
                        }
                    }
                }

                _fileStreams.Clear();

                _plugin.Dispose();

                _getFilesSemaphore.Dispose();
                _getNuspecReaderSemaphore.Dispose();

                if (_tempDirectoryPath.IsValueCreated)
                {
                    LocalResourceUtils.DeleteDirectoryTree(_tempDirectoryPath.Value, new List <string>());
                }

                _isDisposed = true;
            }
        }
Beispiel #2
0
        private bool ClearCacheDirectory(string folderPath)
        {
            // In order to get detailed error messages, we need to do recursion ourselves.
            var failedDeletes = new List <string>();

            LocalResourceUtils.DeleteDirectoryTree(folderPath, failedDeletes);

            if (failedDeletes.Any())
            {
                Console.WriteWarning(
                    LocalizedResourceManager.GetString(nameof(NuGetResources.LocalsCommand_LocalsPartiallyCleared)));

                foreach (var failedDelete in failedDeletes.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
                {
                    Console.WriteWarning(
                        LocalizedResourceManager.GetString(nameof(NuGetResources.LocalsCommand_FailedToDeletePath)),
                        failedDelete);
                }

                return(false);
            }
            else
            {
                return(true);
            }
        }
            public void Dispose()
            {
                LocalResourceUtils.DeleteDirectoryTree(
                    Path.Combine(
                        SettingsUtility.GetPluginsCacheFolder(),
                        CachingUtility.RemoveInvalidFileNameChars(CachingUtility.ComputeHash(_pluginFilePath))),
                    new List <string>());
                PluginManager.Dispose();
                _testDirectory.Dispose();

                _reader.Verify();
                _pluginDiscoverer.Verify();

                foreach (var expectation in _expectations)
                {
                    _connection.Verify(x => x.SendRequestAndReceiveResponseAsync <GetOperationClaimsRequest, GetOperationClaimsResponse>(
                                           It.Is <MessageMethod>(m => m == MessageMethod.GetOperationClaims),
                                           It.Is <GetOperationClaimsRequest>(
                                               g => g.PackageSourceRepository == expectation.SourceRepository.PackageSource.Source),
                                           It.IsAny <CancellationToken>()), Times.Once());

                    var expectedSetCredentialsRequestCalls = expectation.OperationClaims.Any()
                        ? Times.Once() : Times.Never();

                    _connection.Verify(x => x.SendRequestAndReceiveResponseAsync <SetCredentialsRequest, SetCredentialsResponse>(
                                           It.Is <MessageMethod>(m => m == MessageMethod.SetCredentials),
                                           It.Is <SetCredentialsRequest>(
                                               g => g.PackageSourceRepository == expectation.SourceRepository.PackageSource.Source),
                                           It.IsAny <CancellationToken>()), expectedSetCredentialsRequestCalls);
                }

                _plugin.Verify();
                _factory.Verify();
            }
        public void DeleteDirectoryTreeDeletesReparsePointsButNotReparsePointTargets()
        {
            // This test creates a cached package and a subdirectory in the working directory.
            // The subdirectory is a reparse point linked to the target directory.

            // Deleting the directory tree should delete the reparse point, but not the target of the reparse point.
            // The cached package in the working directory should also be deleted.

            // The also creates a dummy file in the linked target directory, and verifies
            // this file is left as-is after deletion of the directory tree including the reparse point.

            // Finally, test clean-up is verified.

            var failedDeletes = new List <string>();

            string targetDirectoryPath;
            string fileInTargetDirectory;

            using (var targetDirectory = TestDirectory.Create())
            {
                // Arrange
                targetDirectoryPath = targetDirectory.Path;

                using (var workingDirectory = TestDirectory.Create())
                {
                    var subDirectoryPath = Path.Combine(workingDirectory.Path, "SubDirectory");
                    var subDirectory     = Directory.CreateDirectory(subDirectoryPath);

                    Util.CreatePackage(workingDirectory.Path, Guid.NewGuid().ToString("N"), "1.0.0");
                    fileInTargetDirectory = Path.Combine(targetDirectoryPath, "test.txt");
                    File.WriteAllText(fileInTargetDirectory, string.Empty);

                    Util.CreateJunctionPoint(subDirectory.FullName, targetDirectoryPath, overwrite: true);

                    // Act
                    LocalResourceUtils.DeleteDirectoryTree(workingDirectory.Path, failedDeletes);

                    // Assert
                    Assert.Empty(failedDeletes);
                    Assert.False(Directory.Exists(workingDirectory.Path));
                    Assert.True(Directory.Exists(targetDirectoryPath));
                    Assert.True(File.Exists(fileInTargetDirectory));
                }
            }

            // Verify clean-up
            Assert.False(Directory.Exists(targetDirectoryPath));
            Assert.False(File.Exists(fileInTargetDirectory));
        }
        public void Dispose()
        {
            LocalResourceUtils.DeleteDirectoryTree(
                Path.Combine(
                    SettingsUtility.GetPluginsCacheFolder(),
                    CachingUtility.RemoveInvalidFileNameChars(CachingUtility.ComputeHash(_pluginFilePath))),
                new List <string>());
            PluginManager.Dispose();

            _reader.Verify();
            _pluginDiscoverer.Verify();
            if (_expectations.PluginLaunched)
            {
                _connection.Verify(x => x.SendRequestAndReceiveResponseAsync <GetOperationClaimsRequest, GetOperationClaimsResponse>(
                                       It.Is <MessageMethod>(m => m == MessageMethod.GetOperationClaims),
                                       It.Is <GetOperationClaimsRequest>(
                                           g => g.PackageSourceRepository == null), // The source repository should be null in the context of credential plugins
                                       It.IsAny <CancellationToken>()), Times.Once());

                if (_expectations.Success)
                {
                    _connection.Verify(x => x.SendRequestAndReceiveResponseAsync <GetAuthenticationCredentialsRequest, GetAuthenticationCredentialsResponse>(
                                           It.Is <MessageMethod>(m => m == MessageMethod.GetAuthenticationCredentials),
                                           It.IsAny <GetAuthenticationCredentialsRequest>(),
                                           It.IsAny <CancellationToken>()), Times.Once());
                }

                if (_expectations.ProxyUsername != null && _expectations.ProxyPassword != null)
                {
                    _connection.Verify(x => x.SendRequestAndReceiveResponseAsync <SetCredentialsRequest, SetCredentialsResponse>(
                                           It.Is <MessageMethod>(m => m == MessageMethod.SetCredentials),
                                           It.Is <SetCredentialsRequest>(e => e.PackageSourceRepository.Equals(_expectations.Uri.AbsolutePath) && e.Password == null && e.Username == null && e.ProxyPassword.Equals(_expectations.ProxyPassword) && e.ProxyUsername.Equals(_expectations.ProxyUsername)),
                                           It.IsAny <CancellationToken>()),
                                       Times.Once());
                }
            }
            _connection.Verify();

            _plugin.Verify();
            _factory.Verify();

            _testDirectory.Dispose();
        }
Beispiel #6
0
        public void CleanupPackagesFolder()
        {
            var unusedPackages = _localPackageRepository
                                 .GetPackages()
                                 .ToList()
                                 .Where(x => !_loadedMsBuildNuGetProjects
                                        .SelectMany(y => y.Value.GetInstalledPackagesAsync(new CancellationToken()).Result)
                                        .Select(y => y.PackageIdentity)
                                        .Any(y => y.Id == x.Id && y.Version.ToString() == x.Version.ToString()))
                                 .ToArray();

            foreach (IPackage package in unusedPackages)
            {
                var pathToDelete = Path.Combine(_packagesFolder, $"{package.Id}.{package.Version}");

                // One would think Directory.Delete(path, recursive: true) would do the job, well
                // it regularly fails, and looking online it seems the solution is try/catches with
                // retries and recursive deletes. Well guess what, Nuget has one of those
                // monstrosities already, hooray!
                LocalResourceUtils.DeleteDirectoryTree(pathToDelete, new List <string>());
            }
        }
        /// <summary>
        /// Recursively deletes the specified directory tree.
        /// </summary>
        /// <param name="folderPath">Specified directory to be deleted</param>
        /// <returns><code>True</code> if the operation was successful; otherwise <code>false</code>.</returns>
        private bool ClearCacheDirectory(string folderPath, LocalsArgs localsArgs)
        {
            // In order to get detailed error messages, we need to do recursion ourselves.
            var failedDeletes = new List <string>();

            LocalResourceUtils.DeleteDirectoryTree(folderPath, failedDeletes);

            if (failedDeletes.Any())
            {
                localsArgs.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_LocalsPartiallyCleared));

                foreach (var failedDelete in failedDeletes.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
                {
                    localsArgs.LogError(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_FailedToDeletePath, failedDelete));
                }

                return(false);
            }
            else
            {
                return(true);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Restores a package by querying, downloading, and unzipping it without generating any other files (like project.assets.json).
        /// </summary>
        /// <param name="libraryIdentity">The <see cref="LibraryIdentity"/> of the package.</param>
        /// <param name="settings">The NuGet settings to use.</param>
        /// <param name="logger">An <see cref="ILogger"/> to use for logging.</param>
        /// <returns></returns>
        public static Task <IReadOnlyList <RestoreResultPair> > RunWithoutCommit(LibraryIdentity libraryIdentity, ISettings settings, ILogger logger)
        {
            using (var sourceCacheContext = new SourceCacheContext
            {
                IgnoreFailedSources = true,
            })
            {
                // Create a unique temporary directory for the project
                var projectDirectory = Directory.CreateDirectory(Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), Guid.NewGuid().ToString("N")));

                try
                {
                    var projectName = Guid.NewGuid().ToString("N");

                    var projectFullPath = Path.Combine(projectDirectory.FullName, $"{projectName}.proj");

                    // The package spec details what packages to restore
                    var packageSpec = new PackageSpec(TargetFrameworks.Select(i => new TargetFrameworkInformation
                    {
                        FrameworkName = i,
                    }).ToList())
                    {
                        Dependencies = new List <LibraryDependency>
                        {
                            new LibraryDependency
                            {
                                LibraryRange = new LibraryRange(
                                    libraryIdentity.Name,
                                    new VersionRange(
                                        minVersion: libraryIdentity.Version,
                                        includeMinVersion: true,
                                        maxVersion: libraryIdentity.Version,
                                        includeMaxVersion: true),
                                    LibraryDependencyTarget.Package),
                                SuppressParent = LibraryIncludeFlags.All,
                                AutoReferenced = true,
                                IncludeType    = LibraryIncludeFlags.None,
                                Type           = LibraryDependencyType.Build
                            }
                        },
                        RestoreMetadata = new ProjectRestoreMetadata
                        {
                            ProjectPath              = projectFullPath,
                            ProjectName              = projectName,
                            ProjectStyle             = ProjectStyle.PackageReference,
                            ProjectUniqueName        = projectFullPath,
                            OutputPath               = projectDirectory.FullName,
                            OriginalTargetFrameworks = TargetFrameworks.Select(i => i.ToString()).ToList(),
                            ConfigFilePaths          = settings.GetConfigFilePaths(),
                            PackagesPath             = SettingsUtility.GetGlobalPackagesFolder(settings),
                            Sources         = SettingsUtility.GetEnabledSources(settings).ToList(),
                            FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList()
                        },
                        FilePath = projectFullPath,
                        Name     = projectName,
                    };

                    var dependencyGraphSpec = new DependencyGraphSpec();

                    dependencyGraphSpec.AddProject(packageSpec);

                    dependencyGraphSpec.AddRestore(packageSpec.RestoreMetadata.ProjectUniqueName);

                    IPreLoadedRestoreRequestProvider requestProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dependencyGraphSpec);

                    var restoreArgs = new RestoreArgs
                    {
                        AllowNoOp    = false,
                        CacheContext = sourceCacheContext,
    #pragma warning disable CS0618 // Type or member is obsolete
                        CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(settings, enablePackageSourcesChangedEvent: false)),
    #pragma warning restore CS0618 // Type or member is obsolete
                        Log = logger,
                    };

                    // Create requests from the arguments
                    var requests = requestProvider.CreateRequests(restoreArgs).Result;

                    // Restore the package without generating extra files
                    return(RestoreRunner.RunWithoutCommit(requests, restoreArgs));
                }
                finally
                {
                    LocalResourceUtils.DeleteDirectoryTree(projectDirectory.FullName, new List <string>());
                }
            }
        }