Esempio n. 1
0
        public async Task <PackageSearchResults> Search(string query, PackageSearchOptions options, Uri source = null)
        {
            await _progressService.StartLoading("Search");

            _progressService.WriteMessage(string.Format("Searching for {0}", query));

            if (source == null)
            {
                source = new Uri(_sourceService.GetDefaultSource().Url);
            }

            if (source.Scheme == "http" || source.Scheme == "https")
            {
                var results = await ODataPackageService.Search(query, _packageFactory, options, source);

                await _progressService.StopLoading();

                return(results);
            }

            if (source.IsFile || source.IsUnc)
            {
                await _progressService.StopLoading();

                return(null);
            }
            throw new InvalidDataException("Invalid Source Uri. Double check that you current source is a valid endpoint.");
        }
        public async Task <PackageResults> Search(string query, PackageSearchOptions options)
        {
            using (await Lock.ReadLockAsync())
            {
                var choco = Lets.GetChocolatey().SetCustomLogging(new SerilogLogger(Logger, _progressService));
                choco.Set(
                    config =>
                {
                    config.CommandName          = CommandNameType.list.ToString();
                    config.Input                = query;
                    config.AllVersions          = options.IncludeAllVersions;
                    config.ListCommand.Page     = options.CurrentPage;
                    config.ListCommand.PageSize = options.PageSize;
                    if (string.IsNullOrWhiteSpace(query) || !string.IsNullOrWhiteSpace(options.SortColumn))
                    {
                        config.ListCommand.OrderByPopularity = string.IsNullOrWhiteSpace(options.SortColumn) ||
                                                               options.SortColumn == "DownloadCount";
                    }
                    config.ListCommand.Exact = options.MatchQuery;
                    if (!string.IsNullOrWhiteSpace(options.Source))
                    {
                        config.Sources = options.Source;
                    }
#if !DEBUG
                    config.Verbose = false;
#endif // DEBUG
                });

                var packages =
                    (await choco.ListAsync <PackageResult>()).Select(
                        pckge => GetMappedPackage(choco, pckge, _mapper));

                return(new PackageResults
                {
                    Packages = packages.ToArray(),
                    TotalCount = await Task.Run(() => choco.ListCount())
                });
            }
        }
Esempio n. 3
0
        public async Task <PackageResults> Search(string query, PackageSearchOptions options)
        {
            _choco.Set(
                config =>
            {
                config.CommandName           = CommandNameType.list.ToString();
                config.Input                 = query;
                config.AllVersions           = options.IncludeAllVersions;
                config.ListCommand.Page      = options.CurrentPage;
                config.ListCommand.PageSize  = options.PageSize;
                config.Prerelease            = options.IncludePrerelease;
                config.ListCommand.LocalOnly = false;
                if (string.IsNullOrWhiteSpace(query) || !string.IsNullOrWhiteSpace(options.SortColumn))
                {
                    config.ListCommand.OrderByPopularity = string.IsNullOrWhiteSpace(options.SortColumn) ||
                                                           options.SortColumn == "DownloadCount";
                }
                config.ListCommand.Exact = options.MatchQuery;
                if (!string.IsNullOrWhiteSpace(options.Source))
                {
                    config.Sources = options.Source;
                }
#if !DEBUG
                config.Verbose = false;
#endif // DEBUG
            });

            var packages =
                (await _choco.ListAsync <PackageResult>()).Select(
                    pckge => GetMappedPackage(_choco, pckge, _mapper));

            return(new PackageResults
            {
                Packages = packages.ToArray(),
                TotalCount = await Task.Run(() => _choco.ListCount())
            });
        }
Esempio n. 4
0
        public async Task <IEnumerable <NuGetReference> > GetNewerVersionsAsync(NuGetReference reference, IEnumerable <TargetFrameworkMoniker> tfms, PackageSearchOptions options, CancellationToken token)
        {
            if (_packages.TryGetValue(reference.Name, out var known))
            {
                return(new NuGetReference[] { known });
            }

            var latest = await _other.GetNewerVersionsAsync(reference, tfms, options, token).ConfigureAwait(false);

            if (latest is not null && latest.LastOrDefault() is NuGetReference latestReference)
            {
                _unknownPackages[latestReference.Name] = latestReference.Version;
                _logger.LogError("Unexpected check for newer version: {Name}, {Version}", reference.Name, reference.Version);
            }

            return(latest ?? Enumerable.Empty <NuGetReference>());
        }
Esempio n. 5
0
        public async Task <NuGetReference?> GetLatestVersionAsync(string packageName, IEnumerable <TargetFrameworkMoniker> tfms, PackageSearchOptions options, CancellationToken token)
        {
            if (_packages.TryGetValue(packageName, out var known))
            {
                return(known);
            }

            var latest = await _other.GetLatestVersionAsync(packageName, tfms, options, token).ConfigureAwait(false);

            if (latest is not null)
            {
                _unknownPackages[packageName] = latest.Version;
                _logger.LogError("Unexpected version: {Name}, {Version}", latest.Name, latest.Version);
            }

            return(latest);
        }
Esempio n. 6
0
 private static string GetMemoryCacheKey(Uri source, string query, PackageSearchOptions options)
 {
     return(string.Format(CultureInfo.CurrentCulture, "FileSystemPackageService.QueryResult.{0}|{1}|{2}|{3}", source, query, options.IncludeAllVersions, options.IncludePrerelease));
 }
        public static async Task <PackageSearchResults> Search(string queryString, IChocolateyService chocolateyService, Func <IPackageViewModel> packageFactory, PackageSearchOptions options, Uri source)
        {
            List <IPackageViewModel> packages;

            if ((packages = (List <IPackageViewModel>)Cache.Get(GetMemoryCacheKey(source, queryString, options))) == null)
            {
                var queryCommand = string.Format("list {0} {1} {2} -source \"{3}\"", queryString,
                                                 options.IncludePrerelease ? "-pre" : "", options.IncludeAllVersions ? "-all" : "", source);

                var chocoPackageList = (await chocolateyService.RunIndirectChocolateyCommand(queryCommand, false))
                                       .ToDictionary(o => o.ToString().Split(' ')[0], o => o.ToString().Split(' ')[1]);

                packages = (await chocolateyService.GetPackagesFromLocalDirectory(chocoPackageList, source.ToString())).ToList();

                Cache.Set(GetMemoryCacheKey(source, queryString, options), packages, new CacheItemPolicy
                {
                    AbsoluteExpiration = DateTime.Now.AddHours(1)
                });
            }

            IQueryable <IPackageViewModel> query = packages.AsQueryable();

            if (!string.IsNullOrWhiteSpace(options.SortColumn))
            {
                query = options.SortDescending
                    ? query.OrderByDescending(options.SortColumn)
                    : query.OrderBy(options.SortColumn);
            }

            return(new PackageSearchResults
            {
                Packages = query.Skip(options.CurrentPage * options.PageSize).Take(options.PageSize),
                TotalCount = packages.Count
            });
        }
Esempio n. 8
0
        private async Task <IEnumerable <NuGetReference> > SearchByNameAsync(string name, IEnumerable <TargetFrameworkMoniker> tfms, PackageSearchOptions options, NuGetVersion?currentVersion = null, IEnumerable <PackageSource>?sources = null, CancellationToken token = default)
        {
            var results = new List <IPackageSearchMetadata>();

            if (sources is null)
            {
                sources = _packageSource;
            }

            foreach (var source in sources)
            {
                try
                {
                    var metadata = await GetSourceRepository(source).GetResourceAsync <PackageMetadataResource>(token).ConfigureAwait(false);

                    var searchResults = await CallWithRetryAsync(() => metadata.GetMetadataAsync(name, includePrerelease: options.Prerelease, includeUnlisted: options.Unlisted, _context, _nugetLogger, token)).ConfigureAwait(false);

                    results.AddRange(searchResults);
                }
                catch (NuGetProtocolException)
                {
                    _logger.LogWarning("Failed to get package versions from source {PackageSource} due to a NuGet protocol error", source.Source);
                    _logger.LogInformation("If NuGet packages are coming from an authenticated source, Upgrade Assistant requires a .NET Core-compatible v2 credential provider be installed. To authenticate with an Azure DevOps NuGet source, for example, see https://github.com/microsoft/artifacts-credprovider#setup");
                }
                catch (HttpRequestException exc)
                {
                    _logger.LogWarning("Failed to get package versions from source {PackageSource} due to an HTTP error ({StatusCode})", source.Source, exc.StatusCode);
                }
            }

            return(FilterSearchResults(name, results, tfms, currentVersion, options.LatestMinorAndBuildOnly));
        }
Esempio n. 9
0
        private async Task <NuGetReference?> GetLatestVersionAsync(string packageName, IEnumerable <TargetFrameworkMoniker> tfms, PackageSearchOptions options, IEnumerable <PackageSource>?sources, CancellationToken token)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var result = await SearchByNameAsync(packageName, tfms, options, null, sources, token : token).ConfigureAwait(false);

            return(result.LastOrDefault());
        }
Esempio n. 10
0
 public Task <NuGetReference?> GetLatestVersionAsync(string packageName, IEnumerable <TargetFrameworkMoniker> tfms, PackageSearchOptions options, CancellationToken token)
 => GetLatestVersionAsync(packageName, tfms, options, default, token);
Esempio n. 11
0
        public Task <IEnumerable <NuGetReference> > GetNewerVersionsAsync(NuGetReference reference, IEnumerable <TargetFrameworkMoniker> tfms, PackageSearchOptions options, CancellationToken token)
        {
            if (reference is null)
            {
                throw new ArgumentNullException(nameof(reference));
            }

            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(SearchByNameAsync(reference.Name, tfms, options, currentVersion: reference.GetNuGetVersion(), _packageSource, token: token));
        }
Esempio n. 12
0
        public static async Task <PackageSearchResults> Search(string query, Func <IPackageViewModel> packageFactory, PackageSearchOptions options, Uri source)
        {
            var service     = GetFeed(source);
            var queryString = query;
            IQueryable <V2FeedPackage> feedQuery = service.Packages.Where(package => package.IsPrerelease == options.IncludePrerelease || package.IsPrerelease == false);

            if (!options.IncludeAllVersions)
            {
                feedQuery = feedQuery.Where(package => package.IsLatestVersion || package.IsAbsoluteLatestVersion);
            }

            if (!string.IsNullOrWhiteSpace(queryString))
            {
                feedQuery = options.MatchQuery ?
                            feedQuery.Where(package => package.Id == queryString || package.Title == queryString) :
                            feedQuery.Where(package => package.Id.Contains(queryString) || package.Title.Contains(queryString));
            }

            var totalCount = feedQuery.Count();

            if (!string.IsNullOrWhiteSpace(options.SortColumn))
            {
                feedQuery = !options.SortDescending ? feedQuery.OrderBy(options.SortColumn) : feedQuery.OrderByDescending(options.SortColumn);
            }

            feedQuery = feedQuery.Skip(options.CurrentPage * options.PageSize).Take(options.PageSize);
            var feedDataServiceQuery = (DataServiceQuery <V2FeedPackage>)feedQuery;
            var result = await Task.Factory.FromAsync(feedDataServiceQuery.BeginExecute, ar => feedDataServiceQuery.EndExecute(ar), null);

            var packages = result.Select(package => AutoMapper.Mapper.Map(package, packageFactory()));

            return(new PackageSearchResults
            {
                TotalCount = totalCount,
                Packages = packages
            });
        }