예제 #1
0
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            UISearchResourceV3 curResource = null;
            var serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                var rawSearch = await source.GetResourceAsync<RawSearchResourceV3>(token);
                var metadataResource = await source.GetResourceAsync<UIMetadataResource>(token);

                curResource = new UISearchResourceV3(rawSearch, metadataResource);
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            MetadataResourceV3 curResource = null;
            RegistrationResourceV3 regResource = await source.GetResourceAsync<RegistrationResourceV3>(token);

            if (regResource != null)
            {
                var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(token);
                DataClient client = new DataClient(messageHandlerResource.MessageHandler);

                curResource = new MetadataResourceV3(client, regResource);
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            UIMetadataResourceV3 curResource = null;

            if (await source.GetResourceAsync<ServiceIndexResourceV3>(token) != null)
            {
                var regResource = await source.GetResourceAsync<RegistrationResourceV3>();
                var reportAbuseResource = await source.GetResourceAsync<ReportAbuseResourceV3>();

                // construct a new resource
                curResource = new UIMetadataResourceV3(_client, regResource, reportAbuseResource);
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken cancellationToken)
        {
            V3TotalsStatsResource totalsStatsResource = null;
            var serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>(cancellationToken);

            if (serviceIndex != null)
            {
                // TODO: fix this for resource templates
                throw new NotImplementedException();

                //ResourceSelector resourceSelector = new ResourceSelector(source);

                //IList<Uri> resourceUrls = serviceIndex[ServiceTypes.TotalStats];
                //Uri resourceUri = await resourceSelector.DetermineResourceUrlAsync(resourceUrls, cancellationToken);

                //var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(cancellationToken);
                //DataClient client = new DataClient(messageHandlerResource.MessageHandler);


                //// construct a new resource
                //totalsStatsResource = new V3TotalsStatsResource(client, resourceUri);
            }

            return new Tuple<bool, INuGetResource>(totalsStatsResource != null, totalsStatsResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            PSAutoCompleteResourceV3 curResource = null;

            var serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                var regResource = await source.GetResourceAsync<RegistrationResourceV3>(token);

                // construct a new resource
                curResource = new PSAutoCompleteResourceV3(_client, serviceIndex, regResource);
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            SearchLatestResourceV3 curResource = null;
            ServiceIndexResourceV3 serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                var rawSearch = await source.GetResourceAsync<RawSearchResourceV3>(token);

                if (rawSearch != null)
                {
                    curResource = new SearchLatestResourceV3(rawSearch);
                }
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            DependencyInfoResource curResource = null;

            if (await source.GetResourceAsync<ServiceIndexResourceV3>(token) != null)
            {
                var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(token);

                var client = new DataClient(messageHandlerResource.MessageHandler);

                var regResource = await source.GetResourceAsync<RegistrationResourceV3>(token);

                // construct a new resource
                curResource = new DependencyInfoResourceV3(client, regResource, source);
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            RegistrationResourceV3 regResource = null;
            var serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                Uri baseUrl = serviceIndex[ServiceTypes.RegistrationsBaseUrl].FirstOrDefault();

                var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(token);

                DataClient client = new DataClient(messageHandlerResource.MessageHandler);

                // construct a new resource
                regResource = new RegistrationResourceV3(client, baseUrl);
            }

            return new Tuple<bool, INuGetResource>(regResource != null, regResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            PSSearchResource resource = null;
            UISearchResource uiSearchResource = await source.GetResourceAsync<UISearchResource>(token);
            if (uiSearchResource != null)
            {
                resource = new PowerShellSearchResourceV2(uiSearchResource);
            }

            return new Tuple<bool, INuGetResource>(resource != null, resource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            RawSearchResourceV3 curResource = null;
            ServiceIndexResourceV3 serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>();

            if (serviceIndex != null)
            {
                var endpoints = serviceIndex[ServiceTypes.SearchQueryService].ToArray();

                if (endpoints.Length > 0)
                {
                    var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(token);

                    // construct a new resource
                    curResource = new RawSearchResourceV3(messageHandlerResource.MessageHandler, endpoints);
                }
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
        protected async Task<V2Resource> GetRepository(SourceRepository source, CancellationToken token)
        {
            var repositoryResource = await source.GetResourceAsync<PackageRepositoryResourceV2>(token);

            if (repositoryResource != null && repositoryResource.V2Client != null)
            {
                return repositoryResource;
            }

            return null;
        }
        private static async Task<Stream> GetDownloadStream(SourceRepository sourceRepository, PackageIdentity packageIdentity, CancellationToken token)
        {
            Stream downloadStream = null;
            DownloadResource downloadResource = await sourceRepository.GetResourceAsync<DownloadResource>(token);
            if(downloadResource != null)
            {
                downloadStream = await downloadResource.GetStream(packageIdentity, token);
                return downloadStream;
            }

            return null;
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            ApiAppSearchResource resource = null;

            var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(token);
            ServiceIndexResourceV3 serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>();

            if (messageHandlerResource != null && serviceIndex != null)
            {
                var endpoints = serviceIndex["ApiAppSearchQueryService"];

                if (endpoints.Any())
                {
                    RawSearchResourceV3 rawSearch = new RawSearchResourceV3(messageHandlerResource.MessageHandler, endpoints);

                    resource = new ApiAppSearchResource(rawSearch);
                }
            }

            return new Tuple<bool, INuGetResource>(resource != null, resource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            SimpleSearchResourceV3 curResource = null;

            var rawSearch = await source.GetResourceAsync<RawSearchResourceV3>(token);

            if (rawSearch != null && rawSearch is RawSearchResourceV3)
            {
                curResource = new SimpleSearchResourceV3(rawSearch);
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository sourceRepository, CancellationToken token)
        {
            INuGetResource resource = null;

            var serviceIndexResource = await sourceRepository.GetResourceAsync<ServiceIndexResourceV3>();

            if (serviceIndexResource != null)
            {
                resource = new RemoteV3FindPackageByIdResource(sourceRepository);
            }

            return Tuple.Create(resource != null, resource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository sourceRepository, CancellationToken token)
        {
            INuGetResource resource = null;
            var serviceIndexResource = await sourceRepository.GetResourceAsync<ServiceIndexResourceV3>();
            var packageBaseAddress = serviceIndexResource?[HttpFileSystemIndexType];

            if (packageBaseAddress != null
                && packageBaseAddress.Count > 0)
            {
                resource = new HttpFileSystemBasedFindPackageByIdResource(packageBaseAddress);
            }

            return Tuple.Create(resource != null, resource);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            PowerShellSearchResource resource = null;

            // PS search depends on v3 json search
            RawSearchResourceV3 rawSearch = await source.GetResourceAsync<RawSearchResourceV3>();

            if (rawSearch != null)
            {
                resource = new PowerShellSearchResource(rawSearch);
            }

            return new Tuple<bool, INuGetResource>(resource != null, resource);
        }
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository sourceRepository, CancellationToken token)
        {
            INuGetResource resource             = null;
            var            serviceIndexResource = await sourceRepository.GetResourceAsync <ServiceIndexResourceV3>();

            var packageBaseAddress = serviceIndexResource?[HttpFileSystemIndexType];

            if (packageBaseAddress != null &&
                packageBaseAddress.Count > 0)
            {
                resource = new HttpFileSystemBasedFindPackageByIdResource(packageBaseAddress);
            }

            return(Tuple.Create(resource != null, resource));
        }
예제 #19
0
        internal static async Task <T> GetResourceAndValidateAsync <T>(this SourceRepository srcRepo) where T : class, INuGetResource
        {
            var resource = await srcRepo.GetResourceAsync <T>();

            if (resource == null)
            {
                // if endpoint is invalid, NuGet client would return us a null resource
                // throw a specific error, so that caller will have a clear understanding what is happening

                string feed = srcRepo.PackageSource != null ? srcRepo.PackageSource.Source : string.Empty;
                throw new InvalidEndpointException(string.Format("Invalid remote feed url: {0}", feed));
            }

            return(resource);
        }
예제 #20
0
        private async Task <SemanticVersion> GetVersionAsync(bool prerelease)
        {
            try
            {
                var metadataResource = await _sourceRepository.GetResourceAsync <MetadataResource>();

                var versions = await metadataResource.GetVersions("dotnet-stryker", includePrerelease : true, includeUnlisted : false, _sourceCacheContext, _logger.Value, CancellationToken.None);

                return(versions.OrderBy(x => x).Last(x => prerelease ? x.IsPrerelease : !x.IsPrerelease));
            }
            catch
            {
                return(new SemanticVersion(0, 0, 0));
            }
        }
예제 #21
0
        private async Task EnsureResource()
        {
            if (_findPackagesByIdResource == null)
            {
                var resource = await _sourceRepository.GetResourceAsync <FindPackageByIdResource>();

                lock (_lock)
                {
                    if (_findPackagesByIdResource == null)
                    {
                        _findPackagesByIdResource = resource;
                    }
                }
            }
        }
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token)
        {
            PackageMetadataResourceV3 curResource = null;

            if (await source.GetResourceAsync <ServiceIndexResourceV3>(token) != null)
            {
                var regResource = await source.GetResourceAsync <RegistrationResourceV3>();

                var reportAbuseResource = await source.GetResourceAsync <ReportAbuseResourceV3>();

                var packageDetailsUriResource = await source.GetResourceAsync <PackageDetailsUriResourceV3>();

                var httpSourceResource = await source.GetResourceAsync <HttpSourceResource>(token);

                // construct a new resource
                curResource = new PackageMetadataResourceV3(
                    httpSourceResource.HttpSource,
                    regResource,
                    reportAbuseResource,
                    packageDetailsUriResource);
            }

            return(new Tuple <bool, INuGetResource>(curResource != null, curResource));
        }
예제 #23
0
        public async Task <string> GetPackageUrl(PackageId packageId,
                                                 NuGetVersion packageVersion = null,
                                                 PackageSourceLocation packageSourceLocation = null,
                                                 bool includePreview = false)
        {
            (var source, var resolvedPackageVersion) = await GetPackageSourceAndVerion(packageId, packageVersion, packageSourceLocation, includePreview);

            SourceRepository repository = Repository.Factory.GetCoreV3(source);

            ServiceIndexResourceV3 serviceIndexResource = repository.GetResourceAsync <ServiceIndexResourceV3>().Result;
            IReadOnlyList <Uri>    packageBaseAddress   =
                serviceIndexResource?.GetServiceEntryUris(ServiceTypes.PackageBaseAddress);

            return(GetNupkgUrl(packageBaseAddress.First().ToString(), packageId, resolvedPackageVersion));
        }
예제 #24
0
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token)
        {
            ReportAbuseResourceV3 resource = null;
            var serviceIndex = await source.GetResourceAsync <ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                var uriTemplate = serviceIndex.GetServiceEntryUri(ServiceTypes.ReportAbuse)?.AbsoluteUri;

                // construct a new resource
                resource = new ReportAbuseResourceV3(uriTemplate);
            }

            return(new Tuple <bool, INuGetResource>(resource != null, resource));
        }
예제 #25
0
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(
            SourceRepository source,
            CancellationToken token)
        {
            PackageUpdateResource packageUpdateResource = null;

            var serviceIndex = await source.GetResourceAsync <ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                var baseUrl = serviceIndex[ServiceTypes.PackagePublish].FirstOrDefault();

                HttpSource httpSource = null;
                var        sourceUri  = baseUrl?.AbsoluteUri;
                if (!string.IsNullOrEmpty(sourceUri))
                {
                    if (!(new Uri(sourceUri)).IsFile)
                    {
                        var httpSourceResource = await source.GetResourceAsync <HttpSourceResource>(token);

                        httpSource = httpSourceResource.HttpSource;
                    }
                    packageUpdateResource = new PackageUpdateResource(sourceUri, httpSource);
                }
                else
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
                                                                      Strings.PackageServerEndpoint_NotSupported,
                                                                      source));
                }
            }

            var result = new Tuple <bool, INuGetResource>(packageUpdateResource != null, packageUpdateResource);

            return(result);
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            DownloadResource curResource = null;

            var serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                if (!_cache.TryGetValue(source.PackageSource, out curResource))
                {
                    var registrationResource = await source.GetResourceAsync<RegistrationResourceV3>(token);

                    var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(token);

                    DataClient client = new DataClient(messageHandlerResource.MessageHandler);

                    curResource = new DownloadResourceV3(client, registrationResource);

                    _cache.TryAdd(source.PackageSource, curResource);
                }
            }

            return new Tuple<bool, INuGetResource>(curResource != null, curResource);
        }
예제 #27
0
        private async Task LoadPackages()
        {
            if (IsLoading)
            {
                // prevent concurrent loading
                return;
            }

            IsLoading    = true;
            ErrorMessage = null;
            AllPackages.Clear();
            _downloadCancelSource = new CancellationTokenSource();

            try
            {
                var versions = await _versionInfos();

                var packageMetadataResource = await _repository.GetResourceAsync <PackageMetadataResource>(_downloadCancelSource.Token);

                using (var sourceCacheContext = new SourceCacheContext())
                {
                    var query = await packageMetadataResource.GetMetadataAsync(LatestPackageInfo.Id, ShowPrerelease, ShowPrerelease, sourceCacheContext, NullLogger.Instance, _downloadCancelSource.Token);

                    query = query.OrderByDescending(p => p.Identity.Version);

                    // now show packages
                    AllPackages.AddRange(query.Select(p => CreatePackageInfo(p, _feedType, versions)));
                }

                HasFinishedLoading = true;
            }
            catch (OperationCanceledException)
            {
            }
            catch (Exception exception)
            {
                if (!(exception is FatalProtocolException) && !(exception is IOException) && !(exception is NullReferenceException))
                {
                    DiagnosticsClient.TrackException(exception);
                }
                ErrorMessage = exception.GetBaseException().Message;
            }
            finally
            {
                _downloadCancelSource = null;
                IsLoading             = false;
            }
        }
        private static async Task <ODataServiceDocumentResourceV2> CreateODataServiceDocumentResourceV2(
            SourceRepository source,
            DateTime utcNow,
            ILogger log,
            CancellationToken token)
        {
            var url = source.PackageSource.Source;
            var httpSourceResource = await source.GetResourceAsync <HttpSourceResource>(token);

            var client = httpSourceResource.HttpSource;

            // Get the service document and record the URL after any redirects.
            string lastRequestUri;

            try
            {
                lastRequestUri = await client.ProcessResponseAsync(
                    new HttpSourceRequest(() => HttpRequestMessageFactory.Create(HttpMethod.Get, url, log)),
                    response =>
                {
                    if (response.RequestMessage == null)
                    {
                        return(Task.FromResult(url));
                    }

                    return(Task.FromResult(response.RequestMessage.RequestUri.ToString()));
                },
                    log,
                    token);
            }
            catch (Exception ex) when(!(ex is FatalProtocolException) && (!(ex is OperationCanceledException)))
            {
                string message = string.Format(CultureInfo.CurrentCulture, Strings.Log_FailedToReadServiceIndex, source.PackageSource.Source);

                log.LogError(message + Environment.NewLine + ExceptionUtilities.DisplayMessage(ex));

                throw new FatalProtocolException(message, ex);
            }

            // Trim the query string or any trailing slash.
            var builder = new UriBuilder(lastRequestUri)
            {
                Query = null
            };
            var baseAddress = builder.Uri.AbsoluteUri.Trim('/');

            return(new ODataServiceDocumentResourceV2(baseAddress, DateTime.UtcNow));
        }
예제 #29
0
        private static async Task <DownloadResource> GetDownloadResource(Uri feedUrl)
        {
            DownloadResource resource;

            if (!s_downloadResourceCache.TryGetValue(feedUrl, out resource))
            {
                PackageSource    packageSource = new PackageSource(feedUrl.AbsoluteUri);
                SourceRepository repo          = new SourceRepository(packageSource, PrivateProviders.Get().Union(Repository.Provider.GetCoreV3()));

                resource = await repo.GetResourceAsync <DownloadResource>();

                s_downloadResourceCache.TryAdd(feedUrl, resource);
            }

            return(resource);
        }
        public static TestableHttpSource Create(SourceRepository source, HttpClient client)
        {
            Func <Task <HttpHandlerResource> > factory = () => source.GetResourceAsync <HttpHandlerResource>();

            var httpCacheDirectory = Path.Combine(
                Path.GetTempPath(),
                "BaGetTests",
                Guid.NewGuid().ToString("N"));

            return(new TestableHttpSource(
                       source.PackageSource,
                       factory,
                       NullThrottle.Instance,
                       client,
                       httpCacheDirectory));
        }
예제 #31
0
        public async Task <IPackage> GetPackageAsync(string id, string version, CancellationToken token)
        {
            var finder = await _repository.GetResourceAsync <FindPackageByIdResource>();

            var nugetVersion = NuGetVersion.Parse(version);

            using (var ms = new MemoryStream())
            {
                if (await finder.CopyNupkgToStreamAsync(id, nugetVersion, ms, _cache, _log, token))
                {
                    return(new NupkgPackage(id, version, ms.ToArray()));
                }

                throw new InvalidOperationException("Could not copy nupkg");
            }
        }
예제 #32
0
        public async Task <IEnumerable <IPackageSearchMetadata> > Search(string searchTerm)
        {
            List <Lazy <INuGetResourceProvider> > providers = new List <Lazy <INuGetResourceProvider> >();

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

            NuGet.Common.ILogger logger = new NullLogger();

            PackageSearchResource searchResource = await sourceRepository.GetResourceAsync <PackageSearchResource>();

            IEnumerable <IPackageSearchMetadata> searchMetadata = await searchResource.SearchAsync(searchTerm, new SearchFilter(), 0, 10, logger, CancellationToken.None);

            return(searchMetadata);
        }
예제 #33
0
        async Task LoadPlugins()
        {
            var providers = Repository.Provider.GetCoreV3();
            var source    = new PackageSource("https://api.nuget.org/v3/index.json");
            var repo      = new SourceRepository(source, providers);
            var search    = await repo.GetResourceAsync <PackageSearchResource>();

            // replace with 'guit'
            var results = await search.SearchAsync("guit", new SearchFilter(true) { SupportedFrameworks = new[] { "netstandard2.0", "netcoreapp3.0" } }, 0, 35, new Logger(), CancellationToken.None);

            plugins.SetValues(results.Where(x => x.Identity.Id != "Guit.Core" && x.Tags.Contains("guit") && !manager.EnabledPlugins.Any(p => p.Id == x.Identity.Id)));
            // TODO: this does not result in the listview being properly focused/painted :(
            Application.MainLoop.Invoke(() => SetFocus(plugins));

            done = true;
        }
        private static async Task <bool> PackageExistsInSourceRepository(
            PackageIdentity packageIdentity,
            SourceRepository sourceRepository,
            SourceCacheContext sourceCacheContext,
            ILogger logger,
            CancellationToken token)
        {
            var metadataResource = await sourceRepository.GetResourceAsync <MetadataResource>(token);

            if (metadataResource == null)
            {
                return(false);
            }

            return(await metadataResource.Exists(packageIdentity, sourceCacheContext, logger, token));
        }
예제 #35
0
        public static HttpSource Create(SourceRepository source, IThrottle throttle)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

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

            Func <Task <HttpHandlerResource> > factory = () => source.GetResourceAsync <HttpHandlerResource>();

            return(new HttpSource(source.PackageSource, factory, throttle));
        }
예제 #36
0
        private static async Task <IEnumerable <IPackageSearchMetadata> > GetListedPackages(string packageID)
        {
            List <Lazy <INuGetResourceProvider> > providers = new List <Lazy <INuGetResourceProvider> >();

            providers.AddRange(Repository.Provider.GetCoreV3());  // Add v3 API support

            PackageSource packageSource = new PackageSource(NUGET_API_SERVICE_INDEX);

            SourceRepository sourceRepository = new SourceRepository(packageSource, providers);

            PackageMetadataResource packageMetadataResource = await sourceRepository.GetResourceAsync <PackageMetadataResource>();

            IEnumerable <IPackageSearchMetadata> searchMetadata = await packageMetadataResource.GetMetadataAsync(packageID, true, true, logger, CancellationToken.None);

            return(searchMetadata);
        }
예제 #37
0
        public async Task <NuGetPackageFilterResult> FilterAsync(SourceRepository repository, IPackageSearchMetadata package, CancellationToken cancellationToken)
        {
            if (!dependencies.Any())
            {
                return(NuGetPackageFilterResult.Ok);
            }

            DependencyInfoResource resource = await repository.GetResourceAsync <DependencyInfoResource>();

            if (resource == null)
            {
                return(NuGetPackageFilterResult.NotCompatible);
            }

            NuGetPackageFilterResult result = NuGetPackageFilterResult.Ok;

            foreach (NuGetFramework framework in frameworks)
            {
                SourcePackageDependencyInfo dependencyInfo = await resource.ResolvePackage(package.Identity, framework, new SourceCacheContext(), nuGetLogger, cancellationToken);

                if (dependencyInfo != null)
                {
                    // Dependency filtering:
                    // - When incompatible dependency version is found there is a chance that previous version has the right one.
                    // - When all dependencies are missing, don't even try previous versions.
                    foreach (var dependency in dependencies)
                    {
                        PackageDependency packageDependency = dependencyInfo.Dependencies.FirstOrDefault(p => string.Equals(p.Id, dependency.Id, StringComparison.CurrentCultureIgnoreCase));
                        if (packageDependency == null)
                        {
                            log.Info($"Package '{package.Identity}' skipped: missing dependency '{dependency.Id}'.");
                            result = NuGetPackageFilterResult.NotCompatible;
                        }

                        if (dependency.Version != null && !packageDependency.VersionRange.Satisfies(new NuGetVersion(dependency.Version)))
                        {
                            log.Info($"Package '{package.Identity}' skipped: not compatible version '{dependency.Version}' on dependency '{dependency.Id}'.");
                            return(NuGetPackageFilterResult.NotCompatibleVersion);
                        }
                    }

                    return(result);
                }
            }

            return(NuGetPackageFilterResult.NotCompatible);
        }
예제 #38
0
        private async Task <IPackageSearchMetadata> SearchPackageAsync(string packageName, string version, bool includePrerelease,
                                                                       SourceRepository sourceRepository)
        {
            var packageMetadataResource = await sourceRepository.GetResourceAsync <PackageMetadataResource>();

            var sourceCacheContext = new SourceCacheContext();

            IPackageSearchMetadata packageMetaData = null;

            if (!string.IsNullOrEmpty(version) && !version.Contains('*'))
            {
                if (NuGetVersion.TryParse(version, out var nugetversion))
                {
                    var packageIdentity = new PackageIdentity(packageName, NuGetVersion.Parse(version));

                    packageMetaData = await packageMetadataResource.GetMetadataAsync(
                        packageIdentity,
                        sourceCacheContext,
                        _logger,
                        CancellationToken.None);
                }
            }
            else
            {
                // Can't use await as we seem to lose the thread
                var searchResults = packageMetadataResource.GetMetadataAsync(
                    packageName,
                    includePrerelease,
                    includeUnlisted: false,
                    sourceCacheContext,
                    _logger,
                    CancellationToken.None).Result;

                searchResults = searchResults
                                .OrderByDescending(p => p.Identity.Version);

                if (!string.IsNullOrEmpty(version))
                {
                    var searchPattern = version.Replace("*", ".*");
                    searchResults = searchResults.Where(p => Regex.IsMatch(p.Identity.Version.ToString(), searchPattern));
                }

                packageMetaData = searchResults.FirstOrDefault();
            }

            return(packageMetaData);
        }
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token)
        {
            RepositorySignatureResource resource = null;
            var serviceIndex = await source.GetResourceAsync <ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                var repoSignUrl = serviceIndex.GetServiceEntryUri(ServiceTypes.RepositorySignatures);

                if (repoSignUrl != null)
                {
                    resource = await GetRepositorySignatureResourceAsync(source, repoSignUrl.AbsoluteUri, NullLogger.Instance, token);
                }
            }

            return(new Tuple <bool, INuGetResource>(resource != null, resource));
        }
        public async Task <IEnumerable <NugetPackageDto> > GetNugetPackagesImperative(string term)
        {
            var sources   = Repository.Provider.GetCoreV3();
            var providers = new List <Lazy <INuGetResourceProvider> >();

            providers.AddRange(Repository.Provider.GetCoreV3());
            var packageSource = new PackageSource("https://api.nuget.org/v3/index.json");
            var source        = new SourceRepository(packageSource, providers);

            var filter   = new SearchFilter(false);
            var resource = await source.GetResourceAsync <PackageSearchResource>().ConfigureAwait(false);

            var metadata = await resource.SearchAsync(term, filter, 0, 10, null, new CancellationToken())
                           .ConfigureAwait(false);

            return(metadata.Select(x => new NugetPackageDto(x)));
        }
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            ReportAbuseResourceV3 resource = null;
            var serviceIndex = await source.GetResourceAsync<ServiceIndexResourceV3>(token);
            if (serviceIndex != null)
            {
                resource = new ReportAbuseResourceV3();

                //IEnumerable<Uri> templateUrls = serviceIndex[ServiceTypes.ReportAbuse];
                //if (templateUrls != null && templateUrls.Any())
                //{
                //    resource = new ReportAbuseResourceV3(templateUrls);
                //}
            }

            return new Tuple<bool, INuGetResource>(resource != null, resource);
        }
예제 #42
0
        public static async Task <IEnumerable <NuGetVersion> > VersionStartsWithAsync(
            this SourceRepository sourceRepository, string packageId, string versionPrefix, bool includePrerelease, CancellationToken cancellationToken)
        {
            var autoCompleteResource = await sourceRepository.GetResourceAsync <AutoCompleteResource> (cancellationToken);

            using (var sourceCacheContext = new SourceCacheContext()) {
                var versions = await autoCompleteResource?.VersionStartsWith(
                    packageId,
                    versionPrefix,
                    includePrerelease : includePrerelease,
                    sourceCacheContext : sourceCacheContext,
                    log : Common.NullLogger.Instance,
                    token : cancellationToken);

                return(versions ?? Enumerable.Empty <NuGetVersion> ());
            }
        }
예제 #43
0
        public static async Task CheckResultsAgainstTemplate(LibraryRange[] package, IReadOnlyList <NuGetFramework> frameworks, [CallerFilePath] string filePath = null, [CallerMemberName] string memberName = null)
        {
            var sourceRepository = new SourceRepository(new PackageSource(NuGetPackageHelper.DefaultNuGetSource), NuGetPackageHelper.Providers);
            var findResource     = await sourceRepository.GetResourceAsync <FindPackageByIdResource>().ConfigureAwait(false);

            var bestPackageIdentity = await NuGetPackageHelper.GetBestMatch(package[0], findResource, CancellationToken.None).ConfigureAwait(false);

            using (var memoryStream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8, 1024, true))
                {
                    await ObservablesForEventGenerator.ExtractEventsFromNuGetPackages(streamWriter, package, frameworks, TestUtilities.GetPackageDirectory(memberName, filePath)).ConfigureAwait(false);
                }

                CheckPackageIdentityContents(memoryStream, bestPackageIdentity, frameworks[0], filePath);
            }
        }
예제 #44
0
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository source, CancellationToken token)
        {
            RepositorySignatureResource resource = null;
            var serviceIndex = await source.GetResourceAsync <ServiceIndexResourceV3>(token);

            if (serviceIndex != null)
            {
                var serviceEntry = serviceIndex.GetServiceEntries(ServiceTypes.RepositorySignatures).FirstOrDefault();

                if (serviceEntry != null)
                {
                    resource = await GetRepositorySignatureResourceAsync(source, serviceEntry, NullLogger.Instance, token);
                }
            }

            return(new Tuple <bool, INuGetResource>(resource != null, resource));
        }
예제 #45
0
        public override async Task <Tuple <bool, INuGetResource> > TryCreate(SourceRepository sourceRepository, CancellationToken token)
        {
            INuGetResource resource = null;

            if (sourceRepository.PackageSource.IsHttp
                &&
                !sourceRepository.PackageSource.Source.EndsWith("json", StringComparison.OrdinalIgnoreCase))
            {
                var httpSourceResource = await sourceRepository.GetResourceAsync <HttpSourceResource>(token);

                resource = new RemoteV2FindPackageByIdResource(
                    sourceRepository.PackageSource,
                    httpSourceResource.HttpSource);
            }

            return(Tuple.Create(resource != null, resource));
        }
예제 #46
0
        /// <summary>
        /// Gets latest version of nuget package
        /// </summary>
        /// <param name="packageId"></param>
        /// <returns><see cref="NuGetVersion"/> will be returned if package is found; otherwise <see langword="null"></see></returns>
        public static async Task <NuGetVersion> GetLatestVersionOfPackage(string packageId)
        {
            ILogger           logger            = NullLogger.Instance;
            CancellationToken cancellationToken = CancellationToken.None;

            SourceCacheContext      cache      = new SourceCacheContext();
            SourceRepository        repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
            FindPackageByIdResource resource   = await repository.GetResourceAsync <FindPackageByIdResource>();

            IEnumerable <NuGetVersion> versions = await resource.GetAllVersionsAsync(
                packageId,
                cache,
                logger,
                cancellationToken);

            return(versions.LastOrDefault());
        }
        public static async Task <string?> FindNewestPackageVersion(string package, bool includePrerelease)
        {
            Logger logger = new Logger();
            List <Lazy <INuGetResourceProvider> > providers = new List <Lazy <INuGetResourceProvider> >();

            providers.AddRange(Repository.Provider.GetCoreV3());  // Add v3 API support
            //providers.AddRange(Repository.Provider.GetCoreV2());  // Add v2 API support
            PackageSource           packageSource           = new PackageSource("https://api.nuget.org/v3/index.json");
            SourceRepository        sourceRepository        = new SourceRepository(packageSource, providers);
            PackageMetadataResource packageMetadataResource = await sourceRepository.GetResourceAsync <PackageMetadataResource>();

            IEnumerable <IPackageSearchMetadata> searchMetadata = await packageMetadataResource.GetMetadataAsync(package, true, true, logger, CancellationToken.None);

            NuGetVersion?newest = null;

            foreach (var item in searchMetadata)
            {
                if (item is PackageSearchMetadata itemMetadata)
                {
                    var version = itemMetadata.Version;
                    if (!itemMetadata.IsListed)
                    {
                        continue;
                    }
                    if (version.IsPrerelease && !includePrerelease)
                    {
                        continue;
                    }
                    if (newest == null)
                    {
                        newest = version;
                        continue;
                    }
                    if (version.CompareTo(newest.Version) > 0)
                    {
                        newest = version;
                    }
                }
            }
            if (newest == null)
            {
                return(null);
            }
            return(newest.ToNormalizedString());
        }
        private async Task EnsureResource()
        {
            if (_findPackagesByIdResource == null)
            {
                FindPackageByIdResource resource = await _sourceRepository.GetResourceAsync <FindPackageByIdResource>();

                resource.Logger       = _logger;
                resource.CacheContext = _cacheContext;

                lock (_lock)
                {
                    if (_findPackagesByIdResource == null)
                    {
                        _findPackagesByIdResource = resource;
                    }
                }
            }
        }
예제 #49
0
        public static async IAsyncEnumerable <IPackageSearchMetadata> SearchPackagesByIdAsync(
            this SourceRepository repository,
            string packageId,
            bool includePrerelease,
            NuGet.Common.ILogger?logger,
            int batchSize = 50,
            [EnumeratorCancellation] CancellationToken cancellationToken = default
            )
        {
            var searchResource = await repository.GetResourceAsync <PackageSearchResource>();

            await foreach (var metadata in searchResource
                           .SearchPackagesByIdAsync(packageId, includePrerelease, logger)
                           .WithCancellation(cancellationToken))
            {
                yield return(metadata);
            }
        }
        // TODO: refresh the file when it gets old
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            ServiceIndexResourceV3 index = null;

            string url = source.PackageSource.Source;

            // the file type can easily rule out if we need to request the url
            if (url.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
            {
                // check the cache before downloading the file
                if (!_cache.TryGetValue(url, out index))
                {
                    var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(token);

                    DataClient client = new DataClient(messageHandlerResource.MessageHandler);

                    JObject json = await client.GetJObjectAsync(new Uri(url), token);

                    if (json != null)
                    {
                        // Use SemVer instead of NuGetVersion, the service index should always be
                        // in strict SemVer format
                        SemanticVersion version = null;
                        var status = json.Value<string>("version");
                        if (status != null && SemanticVersion.TryParse(status, out version))
                        {
                            if (version.Major == 3)
                            {
                                index = new ServiceIndexResourceV3(json, DateTime.UtcNow);
                            }
                        }
                    }
                }

                // cache the value even if it is null to avoid checking it again later
                _cache.TryAdd(url, index);
            }

            return new Tuple<bool, INuGetResource>(index != null, index);
        }
		async Task<PackageIdentity> GetUpdates (SourceRepository sourceRepository, PackageReference packageReference)
		{
			var metadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource> (cancellationToken);

			if (metadataResource == null)
				return null;

			var packages = await metadataResource.GetMetadataAsync (
				packageReference.PackageIdentity.Id,
				includePrerelease: packageReference.PackageIdentity.Version.IsPrerelease,
				includeUnlisted: false,
				log: NullLogger.Instance,
				token: cancellationToken);

			var package = packages
				.Where (p => IsPackageVersionAllowed (p, packageReference))
				.OrderByDescending (p => p.Identity.Version).FirstOrDefault ();
			if (package == null)
				return null;

			if (package.Identity.Version > packageReference.PackageIdentity.Version)
				return package.Identity;

			return null;
		}
예제 #52
0
파일: Package.cs 프로젝트: ibebbs/Wyam
 private async Task<NuGetVersion> GetLatestMatchingVersion(SourceRepository sourceRepository, ILogger logger)
 {
     try
     {
         DependencyInfoResource dependencyInfoResource = await sourceRepository.GetResourceAsync<DependencyInfoResource>();
         IEnumerable<SourcePackageDependencyInfo> dependencyInfo = await dependencyInfoResource.ResolvePackages(
             _packageId, _currentFramework, logger, CancellationToken.None);
         return dependencyInfo
             .Select(x => x.Version)
             .Where(x => x != null && (_versionRange == null || _versionRange.Satisfies(x)))
             .DefaultIfEmpty()
             .Max();
     }
     catch (Exception ex)
     {
         Trace.Warning($"Could not get latest version for package {_packageId} from source {sourceRepository}: {ex.Message}");
         return null;
     }
 }
        private static async Task<NuGetVersion> GetLatestVersionCoreAsync(string packageId, ResolutionContext resolutionContext, SourceRepository source, CancellationToken token)
        {
            NuGetVersion latestVersion = null;

            var metadataResource = await source.GetResourceAsync<MetadataResource>();

            if (metadataResource != null)
            {
                latestVersion = await metadataResource.GetLatestVersion(packageId,
                    resolutionContext.IncludePrerelease, resolutionContext.IncludeUnlisted, token);
            }

            return latestVersion;
        }
        // TODO: refresh the file when it gets old
        public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            ServiceIndexResourceV3 index = null;

            var url = source.PackageSource.Source;

            // the file type can easily rule out if we need to request the url
            if (source.PackageSource.ProtocolVersion == 3 ||
                (source.PackageSource.IsHttp &&
                url.EndsWith(".json", StringComparison.OrdinalIgnoreCase)))
            {
                ServiceIndexCacheInfo cacheInfo;
                // check the cache before downloading the file
                if (!_cache.TryGetValue(url, out cacheInfo) ||
                    UtcNow - cacheInfo.CachedTime > MaxCacheDuration)
                {
                    var messageHandlerResource = await source.GetResourceAsync<HttpHandlerResource>(token);

                    var client = new DataClient(messageHandlerResource.MessageHandler);

                    JObject json;

                    try
                    {
                        json = await client.GetJObjectAsync(new Uri(url), token);
                    }
                    catch (JsonReaderException)
                    {
                        _cache.TryAdd(url, new ServiceIndexCacheInfo { CachedTime = UtcNow });
                        return new Tuple<bool, INuGetResource>(false, null);
                    }
                    catch (HttpRequestException)
                    {
                        _cache.TryAdd(url, new ServiceIndexCacheInfo { CachedTime = UtcNow });
                        return new Tuple<bool, INuGetResource>(false, null);
                    }

                    if (json != null)
                    {
                        // Use SemVer instead of NuGetVersion, the service index should always be
                        // in strict SemVer format
                        SemanticVersion version;
                        JToken versionToken;
                        if (json.TryGetValue("version", out versionToken) &&
                            versionToken.Type == JTokenType.String &&
                            SemanticVersion.TryParse((string)versionToken, out version) &&
                            version.Major == 3)
                        {
                            index = new ServiceIndexResourceV3(json, UtcNow);
                        }
                    }
                }
                else
                {
                    index = cacheInfo.Index;
                }

                // cache the value even if it is null to avoid checking it again later
                _cache.TryAdd(url, new ServiceIndexCacheInfo { CachedTime = UtcNow, Index = index });
            }

            return new Tuple<bool, INuGetResource>(index != null, index);
        }