Beispiel #1
0
        internal NuGetPackProvider(string name, string query, DirectoryInfo packageTempBasePath, int pageSize, bool runOnlyOnePage, bool includePreviewPacks)
        {
            Name             = name;
            _pageSize        = pageSize;
            _runOnlyOnePage  = runOnlyOnePage;
            _packageTempPath = Path.GetFullPath(Path.Combine(packageTempBasePath.FullName, DownloadedPacksDir, Name));
            _repository      = Repository.Factory.GetCoreV3(NuGetOrgFeed);
            ServiceIndexResourceV3            indexResource   = _repository.GetResource <ServiceIndexResourceV3>();
            IReadOnlyList <ServiceIndexEntry> searchResources = indexResource.GetServiceEntries("SearchQueryService");

            _downloadResource = _repository.GetResource <FindPackageByIdResource>();
            _includePreview   = includePreviewPacks;

            if (!searchResources.Any())
            {
                throw new Exception($"{NuGetOrgFeed} does not support search API (SearchQueryService)");
            }

            _searchUriFormat = $"{searchResources[0].Uri}?{query}&skip={{0}}&take={{1}}&prerelease={includePreviewPacks}&semVerLevel=2.0.0";

            if (Directory.Exists(_packageTempPath))
            {
                throw new Exception($"temp storage path for NuGet packages already exists: {_packageTempPath}");
            }
            else
            {
                Directory.CreateDirectory(_packageTempPath);
            }
        }
Beispiel #2
0
        public async Task CanReadPackageInfo()
        {
            string nuGetOrgFeed = "https://api.nuget.org/v3/index.json";
            var    repository   = Repository.Factory.GetCoreV3(nuGetOrgFeed);
            ServiceIndexResourceV3            indexResource   = repository.GetResource <ServiceIndexResourceV3>();
            IReadOnlyList <ServiceIndexEntry> searchResources = indexResource.GetServiceEntries("SearchQueryService");
            string queryString = $"{searchResources[0].Uri}?q=Microsoft.DotNet.Common.ProjectTemplates.5.0&skip=0&take=10&prerelease=true&semVerLevel=2.0.0";
            Uri    queryUri    = new Uri(queryString);

            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(queryUri, CancellationToken.None).ConfigureAwait(false))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        string responseText = await response.Content.ReadAsStringAsync(CancellationToken.None).ConfigureAwait(false);

                        NuGetPackageSearchResult resultsForPage = NuGetPackageSearchResult.FromJObject(JObject.Parse(responseText));
                        Assert.Equal(1, resultsForPage.TotalHits);
                        Assert.Equal(1, resultsForPage.Data.Count);

                        var packageInfo = resultsForPage.Data[0];

                        Assert.Equal("Microsoft.DotNet.Common.ProjectTemplates.5.0", packageInfo.Name);
                        Assert.NotEmpty(packageInfo.Version);
                        Assert.True(packageInfo.TotalDownloads > 0);
                        Assert.True(packageInfo.Verified);
                        Assert.Contains("Microsoft", packageInfo.Owners);
                        Assert.NotEmpty(packageInfo.Description);
                        Assert.NotEmpty(packageInfo.IconUrl);
                    }
                    else
                    {
                        Assert.True(false, "HTTP request failed.");
                    }
                }
        }
        /// <summary>
        ///     Determine the NuGet package sources configured for the current project and create clients for them.
        /// </summary>
        /// <param name="cancellationToken">
        ///     An optional <see cref="CancellationToken"/> that can be used to cancel the operation.
        /// </param>
        /// <returns>
        ///     <c>true</c>, if the package sources were loaded; otherwise, <c>false</c>.
        /// </returns>
        public virtual async Task <bool> ConfigurePackageSources(CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                _configuredPackageSources.Clear();
                _autoCompleteResources.Clear();

                bool             includeLocalSources   = Workspace.Configuration.NuGet.IncludeLocalSources;
                HashSet <string> ignoredPackageSources = Workspace.Configuration.NuGet.IgnorePackageSources;

                foreach (PackageSource packageSource in NuGetHelper.GetWorkspacePackageSources(ProjectFile.Directory.FullName))
                {
                    // Exclude package sources explicitly ignored by name.
                    string packageSourceName = packageSource.Name ?? "<unknown>";
                    if (ignoredPackageSources.Contains(packageSourceName))
                    {
                        Log.Verbose("Ignoring package source named {PackageSourceName} (the language server has been explicitly configured to ignore it).", packageSourceName);

                        continue;
                    }

                    // Exclude package sources explicitly ignored by URI.
                    Uri packageSourceUri = packageSource.TrySourceAsUri ?? new Uri("unknown:/", UriKind.Absolute);
                    if (ignoredPackageSources.Contains(packageSourceUri.AbsoluteUri))
                    {
                        Log.Verbose("Ignoring package source with URI {PackageSourceURI} (the language server has been explicitly configured to ignore it).", packageSourceUri.AbsoluteUri);

                        continue;
                    }

                    // Exclude unsupported package-source types.
                    if (!packageSource.IsHttp)
                    {
                        if (packageSourceUri.Scheme == Uri.UriSchemeFile)
                        {
                            if (!includeLocalSources)
                            {
                                Log.Verbose("Ignoring local package source {PackageSourceName} ({PackageSourcePath}) (the language server has not been configured to use local package sources).",
                                            packageSourceName,
                                            packageSourceUri.AbsolutePath
                                            );

                                continue;
                            }
                        }
                        else
                        {
                            Log.Verbose("Ignoring local package source {PackageSourceName} ({PackageSourceUri}) (the language server only supports local and HTTP-based package sources).",
                                        packageSourceName,
                                        packageSourceUri.AbsolutePath
                                        );

                            continue;
                        }
                    }

                    _configuredPackageSources.Add(packageSource);
                }

                Log.Information("{PackageSourceCount} package sources configured for project {ProjectFile}.",
                                _configuredPackageSources.Count,
                                VSCodeDocumentUri.GetFileSystemPath(DocumentUri)
                                );
                foreach (PackageSource packageSource in _configuredPackageSources)
                {
                    if (packageSource.IsMachineWide)
                    {
                        Log.Information("  Globally-configured package source {PackageSourceName} (v{PackageSourceProtocolVersion}) => {PackageSourceUri}",
                                        packageSource.Name,
                                        packageSource.ProtocolVersion,
                                        packageSource.SourceUri
                                        );
                    }
                    else
                    {
                        Log.Information("  Locally-configured package source {PackageSourceName} (v{PackageSourceProtocolVersion}) => {PackageSourceUri}",
                                        packageSource.Name,
                                        packageSource.ProtocolVersion,
                                        packageSource.SourceUri
                                        );
                    }
                }

                List <SourceRepository> sourceRepositories = _configuredPackageSources.CreateResourceRepositories();
                foreach (SourceRepository sourceRepository in sourceRepositories)
                {
                    ServiceIndexResourceV3 serviceIndex = await sourceRepository.GetResourceAsync <ServiceIndexResourceV3>(cancellationToken);

                    if (serviceIndex == null)
                    {
                        Log.Warning("    Ignoring configured package source {PackageSourceName} ({PackageSourceUri}) because the v3 service index cannot be found for this package source.",
                                    sourceRepository.PackageSource.Name ?? "<unknown>",
                                    sourceRepository.PackageSource.TrySourceAsUri?.AbsoluteUri ?? "unknown:/"
                                    );

                        continue;
                    }

                    IReadOnlyList <ServiceIndexEntry> autoCompleteServices = serviceIndex.GetServiceEntries(ServiceTypes.SearchAutocompleteService);
                    if (autoCompleteServices.Count == 0)
                    {
                        Log.Warning("    Ignoring configured package source {PackageSourceName} ({PackageSourceUri}) because it does not appear to support a compatible version of the NuGet auto-complete API.",
                                    sourceRepository.PackageSource.Name ?? "<unknown>",
                                    sourceRepository.PackageSource.TrySourceAsUri?.AbsoluteUri ?? "unknown:/"
                                    );

                        continue;
                    }

                    AutoCompleteResource autoCompleteResource = await sourceRepository.GetResourceAsync <AutoCompleteResource>(cancellationToken);

                    if (autoCompleteResource == null)
                    {
                        // Should not happen.
                        Log.Error("Failed to retrieve {ServiceName} service instance for configured package source {PackageSourceName} ({PackageSourceUri}).",
                                  "AutoComplete",
                                  sourceRepository.PackageSource.Name ?? "<unknown>",
                                  sourceRepository.PackageSource.TrySourceAsUri?.AbsoluteUri ?? "unknown:/"
                                  );

                        continue;
                    }

                    _autoCompleteResources.Add(autoCompleteResource);
                }

                return(true);
            }
            catch (Exception packageSourceLoadError)
            {
                Log.Error(packageSourceLoadError, "Error configuring NuGet package sources for MSBuild project '{ProjectFileName}'.", ProjectFile.FullName);

                return(false);
            }
        }