Exemplo n.º 1
0
        private void GetAllDependencies(IPackage current, List <IPackage> collectedDependencies)
        {
            Debug.Assert(current != null);
            logger.LogDebug(UIResources.NG_ResolvingPackageDependencies, current.Id, current.Version);

            foreach (PackageDependency dependency in current.GetCompatiblePackageDependencies(null))
            {
                IPackage dependencyPackage = packageManager.LocalRepository.ResolveDependency(dependency, true, true);

                if (dependencyPackage == null)
                {
                    logger.LogWarning(UIResources.NG_FailedToResolveDependency, dependency.Id, dependency.VersionSpec.ToString());
                }
                else
                {
                    if (collectedDependencies.Contains(dependencyPackage))
                    {
                        logger.LogDebug(UIResources.NG_DuplicateDependency, dependencyPackage.Id, dependencyPackage.Version);
                    }
                    else
                    {
                        logger.LogDebug(UIResources.NG_AddingNewDependency, dependencyPackage.Id, dependencyPackage.Version);
                        collectedDependencies.Add(dependencyPackage);

                        GetAllDependencies(dependencyPackage, collectedDependencies);
                    }
                }
            }
        }
Exemplo n.º 2
0
        internal /* for testing */ static bool ShouldMergeAnalysisSettings(string language, AnalysisConfig config, Common.ILogger logger)
        {
            Debug.Assert(!string.IsNullOrEmpty(language));
            Debug.Assert(config != null);

            // See https://github.com/SonarSource/sonar-scanner-msbuild/issues/561
            // Legacy behaviour is to overwrite.
            // The new (SQ 7.4+) behaviour is to merge only if sonar.[LANGUAGE].roslyn.ignoreIssues is false.
            var serverVersion = config?.FindServerVersion();

            if (serverVersion == null || serverVersion < new Version("7.4"))
            {
                logger.LogInfo(Resources.AnalyzerSettings_ExternalIssueNotSupported, SonarProduct.GetSonarProductToLog(config?.SonarQubeHostUrl));
                return(false);
            }

            var settingName   = $"sonar.{language}.roslyn.ignoreIssues";
            var settingInFile = config.GetSettingOrDefault(settingName, includeServerSettings: true, defaultValue: "false");

            if (bool.TryParse(settingInFile, out var ignoreExternalRoslynIssues))
            {
                logger.LogDebug(Resources.AnalyzerSettings_ImportAllSettingValue, settingName, ignoreExternalRoslynIssues.ToString().ToLowerInvariant());
                return(!ignoreExternalRoslynIssues);
            }
            else
            {
                logger.LogWarning(Resources.AnalyzerSettings_InvalidValueForImportAll, settingName, settingInFile);
                return(false);
            }
        }
        public void Log(ProjectManagement.MessageLevel level, string message, params object[] args)
        {
            if (args.Length > 0)
            {
                message = string.Format(CultureInfo.CurrentCulture, message, args);
            }

            switch (level)
            {
            case ProjectManagement.MessageLevel.Debug:
                _logger.LogDebug(message);
                break;

            case ProjectManagement.MessageLevel.Info:
                _logger.LogMinimal(message);
                break;

            case ProjectManagement.MessageLevel.Warning:
                _logger.LogWarning(message);
                break;

            case ProjectManagement.MessageLevel.Error:
                _logger.LogError(message);
                break;
            }
        }
Exemplo n.º 4
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1 && !HideWarningsAndErrors)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

            return(await BuildTasksUtility.RestoreAsync(
                       dependencyGraphSpec : dgFile,
                       interactive : Interactive,
                       recursive : RestoreRecursive,
                       noCache : RestoreNoCache,
                       ignoreFailedSources : RestoreIgnoreFailedSources,
                       disableParallel : RestoreDisableParallel,
                       force : RestoreForce,
                       forceEvaluate : RestoreForceEvaluate,
                       hideWarningsAndErrors : HideWarningsAndErrors,
                       restorePC : RestorePackagesConfig,
                       log : log,
                       cancellationToken : _cts.Token));
        }
Exemplo n.º 5
0
        public async Task <bool> DoesNuGetSupportsAnyProjectAsync()
        {
            // Do NOT initialize VSSolutionManager through this API (by calling EnsureInitializeAsync)
            // This is a fast check implemented specifically for right click context menu to be
            // quick and does not involve initializing VSSolutionManager. Otherwise it will create
            // hang issues for right click on solution.
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            // first check with DTE, and if we find any supported project, then return immediately.
            var dte = _serviceProvider.GetDTE();

            var isSupported = EnvDTESolutionUtility.GetAllEnvDTEProjects(dte)
                              .Where(EnvDTEProjectUtility.IsSupported)
                              .Any();

            if (isSupported)
            {
                return(true);
            }

            var deferredProjects = await GetDeferredProjectsAsync();

            foreach (var project in deferredProjects)
            {
                try
                {
                    var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForDeferredProjectAsync(project);

                    if (vsProjectAdapter.IsSupported)
                    {
                        // as soon as we find a supported project, we returns without checking for all the projects.
                        return(true);
                    }
                }
                catch (Exception e)
                {
                    // Ignore failed projects.
                    _logger.LogWarning($"The project {project} failed to initialize as a NuGet project.");
                    _logger.LogError(e.ToString());
                }
            }

            return(false);
        }
        /// <param name="uri">The uri of a web resource for which credentials are needed.</param>
        /// <param name="proxy">Ignored.  Proxy information will not be passed to plugins.</param>
        /// <param name="type">
        /// The type of credential request that is being made. Note that this implementation of
        /// <see cref="ICredentialProvider"/> does not support providing proxy credenitials and treats
        /// all other types the same.
        /// </param>
        /// <param name="isRetry">If true, credentials were previously supplied by this
        /// provider for the same uri.</param>
        /// <param name="message">A message provided by NuGet to show to the user when prompting.</param>
        /// <param name="nonInteractive">If true, the plugin must not prompt for credentials.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A credential object.</returns>
        public async Task <CredentialResponse> GetAsync(Uri uri, IWebProxy proxy, CredentialRequestType type, string message, bool isRetry, bool nonInteractive, CancellationToken cancellationToken)
        {
            CredentialResponse taskResponse = null;

            if (type == CredentialRequestType.Proxy || !_isAnAuthenticationPlugin)
            {
                taskResponse = new CredentialResponse(CredentialStatus.ProviderNotApplicable);
                return(taskResponse);
            }

            var plugin = await _pluginManager.CreateSourceAgnosticPluginAsync(_discoveredPlugin, cancellationToken);

            if (!string.IsNullOrEmpty(plugin.Message))
            {
                // There is a potential here for double logging as the CredentialService itself catches the exceptions and tries to log it.
                // In reality the logger in the Credential Service will be null because the first request always comes from a resource provider (ServiceIndex provider)
                _logger.LogError(plugin.Message);
                throw new PluginException(plugin.Message); // Throwing here will block authentication and ensure that the complete operation fails
            }

            _isAnAuthenticationPlugin = plugin.Claims.Contains(OperationClaim.Authentication);

            if (_isAnAuthenticationPlugin)
            {
                AddOrUpdateLogger(plugin.Plugin);
                await SetPluginLogLevelAsync(plugin, _logger, cancellationToken);

                if (proxy != null)
                {
                    await SetProxyCredentialsToPlugin(uri, proxy, plugin, cancellationToken);
                }

                var request            = new GetAuthenticationCredentialsRequest(uri, isRetry, nonInteractive);
                var credentialResponse = await plugin.Plugin.Connection.SendRequestAndReceiveResponseAsync <GetAuthenticationCredentialsRequest, GetAuthenticationCredentialsResponse>(
                    MessageMethod.GetAuthenticationCredentials,
                    request,
                    cancellationToken);

                if (credentialResponse.ResponseCode == MessageResponseCode.NotFound && nonInteractive)
                {
                    _logger.LogWarning(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.SecurePluginWarning_UseInteractiveOption)
                        );
                }

                taskResponse = GetAuthenticationCredentialsResponseToCredentialResponse(credentialResponse);
            }
            else
            {
                taskResponse = new CredentialResponse(CredentialStatus.ProviderNotApplicable);
            }

            return(taskResponse);
        }
Exemplo n.º 7
0
        private async Task EnsureNuGetAndVsProjectAdapterCacheAsync()
        {
            await _initLock.ExecuteNuGetOperationAsync(async() =>
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                if (!_cacheInitialized && await IsSolutionOpenAsync())
                {
                    try
                    {
                        var dte = await _asyncServiceProvider.GetDTEAsync();

                        var supportedProjects = new List <Project>();
                        foreach (Project project in await EnvDTESolutionUtility.GetAllEnvDTEProjectsAsync(dte))
                        {
                            if (await EnvDTEProjectUtility.IsSupportedAsync(project))
                            {
                                supportedProjects.Add(project);
                            }
                        }

                        foreach (var project in supportedProjects)
                        {
                            try
                            {
                                var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(project);
                                await AddVsProjectAdapterToCacheAsync(vsProjectAdapter);
                            }
                            catch (Exception e)
                            {
                                // Ignore failed projects.
                                _logger.LogWarning($"The project {project.Name} failed to initialize as a NuGet project.");
                                _logger.LogError(e.ToString());
                            }

                            // Consider that the cache is initialized only when there are any projects to add.
                            _cacheInitialized = true;
                        }

                        await SetDefaultProjectNameAsync();
                    }
                    catch
                    {
                        _projectSystemCache.Clear();
                        _cacheInitialized       = false;
                        DefaultNuGetProjectName = null;

                        throw;
                    }
                }
            }, CancellationToken.None);
        }
Exemplo n.º 8
0
        private void EnsureNuGetAndEnvDTEProjectCache()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!_cacheInitialized && IsSolutionOpen)
            {
                try
                {
                    var dte = _serviceProvider.GetDTE();
                    var supportedProjects = EnvDTESolutionUtility.GetAllEnvDTEProjects(dte)
                                            .Where(project => EnvDTEProjectUtility.IsSupported(project));

                    foreach (var project in supportedProjects)
                    {
                        try
                        {
                            AddEnvDTEProjectToCache(project);
                        }
                        catch (Exception e)
                        {
                            // Ignore failed projects.
                            _logger.LogWarning($"The project {project.Name} failed to initialize as a NuGet project.");
                            _logger.LogError(e.ToString());
                        }

                        // Consider that the cache is initialized only when there are any projects to add.
                        _cacheInitialized = true;
                    }

                    SetDefaultProjectName();
                }
                catch
                {
                    _projectSystemCache.Clear();
                    _cacheInitialized       = false;
                    DefaultNuGetProjectName = null;

                    throw;
                }
            }
        }
        /// <summary>
        /// Creates and returns an aggregate repository using the specified settings
        /// </summary>
        public static IPackageRepository CreateRepository(ISettings settings, Common.ILogger logger)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            // Load the user and machine-wide settings
            logger.LogDebug(UIResources.NG_FetchingConfigFiles);

            // Get a package source provider that can use the settings
            PackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings);

            logger.LogDebug(UIResources.NG_ListingEnablePackageSources);
            IEnumerable <PackageSource> enabledSources = packageSourceProvider.GetEnabledPackageSources();

            if (!enabledSources.Any())
            {
                logger.LogWarning(UIResources.NG_NoEnabledPackageSources);
            }
            else
            {
                foreach (PackageSource enabledSource in enabledSources)
                {
                    logger.LogDebug(UIResources.NG_ListEnabledPackageSource, enabledSource.Source, enabledSource.IsMachineWide);
                }
            }

            // Create an aggregate repository that uses all of the configured sources
            AggregateRepository aggRepo = packageSourceProvider.CreateAggregateRepository(PackageRepositoryFactory.Default,
                                                                                          true /* ignore failing repos. Errors will be logged as warnings. */);

            aggRepo.Logger = new NuGetLoggerAdapter(logger);

            return(aggRepo);
        }
Exemplo n.º 10
0
        public void Log(MessageLevel level, string message, params object[] args)
        {
            // Add a prefix to the message to make it easier to determine the source
            string prefixedMessage = LogMessagePrefix + message;

            switch (level)
            {
            case MessageLevel.Debug:
                logger.LogDebug(prefixedMessage, args);
                break;

            case MessageLevel.Error:
                logger.LogError(prefixedMessage, args);
                break;

            case MessageLevel.Warning:
                logger.LogWarning(prefixedMessage, args);
                break;

            default:
                logger.LogInfo(prefixedMessage, args);
                break;
            }
        }
Exemplo n.º 11
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Set user agent and connection settings.
            ConfigureProtocol();

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            //var graphLines = RestoreGraphItems;
            var providerCache = new RestoreCommandProvidersCache();

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache             = RestoreNoCache;
                cacheContext.IgnoreFailedSources = RestoreIgnoreFailedSources;

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>();

                var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

                if (dgFile.Restore.Count < 1)
                {
                    // Restore will fail if given no inputs, but here we should skip it and provide a friendly message.
                    log.LogMinimal(Strings.NoProjectsToRestore);
                    return(true);
                }

                // Add all child projects
                if (RestoreRecursive)
                {
                    BuildTasksUtility.AddAllProjectsForRestore(dgFile);
                }

                providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgFile));

                var defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null);
                var sourceProvider  = new CachingSourceProvider(new PackageSourceProvider(defaultSettings));

                var restoreContext = new RestoreArgs()
                {
                    CacheContext         = cacheContext,
                    LockFileVersion      = LockFileFormat.Version,
                    ConfigFile           = MSBuildStringUtility.TrimAndGetNullForEmpty(RestoreConfigFile),
                    DisableParallel      = RestoreDisableParallel,
                    GlobalPackagesFolder = RestorePackagesPath,
                    Log = log,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    CachingSourceProvider     = sourceProvider,
                    AllowNoOp             = !RestoreForce,
                    HideWarningsAndErrors = HideWarningsAndErrors
                };

                if (!string.IsNullOrEmpty(RestoreSources))
                {
                    var sources = MSBuildStringUtility.Split(RestoreSources);
                    restoreContext.Sources.AddRange(sources);
                }

                if (restoreContext.DisableParallel)
                {
                    HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                }

                _cts.Token.ThrowIfCancellationRequested();

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, _cts.Token);

                // Summary
                RestoreSummary.Log(log, restoreSummaries);

                return(restoreSummaries.All(x => x.Success));
            }
        }
Exemplo n.º 12
0
        public static async Task <bool> RestoreAsync(
            DependencyGraphSpec dependencyGraphSpec,
            bool interactive,
            bool recursive,
            bool noCache,
            bool ignoreFailedSources,
            bool disableParallel,
            bool force,
            bool forceEvaluate,
            bool hideWarningsAndErrors,
            bool restorePC,
            Common.ILogger log,
            CancellationToken cancellationToken)
        {
            if (dependencyGraphSpec == null)
            {
                throw new ArgumentNullException(nameof(dependencyGraphSpec));
            }

            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            try
            {
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !interactive);

                // Set connection limit
                NetworkProtocolUtility.SetConnectionLimit();

                // Set user agent string used for network calls
#if IS_CORECLR
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet .NET Core MSBuild Task")
                                             .WithOSDescription(RuntimeInformation.OSDescription));
#else
                // OS description is set by default on Desktop
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet Desktop MSBuild Task"));
#endif

                // This method has no effect on .NET Core.
                NetworkProtocolUtility.ConfigureSupportedSslProtocols();

                var restoreSummaries = new List <RestoreSummary>();
                var providerCache    = new RestoreCommandProvidersCache();

#if IS_DESKTOP
                if (restorePC && dependencyGraphSpec.Projects.Any(i => i.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig))
                {
                    var v2RestoreResult = await PerformNuGetV2RestoreAsync(log, dependencyGraphSpec, noCache, disableParallel, interactive);

                    restoreSummaries.Add(v2RestoreResult);

                    if (restoreSummaries.Count < 1)
                    {
                        var message = string.Format(
                            Strings.InstallCommandNothingToInstall,
                            "packages.config"
                            );

                        log.LogMinimal(message);
                    }

                    if (!v2RestoreResult.Success)
                    {
                        v2RestoreResult
                        .Errors
                        .Where(l => l.Level == LogLevel.Warning)
                        .ForEach(message =>
                        {
                            log.LogWarning(message.Message);
                        });
                    }
                }
#endif

                using (var cacheContext = new SourceCacheContext())
                {
                    cacheContext.NoCache             = noCache;
                    cacheContext.IgnoreFailedSources = ignoreFailedSources;

                    // Pre-loaded request provider containing the graph file
                    var providers = new List <IPreLoadedRestoreRequestProvider>();

                    if (dependencyGraphSpec.Restore.Count > 0)
                    {
                        // Add all child projects
                        if (recursive)
                        {
                            AddAllProjectsForRestore(dependencyGraphSpec);
                        }

                        providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dependencyGraphSpec));

                        var restoreContext = new RestoreArgs()
                        {
                            CacheContext    = cacheContext,
                            LockFileVersion = LockFileFormat.Version,
                            // 'dotnet restore' fails on slow machines (https://github.com/NuGet/Home/issues/6742)
                            // The workaround is to pass the '--disable-parallel' option.
                            // We apply the workaround by default when the system has 1 cpu.
                            // This will fix restore failures on VMs with 1 CPU and containers with less or equal to 1 CPU assigned.
                            DisableParallel           = Environment.ProcessorCount == 1 ? true : disableParallel,
                            Log                       = log,
                            MachineWideSettings       = new XPlatMachineWideSetting(),
                            PreLoadedRequestProviders = providers,
                            AllowNoOp                 = !force,
                            HideWarningsAndErrors     = hideWarningsAndErrors,
                            RestoreForceEvaluate      = forceEvaluate
                        };

                        if (restoreContext.DisableParallel)
                        {
                            HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        restoreSummaries.AddRange(await RestoreRunner.RunAsync(restoreContext, cancellationToken));
                    }
                }

                if (restoreSummaries.Count < 1)
                {
                    log.LogMinimal(Strings.NoProjectsToRestore);
                }
                else
                {
                    RestoreSummary.Log(log, restoreSummaries);
                }
                return(restoreSummaries.All(x => x.Success));
            }
            finally
            {
                // The CredentialService lifetime is for the duration of the process. We should not leave a potentially unavailable logger.
                // We need to update the delegating logger with a null instance
                // because the tear downs of the plugins and similar rely on idleness and process exit.
                DefaultCredentialServiceUtility.UpdateCredentialServiceDelegatingLogger(NullLogger.Instance);
            }
        }
        /// <summary>
        /// Call the plugin credential provider application to acquire credentials.
        /// The request will be passed to the plugin on standard input as a json serialized
        /// PluginCredentialRequest.
        /// The plugin will return credentials as a json serialized PluginCredentialResponse.
        /// Valid credentials will be returned, or null if the provide cannot provide credentials
        /// for the given request.  If the plugin returns an Abort message, an exception will be thrown to
        /// fail the current request.
        /// </summary>
        /// <param name="uri">The uri of a web resource for which credentials are needed.</param>
        /// <param name="proxy">Ignored.  Proxy information will not be passed to plugins.</param>
        /// <param name="type">
        /// The type of credential request that is being made. Note that this implementation of
        /// <see cref="ICredentialProvider"/> does not support providing proxy credenitials and treats
        /// all other types the same.
        /// </param>
        /// <param name="isRetry">If true, credentials were previously supplied by this
        /// provider for the same uri.</param>
        /// <param name="message">A message provided by NuGet to show to the user when prompting.</param>
        /// <param name="nonInteractive">If true, the plugin must not prompt for credentials.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A credential object.</returns>
        public Task <CredentialResponse> GetAsync(
            Uri uri,
            IWebProxy proxy,
            CredentialRequestType type,
            string message,
            bool isRetry,
            bool nonInteractive,
            CancellationToken cancellationToken)
        {
            CredentialResponse taskResponse;

            if (type == CredentialRequestType.Proxy)
            {
                taskResponse = new CredentialResponse(CredentialStatus.ProviderNotApplicable);
                return(Task.FromResult(taskResponse));
            }

            try
            {
                var request = new PluginCredentialRequest
                {
                    Uri            = uri.AbsoluteUri,
                    IsRetry        = isRetry,
                    NonInteractive = nonInteractive,
                    Verbosity      = _verbosity
                };
                PluginCredentialResponse response;
                if (Interlocked.CompareExchange(ref _deprecationMessageWarningLogged, 1, 0) == 0)
                {
                    _logger.LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.PluginWarning_PluginIsBeingDeprecated, Path, CrossPlatformPluginLink));
                }

                try
                {
                    response = GetPluginResponse(request, cancellationToken);
                }
                catch (PluginUnexpectedStatusException) when(PassVerbosityFlag(request))
                {
                    // older providers may throw if the verbosity flag is sent,
                    // so retry without it
                    request.Verbosity = null;
                    response          = GetPluginResponse(request, cancellationToken);
                }

                if (response.IsValid)
                {
                    var result = new AuthTypeFilteredCredentials(
                        new NetworkCredential(response.Username, response.Password),
                        response.AuthTypes ?? Enumerable.Empty <string>());

                    taskResponse = new CredentialResponse(result);
                }
                else
                {
                    taskResponse = new CredentialResponse(CredentialStatus.ProviderNotApplicable);
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (PluginException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw PluginException.Create(Path, e);
            }

            return(Task.FromResult(taskResponse));
        }
Exemplo n.º 14
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1 && !HideWarningsAndErrors)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Set user agent and connection settings.
            ConfigureProtocol();

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            //var graphLines = RestoreGraphItems;
            var providerCache = new RestoreCommandProvidersCache();

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache             = RestoreNoCache;
                cacheContext.IgnoreFailedSources = RestoreIgnoreFailedSources;

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>();

                var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

                if (dgFile.Restore.Count < 1)
                {
                    // Restore will fail if given no inputs, but here we should skip it and provide a friendly message.
                    log.LogMinimal(Strings.NoProjectsToRestore);
                    return(true);
                }

                // Add all child projects
                if (RestoreRecursive)
                {
                    BuildTasksUtility.AddAllProjectsForRestore(dgFile);
                }

                providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgFile));

                var restoreContext = new RestoreArgs()
                {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    DisableParallel           = RestoreDisableParallel,
                    Log                       = log,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    AllowNoOp                 = !RestoreForce,
                    HideWarningsAndErrors     = HideWarningsAndErrors,
                    RestoreForceEvaluate      = RestoreForceEvaluate
                };

                // 'dotnet restore' fails on slow machines (https://github.com/NuGet/Home/issues/6742)
                // The workaround is to pass the '--disable-parallel' option.
                // We apply the workaround by default when the system has 1 cpu.
                // This will fix restore failures on VMs with 1 CPU and containers with less or equal to 1 CPU assigned.
                if (Environment.ProcessorCount == 1)
                {
                    restoreContext.DisableParallel = true;
                }

                if (restoreContext.DisableParallel)
                {
                    HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                }

                _cts.Token.ThrowIfCancellationRequested();

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, _cts.Token);

                // Summary
                RestoreSummary.Log(log, restoreSummaries);

                return(restoreSummaries.All(x => x.Success));
            }
        }
Exemplo n.º 15
0
        public static async Task <bool> RestoreAsync(
            DependencyGraphSpec dependencyGraphSpec,
            bool interactive,
            bool recursive,
            bool noCache,
            bool ignoreFailedSources,
            bool disableParallel,
            bool force,
            bool forceEvaluate,
            bool hideWarningsAndErrors,
            bool restorePC,
            bool cleanupAssetsForUnsupportedProjects,
            Common.ILogger log,
            CancellationToken cancellationToken)
        {
            if (dependencyGraphSpec == null)
            {
                throw new ArgumentNullException(nameof(dependencyGraphSpec));
            }

            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            try
            {
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !interactive);

                // Set connection limit
                NetworkProtocolUtility.SetConnectionLimit();

                // Set user agent string used for network calls
#if IS_CORECLR
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet .NET Core MSBuild Task")
                                             .WithOSDescription(RuntimeInformation.OSDescription));
#else
                // OS description is set by default on Desktop
                UserAgent.SetUserAgentString(new UserAgentStringBuilder("NuGet Desktop MSBuild Task"));
#endif

                X509TrustStore.InitializeForDotNetSdk(log);

                var restoreSummaries = new List <RestoreSummary>();
                var providerCache    = new RestoreCommandProvidersCache();

#if IS_DESKTOP
                if (restorePC && dependencyGraphSpec.Projects.Any(i => i.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig))
                {
                    var v2RestoreResult = await PerformNuGetV2RestoreAsync(log, dependencyGraphSpec, noCache, disableParallel, interactive);

                    restoreSummaries.Add(v2RestoreResult);

                    if (restoreSummaries.Count < 1)
                    {
                        var message = string.Format(
                            Strings.InstallCommandNothingToInstall,
                            "packages.config"
                            );

                        log.LogMinimal(message);
                    }

                    if (!v2RestoreResult.Success)
                    {
                        v2RestoreResult
                        .Errors
                        .Where(l => l.Level == LogLevel.Warning)
                        .ForEach(message =>
                        {
                            log.LogWarning(message.Message);
                        });
                    }
                }
#endif

                using (var cacheContext = new SourceCacheContext())
                {
                    cacheContext.NoCache             = noCache;
                    cacheContext.IgnoreFailedSources = ignoreFailedSources;

                    // Pre-loaded request provider containing the graph file
                    var providers = new List <IPreLoadedRestoreRequestProvider>();

                    if (dependencyGraphSpec.Restore.Count > 0)
                    {
                        // Add all child projects
                        if (recursive)
                        {
                            AddAllProjectsForRestore(dependencyGraphSpec);
                        }

                        providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dependencyGraphSpec));

                        var restoreContext = new RestoreArgs()
                        {
                            CacheContext    = cacheContext,
                            LockFileVersion = LockFileFormat.Version,
                            // 'dotnet restore' fails on slow machines (https://github.com/NuGet/Home/issues/6742)
                            // The workaround is to pass the '--disable-parallel' option.
                            // We apply the workaround by default when the system has 1 cpu.
                            // This will fix restore failures on VMs with 1 CPU and containers with less or equal to 1 CPU assigned.
                            DisableParallel           = Environment.ProcessorCount == 1 ? true : disableParallel,
                            Log                       = log,
                            MachineWideSettings       = new XPlatMachineWideSetting(),
                            PreLoadedRequestProviders = providers,
                            AllowNoOp                 = !force,
                            HideWarningsAndErrors     = hideWarningsAndErrors,
                            RestoreForceEvaluate      = forceEvaluate
                        };

                        if (restoreContext.DisableParallel)
                        {
                            HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                        }

                        cancellationToken.ThrowIfCancellationRequested();

                        restoreSummaries.AddRange(await RestoreRunner.RunAsync(restoreContext, cancellationToken));
                    }

                    if (cleanupAssetsForUnsupportedProjects)
                    {
                        // Restore assets are normally left on disk between restores for all projects.  This can cause a condition where a project that supports PackageReference was restored
                        // but then a user changes a branch or some other condition and now the project does not use PackageReference. Since the restore assets are left on disk, the build
                        // consumes them which can cause build errors. The code below cleans up all of the files that we write so that they are not used during build
                        Parallel.ForEach(dependencyGraphSpec.Projects.Where(i => !DoesProjectSupportRestore(i)), project =>
                        {
                            if (project.RestoreMetadata == null || string.IsNullOrWhiteSpace(project.RestoreMetadata.OutputPath) || string.IsNullOrWhiteSpace(project.RestoreMetadata.ProjectPath))
                            {
                                return;
                            }

                            // project.assets.json
                            FileUtility.Delete(Path.Combine(project.RestoreMetadata.OutputPath, LockFileFormat.AssetsFileName));

                            // project.csproj.nuget.cache
                            FileUtility.Delete(project.RestoreMetadata.CacheFilePath);

                            // project.csproj.nuget.g.props
                            FileUtility.Delete(BuildAssetsUtils.GetMSBuildFilePathForPackageReferenceStyleProject(project, BuildAssetsUtils.PropsExtension));

                            // project..csproj.nuget.g.targets
                            FileUtility.Delete(BuildAssetsUtils.GetMSBuildFilePathForPackageReferenceStyleProject(project, BuildAssetsUtils.TargetsExtension));

                            // project.csproj.nuget.dgspec.json
                            FileUtility.Delete(Path.Combine(project.RestoreMetadata.OutputPath, DependencyGraphSpec.GetDGSpecFileName(Path.GetFileName(project.RestoreMetadata.ProjectPath))));
                        });
                    }
                }

                if (restoreSummaries.Count < 1)
                {
                    log.LogMinimal(Strings.NoProjectsToRestore);
                }
                else
                {
                    RestoreSummary.Log(log, restoreSummaries);
                }
                return(restoreSummaries.All(x => x.Success));
            }
            finally
            {
                // The CredentialService lifetime is for the duration of the process. We should not leave a potentially unavailable logger.
                // We need to update the delegating logger with a null instance
                // because the tear downs of the plugins and similar rely on idleness and process exit.
                DefaultCredentialServiceUtility.UpdateCredentialServiceDelegatingLogger(NullLogger.Instance);
            }
        }
Exemplo n.º 16
0
        private async Task EnsureNuGetAndVsProjectAdapterCacheAsync()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!_cacheInitialized && IsSolutionOpen)
            {
                try
                {
                    var deferedProjects = GetDeferredProjects();

                    foreach (var project in deferedProjects)
                    {
                        try
                        {
                            var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForDeferredProjectAsync(project);

                            AddVsProjectAdapterToCache(vsProjectAdapter);
                        }
                        catch (Exception e)
                        {
                            // Ignore failed projects.
                            _logger.LogWarning($"The project {project} failed to initialize as a NuGet project.");
                            _logger.LogError(e.ToString());
                        }

                        // Consider that the cache is initialized only when there are any projects to add.
                        _cacheInitialized = true;
                    }

                    var dte = _serviceProvider.GetDTE();

                    var supportedProjects = EnvDTESolutionUtility
                                            .GetAllEnvDTEProjects(dte)
                                            .Where(EnvDTEProjectUtility.IsSupported);

                    foreach (var project in supportedProjects)
                    {
                        try
                        {
                            var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(project);

                            AddVsProjectAdapterToCache(vsProjectAdapter);
                        }
                        catch (Exception e)
                        {
                            // Ignore failed projects.
                            _logger.LogWarning($"The project {project.Name} failed to initialize as a NuGet project.");
                            _logger.LogError(e.ToString());
                        }

                        // Consider that the cache is initialized only when there are any projects to add.
                        _cacheInitialized = true;
                    }

                    SetDefaultProjectName();
                }
                catch
                {
                    _projectSystemCache.Clear();
                    _cacheInitialized       = false;
                    DefaultNuGetProjectName = null;

                    throw;
                }
            }
        }