Exemplo n.º 1
0
        private void ReadSettings(PackageRestoreInputs packageRestoreInputs)
        {
            if (IsSolutionRestore(packageRestoreInputs))
            {
                var solutionDirectory = GetSolutionDirectory(packageRestoreInputs);

                // Read the solution-level settings
                var solutionSettingsFile = Path.Combine(
                    solutionDirectory,
                    NuGetConstants.NuGetSolutionSettingsFolder);
                if (ConfigFile != null)
                {
                    ConfigFile = Path.GetFullPath(ConfigFile);
                }

                Settings = Configuration.Settings.LoadDefaultSettings(
                    solutionSettingsFile,
                    configFileName: ConfigFile,
                    machineWideSettings: MachineWideSettings);

                // Recreate the source provider and credential provider
                SourceProvider = PackageSourceBuilder.CreateSourceProvider(Settings);
                SetDefaultCredentialProvider();
            }
        }
Exemplo n.º 2
0
        private void ProcessSolutionFile(string solutionFileFullPath, PackageRestoreInputs restoreInputs)
        {
            restoreInputs.DirectoryOfSolutionFile = Path.GetDirectoryName(solutionFileFullPath);
            restoreInputs.NameOfSolutionFile      = Path.GetFileNameWithoutExtension(solutionFileFullPath);

            // restore packages for the solution
            var solutionLevelPackagesConfig = Path.Combine(
                restoreInputs.DirectoryOfSolutionFile,
                NuGetConstants.NuGetSolutionSettingsFolder,
                Constants.PackageReferenceFile);

            if (File.Exists(solutionLevelPackagesConfig))
            {
                restoreInputs.PackagesConfigFiles.Add(solutionLevelPackagesConfig);
            }

            var projectFiles = MsBuildUtility.GetAllProjectFileNames(solutionFileFullPath, MsBuildDirectory.Value.Path);

            foreach (var projectFile in projectFiles)
            {
                if (!File.Exists(projectFile))
                {
                    var message = string.Format(CultureInfo.CurrentCulture,
                                                LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"),
                                                projectFile);
                    Console.LogWarning(message);
                    continue;
                }

                var normalizedProjectFile = Path.GetFullPath(projectFile);

                // Add everything
                restoreInputs.ProjectFiles.Add(normalizedProjectFile);
            }
        }
Exemplo n.º 3
0
        private void AddInputsFromDependencyGraphSpec(PackageRestoreInputs packageRestoreInputs, DependencyGraphSpec dgFileOutput)
        {
            packageRestoreInputs.ProjectReferenceLookup = dgFileOutput;

            // Get top level entries
            var entryPointProjects = dgFileOutput
                                     .Projects
                                     .Where(project => dgFileOutput.Restore.Contains(project.RestoreMetadata.ProjectUniqueName, StringComparer.Ordinal))
                                     .ToList();

            // possible packages.config
            // Compare paths case-insenstive here since we do not know how msbuild modified them
            // find all projects that are not part of the v3 group
            var v2RestoreProjects =
                packageRestoreInputs.ProjectFiles
                .Where(path => !entryPointProjects.Any(project => path.Equals(project.RestoreMetadata.ProjectPath, StringComparison.OrdinalIgnoreCase)));

            packageRestoreInputs.PackagesConfigFiles
            .AddRange(v2RestoreProjects
                      .Select(GetPackagesConfigFile)
                      .Where(path => path != null));

            // Filter down to just the requested projects in the file
            // that support transitive references.
            var v3RestoreProjects = dgFileOutput.Projects
                                    .Where(project => (project.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference ||
                                                       project.RestoreMetadata.ProjectStyle == ProjectStyle.ProjectJson) &&
                                           entryPointProjects.Contains(project));

            packageRestoreInputs.RestoreV3Context.Inputs.AddRange(v3RestoreProjects
                                                                  .Select(project => project.RestoreMetadata.ProjectPath));
        }
Exemplo n.º 4
0
        private string GetPackagesFolder(PackageRestoreInputs packageRestoreInputs)
        {
            if (!string.IsNullOrEmpty(PackagesDirectory))
            {
                return(PackagesDirectory);
            }

            var repositoryPath = SettingsUtility.GetRepositoryPath(Settings);

            if (!string.IsNullOrEmpty(repositoryPath))
            {
                return(repositoryPath);
            }

            if (!string.IsNullOrEmpty(SolutionDirectory))
            {
                return(Path.Combine(SolutionDirectory, CommandLineConstants.PackagesDirectoryName));
            }

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                return(Path.Combine(
                           packageRestoreInputs.DirectoryOfSolutionFile,
                           CommandLineConstants.PackagesDirectoryName));
            }

            throw new InvalidOperationException(
                      LocalizedResourceManager.GetString("RestoreCommandCannotDeterminePackagesFolder"));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Determine if a file is v2 or v3
        /// </summary>
        private void GetInputsFromFile(string projectFilePath, PackageRestoreInputs packageRestoreInputs)
        {
            // An argument was passed in. It might be a solution file or directory,
            // project file, or packages.config file
            var projectFileName = Path.GetFileName(projectFilePath);

            if (IsPackagesConfig(projectFileName))
            {
                // restoring from packages.config or packages.projectname.config file
                packageRestoreInputs.PackagesConfigFiles.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
            {
                packageRestoreInputs.ProjectFiles.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith(".dg", StringComparison.OrdinalIgnoreCase))
            {
                packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
            {
                ProcessSolutionFile(projectFilePath, packageRestoreInputs);
            }
            else if (ProjectJsonPathUtilities.IsProjectConfig(projectFileName))
            {
                // project.json is no longer allowed
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("Error_ProjectJsonNotAllowed"), projectFileName));
            }
            else
            {
                // Not a file we know about. Try to be helpful without response.
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, RestoreRunner.GetInvalidInputErrorMessage(projectFileName), projectFileName));
            }
        }
Exemplo n.º 6
0
        private void ProcessSolutionFile(string solutionFileFullPath, PackageRestoreInputs restoreInputs)
        {
            restoreInputs.DirectoryOfSolutionFile = Path.GetDirectoryName(solutionFileFullPath);

            // restore packages for the solution
            var solutionLevelPackagesConfig = Path.Combine(
                restoreInputs.DirectoryOfSolutionFile,
                NuGetConstants.NuGetSolutionSettingsFolder,
                Constants.PackageReferenceFile);

            if (File.Exists(solutionLevelPackagesConfig))
            {
                restoreInputs.PackagesConfigFiles.Add(solutionLevelPackagesConfig);
            }

            var projectFiles = MsBuildUtility.GetAllProjectFileNames(solutionFileFullPath, _msbuildDirectory.Value);

            foreach (var projectFile in projectFiles)
            {
                if (!File.Exists(projectFile))
                {
                    var message = string.Format(CultureInfo.CurrentCulture,
                                                LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"),
                                                projectFile);
                    Console.LogWarning(message);
                    continue;
                }

                var normalizedProjectFile = Path.GetFullPath(projectFile);

                // packages.config
                var packagesConfigFilePath = GetPackageReferenceFile(normalizedProjectFile);

                // project.json
                var dir             = Path.GetDirectoryName(normalizedProjectFile);
                var projectName     = Path.GetFileNameWithoutExtension(normalizedProjectFile);
                var projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(dir, projectName);

                // project.json overrides packages.config
                if (File.Exists(projectJsonPath))
                {
                    // project.json inputs are resolved again against the p2p file
                    // and are matched with the solution there
                    // For known msbuild project types use the project
                    if (MsBuildUtility.IsMsBuildBasedProject(normalizedProjectFile))
                    {
                        restoreInputs.RestoreV3Context.Inputs.Add(normalizedProjectFile);
                    }
                    else
                    {
                        // For unknown types restore the project.json file without p2ps
                        restoreInputs.RestoreV3Context.Inputs.Add(projectJsonPath);
                    }
                }
                else if (File.Exists(packagesConfigFilePath))
                {
                    restoreInputs.PackagesConfigFiles.Add(packagesConfigFilePath);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Read project inputs using MSBuild
        /// </summary>
        private async Task DetermineInputsFromMSBuildAsync(PackageRestoreInputs packageRestoreInputs)
        {
            // Find P2P graph for v3 inputs.
            // Ignore xproj files as top level inputs
            var projectsWithPotentialP2PReferences = packageRestoreInputs
                                                     .ProjectFiles
                                                     .Where(path => !path.EndsWith(".xproj", StringComparison.OrdinalIgnoreCase))
                                                     .ToArray();

            if (projectsWithPotentialP2PReferences.Length > 0)
            {
                DependencyGraphSpec dgFileOutput = null;

                try
                {
                    dgFileOutput = await GetDependencyGraphSpecAsync(projectsWithPotentialP2PReferences,
                                                                     GetSolutionDirectory(packageRestoreInputs),
                                                                     packageRestoreInputs.NameOfSolutionFile,
                                                                     ConfigFile);
                }
                catch (Exception ex)
                {
                    // At this point reading the project has failed, to keep backwards
                    // compatibility this should warn instead of error if
                    // packages.config files exist, but no project.json files.
                    // This will skip NETCore projects which is a problem, but there is
                    // not a good way to know if they exist, or if this is an old type of
                    // project that the targets file cannot handle.

                    // Log exception for debug
                    Console.LogDebug(ex.ToString());

                    // Check for packages.config but no project.json files
                    if (projectsWithPotentialP2PReferences.Where(HasPackagesConfigFile).Any() &&
                        !projectsWithPotentialP2PReferences.Where(HasProjectJsonFile).Any())
                    {
                        // warn to let the user know that NETCore will be skipped
                        Console.LogWarning(LocalizedResourceManager.GetString("Warning_ReadingProjectsFailed"));

                        // Add packages.config
                        packageRestoreInputs.PackagesConfigFiles
                        .AddRange(projectsWithPotentialP2PReferences
                                  .Select(GetPackagesConfigFile)
                                  .Where(path => path != null));
                    }
                    else
                    {
                        // If there are project.json files or no packages.config files
                        // continue to fail
                        throw;
                    }
                }

                // Process the DG file and add both v2 and v3 inputs
                if (dgFileOutput != null)
                {
                    AddInputsFromDependencyGraphSpec(packageRestoreInputs, dgFileOutput);
                }
            }
        }
        /// <summary>
        /// Determine if a file is v2 or v3
        /// </summary>
        private void GetInputsFromFile(string projectFilePath, PackageRestoreInputs packageRestoreInputs)
        {
            // An argument was passed in. It might be a solution file or directory,
            // project file, project.json, or packages.config file
            var projectFileName = Path.GetFileName(projectFilePath);

            if (ProjectJsonPathUtilities.IsProjectConfig(projectFileName))
            {
                // project.json or projName.project.json
                packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
            }
            else if (IsPackagesConfig(projectFileName))
            {
                // restoring from packages.config or packages.projectname.config file
                packageRestoreInputs.PackagesConfigFiles.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
            {
                // For msbuild files find the project.json or packages.config file,
                // if neither exist skip it
                var projectName = Path.GetFileNameWithoutExtension(projectFileName);
                var dir         = Path.GetDirectoryName(projectFilePath);

                var projectJsonPath    = ProjectJsonPathUtilities.GetProjectConfigPath(dir, projectName);
                var packagesConfigPath = GetPackageReferenceFile(projectFilePath);

                // Check for project.json
                if (File.Exists(projectJsonPath))
                {
                    if (MsBuildUtility.IsMsBuildBasedProject(projectFilePath))
                    {
                        // Add the project file path if it allows p2ps
                        packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
                    }
                    else
                    {
                        // Unknown project type, add the project.json by itself
                        packageRestoreInputs.RestoreV3Context.Inputs.Add(projectJsonPath);
                    }
                }
                else if (File.Exists(packagesConfigPath))
                {
                    // Check for packages.config, if it exists add it directly
                    packageRestoreInputs.PackagesConfigFiles.Add(packagesConfigPath);
                }
            }
            else if (projectFileName.EndsWith(".dg", StringComparison.OrdinalIgnoreCase))
            {
                packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
            {
                ProcessSolutionFile(projectFilePath, packageRestoreInputs);
            }
            else
            {
                // Not a file we know about. Try to be helpful without response.
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, RestoreRunner.GetInvalidInputErrorMessage(projectFileName), projectFileName));
            }
        }
Exemplo n.º 9
0
        private string GetSolutionDirectory(PackageRestoreInputs packageRestoreInputs)
        {
            var solutionDirectory = packageRestoreInputs.RestoringWithSolutionFile ?
                                    packageRestoreInputs.DirectoryOfSolutionFile :
                                    SolutionDirectory;

            return(solutionDirectory != null?PathUtility.EnsureTrailingSlash(solutionDirectory) : null);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Search a directory for v2 or v3 inputs, only the first type is taken.
        /// </summary>
        private void GetInputsFromDirectory(string directory, PackageRestoreInputs packageRestoreInputs)
        {
            var topLevelFiles = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly);

            //  Solution files
            var solutionFiles = topLevelFiles.Where(file =>
                                                    file.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
                                .ToArray();

            if (solutionFiles.Length > 0)
            {
                if (solutionFiles.Length != 1)
                {
                    throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_MultipleSolutions"));
                }

                var file = solutionFiles[0];

                if (Verbosity == Verbosity.Detailed)
                {
                    Console.WriteLine(
                        LocalizedResourceManager.GetString("RestoreCommandRestoringPackagesForSolution"),
                        file);
                }

                ProcessSolutionFile(file, packageRestoreInputs);

                return;
            }

            // Packages.config
            var packagesConfigFile = Path.Combine(directory, Constants.PackageReferenceFile);

            if (File.Exists(packagesConfigFile))
            {
                if (Verbosity == Verbosity.Detailed)
                {
                    Console.WriteLine(
                        LocalizedResourceManager.GetString(
                            "RestoreCommandRestoringPackagesFromPackagesConfigFile"));
                }

                // packages.confg with no solution file
                packageRestoreInputs.PackagesConfigFiles.Add(packagesConfigFile);

                return;
            }

            // The directory did not contain a valid target, fail!
            var noInputs = string.Format(
                CultureInfo.CurrentCulture,
                LocalizedResourceManager.GetString(
                    "Error_UnableToLocateRestoreTarget"),
                directory);

            throw new InvalidOperationException(noInputs);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Discover all restore inputs, this checks for both v2 and v3
        /// </summary>
        private async Task <PackageRestoreInputs> DetermineRestoreInputsAsync()
        {
            var packageRestoreInputs = new PackageRestoreInputs();

            if (Arguments.Count == 0)
            {
                // If no arguments were provided use the current directory
                GetInputsFromDirectory(Directory.GetCurrentDirectory(), packageRestoreInputs);
            }
            else
            {
                // Restore takes multiple arguments, each could be a file or directory
                var argument = Arguments.Single();
                var fullPath = Path.GetFullPath(argument);

                if (Directory.Exists(fullPath))
                {
                    // Dir
                    GetInputsFromDirectory(fullPath, packageRestoreInputs);
                }
                else if (File.Exists(fullPath))
                {
                    // File
                    GetInputsFromFile(fullPath, packageRestoreInputs);
                }
                else
                {
                    // Not found
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        argument);

                    throw new InvalidOperationException(message);
                }
            }
            // Run inputs through msbuild to determine the
            // correct type and find dependencies as needed.
            await DetermineInputsFromMSBuildAsync(packageRestoreInputs);

            return(packageRestoreInputs);
        }
Exemplo n.º 12
0
        private static string GetEffectiveGlobalPackagesFolder(
            string packagesDirectoryParameter,
            string solutionDirectoryParameter,
            PackageRestoreInputs packageRestoreInputs,
            string globalPackagesFolder)
        {
            // Return the -PackagesDirectory parameter if specified
            if (!string.IsNullOrEmpty(packagesDirectoryParameter))
            {
                return(packagesDirectoryParameter);
            }

            // Return the globalPackagesFolder as-is if it is a full path
            if (Path.IsPathRooted(globalPackagesFolder))
            {
                return(globalPackagesFolder);
            }
            else if (!string.IsNullOrEmpty(solutionDirectoryParameter) ||
                     packageRestoreInputs.RestoringWithSolutionFile)
            {
                var solutionDirectory = packageRestoreInputs.RestoringWithSolutionFile ?
                                        packageRestoreInputs.DirectoryOfSolutionFile :
                                        solutionDirectoryParameter;

                // -PackagesDirectory parameter was not provided and globalPackagesFolder is a relative path.
                // Use the solutionDirectory to construct the full path
                return(Path.Combine(solutionDirectory, globalPackagesFolder));
            }

            // -PackagesDirectory parameter was not provided and globalPackagesFolder is a relative path.
            // solution directory is not available either. Throw
            var message = string.Format(
                CultureInfo.CurrentCulture,
                LocalizedResourceManager.GetString("RestoreCommandCannotDetermineGlobalPackagesFolder"));

            throw new CommandLineException(message);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Search a directory for v2 or v3 inputs, only the first type is taken.
        /// </summary>
        private void GetInputsFromDirectory(string directory, PackageRestoreInputs packageRestoreInputs)
        {
            var topLevelFiles = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly);

            //  Solution files
            var solutionFiles = topLevelFiles.Where(file =>
                                                    file.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
                                .ToArray();

            if (solutionFiles.Length > 0)
            {
                if (solutionFiles.Length != 1)
                {
                    throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_MultipleSolutions"));
                }

                var file = solutionFiles[0];

                if (Verbosity == Verbosity.Detailed)
                {
                    Console.WriteLine(
                        LocalizedResourceManager.GetString("RestoreCommandRestoringPackagesForSolution"),
                        file);
                }

                ProcessSolutionFile(file, packageRestoreInputs);

                return;
            }

            // Packages.config
            var packagesConfigFile = Path.Combine(directory, Constants.PackageReferenceFile);

            if (File.Exists(packagesConfigFile))
            {
                if (Verbosity == Verbosity.Detailed)
                {
                    Console.WriteLine(
                        LocalizedResourceManager.GetString(
                            "RestoreCommandRestoringPackagesFromPackagesConfigFile"));
                }

                // packages.confg with no solution file
                packageRestoreInputs.PackagesConfigFiles.Add(packagesConfigFile);

                return;
            }

            // Project.json is any directory
            try
            {
                if (Directory.EnumerateFiles(directory, $"*{ProjectJsonPathUtilities.ProjectConfigFileName}", SearchOption.AllDirectories).Any())
                {
                    // V3 recursive project.json search
                    packageRestoreInputs.RestoreV3Context.Inputs.Add(directory);

                    return;
                }
            }
            catch (UnauthorizedAccessException e)
            {
                // Access to a subpath of the directory is denied.
                var resourceMessage = LocalizedResourceManager.GetString("Error_UnableToLocateRestoreTarget_Because");
                var message         = string.Format(CultureInfo.CurrentCulture, resourceMessage, directory);

                throw new InvalidOperationException(message, e);
            }

            // The directory did not contain a valid target, fail!
            var noInputs = string.Format(
                CultureInfo.CurrentCulture,
                LocalizedResourceManager.GetString(
                    "Error_UnableToLocateRestoreTarget"),
                directory);

            throw new InvalidOperationException(noInputs);
        }
Exemplo n.º 14
0
        private async Task <IReadOnlyList <RestoreSummary> > PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
        {
            ReadSettings(packageRestoreInputs);
            var packagesFolderPath = Path.GetFullPath(GetPackagesFolder(packageRestoreInputs));

            var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                installedPackageReferences.AddRange(packageRestoreInputs
                                                    .PackagesConfigFiles
                                                    .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true)));
            }
            else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
            {
                // By default the PackageReferenceFile does not throw
                // if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
                             "Only one packages.config file is allowed to be specified " +
                             "at a time when not performing solution restore.");

                var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
                if (!File.Exists(packageReferenceFile))
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        packageReferenceFile);

                    throw new InvalidOperationException(message);
                }

                installedPackageReferences.AddRange(
                    GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true));
            }

            // EffectivePackageSaveMode is None when -PackageSaveMode is not provided by the user. None is treated as
            // Defaultv3 for V3 restore and should be treated as Defaultv2 for V2 restore. This is the case in the
            // actual V2 restore flow and should match in this preliminary missing packages check.
            var packageSaveMode = EffectivePackageSaveMode == Packaging.PackageSaveMode.None ?
                                  Packaging.PackageSaveMode.Defaultv2 :
                                  EffectivePackageSaveMode;

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity, packageSaveMode)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    "packages.config");

                Console.LogMinimal(message);

                var restoreSummaries = new List <RestoreSummary>();

                ValidatePackagesConfigLockFiles(
                    packageRestoreInputs.PackagesConfigFiles,
                    packageRestoreInputs.ProjectReferenceLookup.Projects,
                    packagesFolderPath,
                    restoreSummaries);

                if (restoreSummaries.Count == 0)
                {
                    restoreSummaries.Add(new RestoreSummary(success: true));
                }

                return(restoreSummaries);
            }

            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { packageRestoreInputs.RestoringWithSolutionFile
                                ? packageRestoreInputs.DirectoryOfSolutionFile
                                : packageRestoreInputs.PackagesConfigFiles[0] },
                                                                         isMissing: true));

            var packageSources = GetPackageSources(Settings);

            var repositories = packageSources
                               .Select(sourceRepositoryProvider.CreateRepository)
                               .ToArray();

            var installCount    = 0;
            var failedEvents    = new ConcurrentQueue <PackageRestoreFailedEventArgs>();
            var collectorLogger = new RestoreCollectorLogger(Console);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: DisableParallelProcessing
                        ? 1
                        : PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: collectorLogger);

            CheckRequireConsent();

            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, collectorLogger);
            var projectContext      = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    Packaging.PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    clientPolicyContext,
                    collectorLogger)
            };

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

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var packageSourceMapping = PackageSourceMapping.GetPackageSourceMapping(Settings);

                var downloadContext = new PackageDownloadContext(cacheContext, packagesFolderPath, DirectDownload, packageSourceMapping)
                {
                    ClientPolicyContext = clientPolicyContext
                };

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    projectContext,
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }

                IReadOnlyList <IRestoreLogMessage> errors = collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents)).ToList();
                var restoreSummaries = new List <RestoreSummary>()
                {
                    new RestoreSummary(
                        result.Restored,
                        "packages.config projects",
                        Settings.GetConfigFilePaths().ToList().AsReadOnly(),
                        packageSources.Select(x => x.Source).ToList().AsReadOnly(),
                        installCount,
                        errors)
                };

                if (result.Restored)
                {
                    ValidatePackagesConfigLockFiles(
                        packageRestoreInputs.PackagesConfigFiles,
                        packageRestoreInputs.ProjectReferenceLookup.Projects,
                        packagesFolderPath,
                        restoreSummaries);
                }

                return(restoreSummaries);
            }
        }
Exemplo n.º 15
0
 private bool IsSolutionRestore(PackageRestoreInputs packageRestoreInputs)
 {
     return(!string.IsNullOrEmpty(SolutionDirectory) || packageRestoreInputs.RestoringWithSolutionFile);
 }
Exemplo n.º 16
0
 private string GetSolutionDirectory(PackageRestoreInputs packageRestoreInputs)
 {
     return(packageRestoreInputs.RestoringWithSolutionFile ?
            packageRestoreInputs.DirectoryOfSolutionFile :
            SolutionDirectory);
 }
        /// <summary>
        /// Discover all restore inputs, this checks for both v2 and v3
        /// </summary>
        private PackageRestoreInputs DetermineRestoreInputs()
        {
            var packageRestoreInputs = new PackageRestoreInputs();

            if (Arguments.Count == 0)
            {
                // If no arguments were provided use the current directory
                GetInputsFromDirectory(Directory.GetCurrentDirectory(), packageRestoreInputs);
            }
            else
            {
                // Restore takes multiple arguments, each could be a file or directory
                var argument = Arguments.Single();
                var fullPath = Path.GetFullPath(argument);

                if (Directory.Exists(fullPath))
                {
                    // Dir
                    GetInputsFromDirectory(fullPath, packageRestoreInputs);
                }
                else if (File.Exists(fullPath))
                {
                    // File
                    GetInputsFromFile(fullPath, packageRestoreInputs);
                }
                else
                {
                    // Not found
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        argument);

                    throw new InvalidOperationException(message);
                }
            }

            // Find P2P graph for v3 inputs.
            var projectsWithPotentialP2PReferences = packageRestoreInputs.RestoreV3Context.Inputs
                                                     .Where(MsBuildUtility.IsMsBuildBasedProject)
                                                     .ToArray();

            if (projectsWithPotentialP2PReferences.Length > 0)
            {
                int scaleTimeout;

                if (Project2ProjectTimeOut > 0)
                {
                    scaleTimeout = Project2ProjectTimeOut * 1000;
                }
                else
                {
                    scaleTimeout = MsBuildUtility.MsBuildWaitTime *
                                   Math.Max(10, projectsWithPotentialP2PReferences.Length / 2) / 10;
                }

                Console.LogVerbose($"MSBuild P2P timeout [ms]: {scaleTimeout}");

                // Call MSBuild to resolve P2P references.
                var referencesLookup = MsBuildUtility.GetProjectReferences(
                    _msbuildDirectory.Value,
                    projectsWithPotentialP2PReferences,
                    scaleTimeout);

                packageRestoreInputs.ProjectReferenceLookup = referencesLookup;
            }

            return(packageRestoreInputs);
        }
        private async Task <RestoreSummary> PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
        {
            ReadSettings(packageRestoreInputs);
            var packagesFolderPath = GetPackagesFolder(packageRestoreInputs);

            var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                installedPackageReferences.AddRange(packageRestoreInputs
                                                    .PackagesConfigFiles
                                                    .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true)));
            }
            else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
            {
                // By default the PackageReferenceFile does not throw
                // if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
                             "Only one packages.config file is allowed to be specified " +
                             "at a time when not performing solution restore.");

                var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
                if (!File.Exists(packageReferenceFile))
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        packageReferenceFile);

                    throw new InvalidOperationException(message);
                }

                installedPackageReferences.AddRange(
                    GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true));
            }

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    "packages.config");

                Console.LogMinimal(message);
                return(new RestoreSummary(true));
            }

            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { packageRestoreInputs.RestoringWithSolutionFile
                                ? packageRestoreInputs.DirectoryOfSolutionFile
                                : packageRestoreInputs.PackagesConfigFiles[0] },
                                                                         isMissing: true));

            var packageSources = GetPackageSources(Settings);

            var repositories = packageSources
                               .Select(sourceRepositoryProvider.CreateRepository)
                               .ToArray();

            var installCount = 0;
            var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>();

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: DisableParallelProcessing
                        ? 1
                        : PackageManagementConstants.DefaultMaxDegreeOfParallelism);

            CheckRequireConsent();

            var collectorLogger = new CollectorLogger(Console);
            var projectContext  = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(collectorLogger)
            };

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

            var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                packageRestoreContext,
                projectContext);

            return(new RestoreSummary(
                       result.Restored,
                       "packages.config projects",
                       Settings.Priority.Select(x => Path.Combine(x.Root, x.FileName)),
                       packageSources.Select(x => x.Source),
                       installCount,
                       collectorLogger.Errors.Concat(failedEvents.Select(e => e.Exception.Message))));
        }