|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Linq; |
| 7 | + |
| 8 | +namespace NuGetGallery |
| 9 | +{ |
| 10 | + public class GitHubUsageConfiguration : IGitHubUsageConfiguration |
| 11 | + { |
| 12 | + private readonly IReadOnlyDictionary<string, NuGetPackageGitHubInformation> _nuGetPackagesGitHubDependencies; |
| 13 | + |
| 14 | + public GitHubUsageConfiguration(IReadOnlyCollection<RepositoryInformation> repositories) |
| 15 | + { |
| 16 | + if (repositories == null) |
| 17 | + { |
| 18 | + throw new ArgumentNullException(nameof(repositories)); |
| 19 | + } |
| 20 | + |
| 21 | + _nuGetPackagesGitHubDependencies = GetNuGetPackagesDependents(repositories); |
| 22 | + } |
| 23 | + |
| 24 | + public NuGetPackageGitHubInformation GetPackageInformation(string packageId) |
| 25 | + { |
| 26 | + if (packageId == null) |
| 27 | + { |
| 28 | + throw new ArgumentNullException(nameof(packageId)); |
| 29 | + } |
| 30 | + |
| 31 | + if (_nuGetPackagesGitHubDependencies.TryGetValue(packageId, out var value)) |
| 32 | + { |
| 33 | + return value; |
| 34 | + } |
| 35 | + |
| 36 | + return NuGetPackageGitHubInformation.Empty; |
| 37 | + } |
| 38 | + |
| 39 | + private static IReadOnlyDictionary<string, NuGetPackageGitHubInformation> GetNuGetPackagesDependents(IReadOnlyCollection<RepositoryInformation> repositories) |
| 40 | + { |
| 41 | + var dependentsPerPackage = new Dictionary<string, List<RepositoryInformation>>(StringComparer.OrdinalIgnoreCase); |
| 42 | + foreach (var repo in repositories) |
| 43 | + { |
| 44 | + foreach (var dependency in repo.Dependencies) |
| 45 | + { |
| 46 | + if (!dependentsPerPackage.TryGetValue(dependency, out var packageDependents)) |
| 47 | + { |
| 48 | + packageDependents = new List<RepositoryInformation>(); |
| 49 | + dependentsPerPackage[dependency] = packageDependents; |
| 50 | + } |
| 51 | + |
| 52 | + packageDependents.Add(repo); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return dependentsPerPackage |
| 57 | + .ToDictionary( |
| 58 | + entry => entry.Key, |
| 59 | + entry => new NuGetPackageGitHubInformation(entry.Value), |
| 60 | + StringComparer.OrdinalIgnoreCase); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments