From c624fb6b8b533806e9c14b2060f2d8ef5cf4fb21 Mon Sep 17 00:00:00 2001 From: Simon Ensslen Date: Wed, 2 Nov 2022 12:36:59 +0100 Subject: [PATCH] Use local cache to retreive package information (#156) --- .../LicenseDownloadException.cs | 5 +- .../LicenseValidationResult.cs | 4 +- .../LicenseValidator/LicenseValidator.cs | 17 +- src/NuGetUtility/NuGetUtility.csproj | 10 +- .../Output/Json/JsonOutputFormatter.cs | 6 +- .../Output/Json/NuGetVersionJsonConverter.cs | 20 --- .../Output/Table/TableOutputFormatter.cs | 23 ++- src/NuGetUtility/Output/Table/TablePrinter.cs | 31 ++-- .../Output/Table/TablePrinterExtensions.cs | 4 +- .../CustomPackageInformation.cs | 4 +- .../PackageInformationReader.cs | 98 ++++++---- .../PackageMetadata.cs | 33 ++++ .../PackageMetadataWithLicenseInformation.cs | 75 -------- .../ProjectWithReferencedPackages.cs | 4 +- .../ReferencedPackageWithContext.cs | 4 +- src/NuGetUtility/Program.cs | 31 ++-- .../ReferencedPackageReader.cs | 16 +- .../Serialization/NuGetVersionConverter.cs | 25 --- .../NuGetVersionJsonConverter.cs | 30 ++++ ...JsonConverterWithOmittingEmptyErrorList.cs | 4 +- .../Packaging/Core/PackageIdentity.cs | 4 +- .../Packaging/IPackageMetadata.cs | 15 ++ .../NuGetWrapper/Packaging/LicenseMetadata.cs | 21 +++ .../NuGetWrapper/Packaging/LicenseType.cs | 8 + .../CachingDisposableSourceRepository.cs | 2 +- .../Types/CachingPackageMetadataResource.cs | 39 +++- .../Core/Types/IDisposableSourceRepository.cs | 5 +- .../Core/Types/IPackageMetadataResource.cs | 7 +- .../Types/IPackageSearchMetadataBuilder.cs | 9 - .../IPackageSearchMetadataBuilderFactory.cs | 9 - .../Protocol/Core/Types/ISourceRepository.cs | 7 + .../Types/IWrappedSourceRepositoryProvider.cs | 4 +- .../PackageSearchMetadataBuilderFactory.cs | 19 -- .../WrappedPackageSearchMetadataBuilder.cs | 19 -- .../Types/WrappedSourceRepositoryProvider.cs | 20 ++- .../Protocol/GlobalPackagesFolderUtility.cs | 38 ++++ .../Protocol/IGlobalPackagesFolderUtility.cs | 10 ++ .../Protocol/WrappedPackageMetadata.cs | 33 ++++ .../Versioning/WrappedNuGetVersion.cs | 13 +- .../NuGet/Versioning/NuGetVersionBuilder.cs | 21 ++- .../Types/PackageMetadataWithVersionInfo.cs | 80 --------- .../Core/Types/PackageSearchMetadataMock.cs | 64 ------- .../LicenseValidator/LicenseValidatorTest.cs | 64 +++---- .../NuGetUtility.Test.csproj | 22 +-- tests/NuGetUtility.Test/Output/TestBase.cs | 19 +- .../PackageInformationReaderTest.cs | 170 ++++++++---------- .../ReferencedPackageReaderTest.cs | 131 ++++++-------- ...ReferencedPackagesReaderIntegrationTest.cs | 8 +- 48 files changed, 607 insertions(+), 698 deletions(-) delete mode 100644 src/NuGetUtility/Output/Json/NuGetVersionJsonConverter.cs create mode 100644 src/NuGetUtility/PackageInformationReader/PackageMetadata.cs delete mode 100644 src/NuGetUtility/PackageInformationReader/PackageMetadataWithLicenseInformation.cs delete mode 100644 src/NuGetUtility/Serialization/NuGetVersionConverter.cs create mode 100644 src/NuGetUtility/Serialization/NuGetVersionJsonConverter.cs rename src/NuGetUtility/{Output/Json => Serialization}/ValidatedLicenseJsonConverterWithOmittingEmptyErrorList.cs (94%) create mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/IPackageMetadata.cs create mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/LicenseMetadata.cs create mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/LicenseType.cs delete mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageSearchMetadataBuilder.cs delete mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageSearchMetadataBuilderFactory.cs create mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/ISourceRepository.cs delete mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/PackageSearchMetadataBuilderFactory.cs delete mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/WrappedPackageSearchMetadataBuilder.cs create mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/GlobalPackagesFolderUtility.cs create mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/IGlobalPackagesFolderUtility.cs create mode 100644 src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/WrappedPackageMetadata.cs delete mode 100644 tests/NuGetUtility.Test/Helper/NuGet/Protocol/Core/Types/PackageMetadataWithVersionInfo.cs delete mode 100644 tests/NuGetUtility.Test/Helper/NuGet/Protocol/Core/Types/PackageSearchMetadataMock.cs diff --git a/src/NuGetUtility/LicenseValidator/LicenseDownloadException.cs b/src/NuGetUtility/LicenseValidator/LicenseDownloadException.cs index 8316a0f0..74b43e99 100644 --- a/src/NuGetUtility/LicenseValidator/LicenseDownloadException.cs +++ b/src/NuGetUtility/LicenseValidator/LicenseDownloadException.cs @@ -1,4 +1,4 @@ -using NuGet.Packaging.Core; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; namespace NuGetUtility.LicenseValidator { @@ -8,6 +8,7 @@ public LicenseDownloadException(Exception inner, string context, PackageIdentity : base( $"Failed to download license for package {packageInfo.Id} ({packageInfo.Version}).\nContext: {context}", - inner) { } + inner) + { } } } diff --git a/src/NuGetUtility/LicenseValidator/LicenseValidationResult.cs b/src/NuGetUtility/LicenseValidator/LicenseValidationResult.cs index 48d93e8c..00705ac4 100644 --- a/src/NuGetUtility/LicenseValidator/LicenseValidationResult.cs +++ b/src/NuGetUtility/LicenseValidator/LicenseValidationResult.cs @@ -1,9 +1,9 @@ -using NuGet.Versioning; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; namespace NuGetUtility.LicenseValidator { public record LicenseValidationResult(string PackageId, - NuGetVersion PackageVersion, + INuGetVersion PackageVersion, string? PackageProjectUrl, string? License, LicenseInformationOrigin LicenseInformationOrigin, diff --git a/src/NuGetUtility/LicenseValidator/LicenseValidator.cs b/src/NuGetUtility/LicenseValidator/LicenseValidator.cs index 19ed9ee3..c8522b8a 100644 --- a/src/NuGetUtility/LicenseValidator/LicenseValidator.cs +++ b/src/NuGetUtility/LicenseValidator/LicenseValidator.cs @@ -1,8 +1,7 @@ -using NuGet.Packaging; -using NuGet.Protocol.Core.Types; -using NuGet.Versioning; using NuGetUtility.PackageInformationReader; using NuGetUtility.Wrapper.HttpClientWrapper; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; using System.Collections.Concurrent; namespace NuGetUtility.LicenseValidator @@ -49,7 +48,7 @@ public async Task> Validate( private void AddOrUpdateLicense( ConcurrentDictionary result, - IPackageSearchMetadata info, + IPackageMetadata info, LicenseInformationOrigin origin, ValidationError error, string? license = null) @@ -68,7 +67,7 @@ private void AddOrUpdateLicense( private void AddOrUpdateLicense( ConcurrentDictionary result, - IPackageSearchMetadata info, + IPackageMetadata info, LicenseInformationOrigin origin, string? license = null) { @@ -101,7 +100,7 @@ private LicenseValidationResult CreateResult(LicenseNameAndVersion _, LicenseVal return newValue; } - private void ValidateLicenseByMetadata(IPackageSearchMetadata info, + private void ValidateLicenseByMetadata(IPackageMetadata info, string context, ConcurrentDictionary result) { @@ -137,11 +136,11 @@ private void ValidateLicenseByMetadata(IPackageSearchMetadata info, } } - private async Task ValidateLicenseByUrl(IPackageSearchMetadata info, + private async Task ValidateLicenseByUrl(IPackageMetadata info, string context, ConcurrentDictionary result) { - if (info.LicenseUrl.IsAbsoluteUri) + if (info.LicenseUrl!.IsAbsoluteUri) { try { @@ -212,6 +211,6 @@ private string GetLicenseNotAllowedMessage(string license) return $"License {license} not found in list of supported licenses"; } - private record LicenseNameAndVersion(string LicenseName, NuGetVersion Version); + private record LicenseNameAndVersion(string LicenseName, INuGetVersion Version); } } diff --git a/src/NuGetUtility/NuGetUtility.csproj b/src/NuGetUtility/NuGetUtility.csproj index d3ca0c3c..8fbdc3c0 100644 --- a/src/NuGetUtility/NuGetUtility.csproj +++ b/src/NuGetUtility/NuGetUtility.csproj @@ -24,11 +24,11 @@ - - - - - + + + + + diff --git a/src/NuGetUtility/Output/Json/JsonOutputFormatter.cs b/src/NuGetUtility/Output/Json/JsonOutputFormatter.cs index 5d47f1e6..f3717da8 100644 --- a/src/NuGetUtility/Output/Json/JsonOutputFormatter.cs +++ b/src/NuGetUtility/Output/Json/JsonOutputFormatter.cs @@ -1,4 +1,5 @@ -using NuGetUtility.LicenseValidator; +using NuGetUtility.LicenseValidator; +using NuGetUtility.Serialization; using System.Text.Json; namespace NuGetUtility.Output.Json @@ -12,8 +13,7 @@ public JsonOutputFormatter(bool prettyPrint = false, bool printErrorsOnly = fals _printErrorsOnly = printErrorsOnly; _options = new JsonSerializerOptions { - Converters = - { new NuGetVersionJsonConverter(), new ValidatedLicenseJsonConverterWithOmittingEmptyErrorList() }, + Converters = { new NuGetVersionJsonConverter(), new ValidatedLicenseJsonConverterWithOmittingEmptyErrorList() }, WriteIndented = prettyPrint }; } diff --git a/src/NuGetUtility/Output/Json/NuGetVersionJsonConverter.cs b/src/NuGetUtility/Output/Json/NuGetVersionJsonConverter.cs deleted file mode 100644 index 2f5a3ad3..00000000 --- a/src/NuGetUtility/Output/Json/NuGetVersionJsonConverter.cs +++ /dev/null @@ -1,20 +0,0 @@ -using NuGet.Versioning; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace NuGetUtility.Output.Json -{ - public class NuGetVersionJsonConverter : JsonConverter - { - public override NuGetVersion? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var readStringValue = reader.GetString(); - return new NuGetVersion(readStringValue); - } - - public override void Write(Utf8JsonWriter writer, NuGetVersion value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } - } -} diff --git a/src/NuGetUtility/Output/Table/TableOutputFormatter.cs b/src/NuGetUtility/Output/Table/TableOutputFormatter.cs index 31f78228..a02b0aa7 100644 --- a/src/NuGetUtility/Output/Table/TableOutputFormatter.cs +++ b/src/NuGetUtility/Output/Table/TableOutputFormatter.cs @@ -1,4 +1,4 @@ -using NuGetUtility.LicenseValidator; +using NuGetUtility.LicenseValidator; namespace NuGetUtility.Output.Table { @@ -12,24 +12,23 @@ public TableOutputFormatter(bool printErrorsOnly = false) public async Task Write(Stream stream, IList results) { - var errorColumnDefinition = new ColumnDefinition("Error", - license => string.Join(Environment.NewLine, license.ValidationErrors.Select(e => e.Error))); + var errorColumnDefinition = new ColumnDefinition("Error", license => license.ValidationErrors.Select(e => e.Error), license => license.ValidationErrors.Any()); var columnDefinitions = new[] { - new ColumnDefinition("Package", license => license.PackageId, true), - new ColumnDefinition("Version", license => license.PackageVersion.ToString() ,true), - new ColumnDefinition("License Information Origin", license => license.LicenseInformationOrigin.ToString(), true), - new ColumnDefinition("License Expression", license => license.License ?? string.Empty), - new ColumnDefinition("Package Project Url",license => license.PackageProjectUrl??string.Empty), + new ColumnDefinition("Package", license => license.PackageId, license => true, true), + new ColumnDefinition("Version", license => license.PackageVersion, license => true, true), + new ColumnDefinition("License Information Origin", license => license.LicenseInformationOrigin, license => true, true), + new ColumnDefinition("License Expression", license => license.License, license => license.License != null), + new ColumnDefinition("Package Project Url",license => license.PackageProjectUrl, license => license.PackageProjectUrl != null), errorColumnDefinition, - new ColumnDefinition("Error Context", license => string.Join(Environment.NewLine, license.ValidationErrors.Select(e => e.Context))), + new ColumnDefinition("Error Context", license => license.ValidationErrors.Select(e => e.Context), license => license.ValidationErrors.Any()), }; foreach (var license in results) { foreach (var definition in columnDefinitions) { - definition.Enabled |= !string.IsNullOrWhiteSpace(definition.StringAccessor(license)); + definition.Enabled |= definition.IsRelevant(license); } } @@ -43,11 +42,11 @@ await TablePrinterExtensions .Create(stream, relevantColumns.Select(d => d.Title)) .FromValues( results, - license => relevantColumns.Select(d => d.StringAccessor(license))) + license => relevantColumns.Select(d => d.PropertyAccessor(license))) .Print(); } - private record ColumnDefinition(string Title, Func StringAccessor, bool Enabled = false) + private record ColumnDefinition(string Title, Func PropertyAccessor, Func IsRelevant, bool Enabled = false) { public bool Enabled { get; set; } = Enabled; } diff --git a/src/NuGetUtility/Output/Table/TablePrinter.cs b/src/NuGetUtility/Output/Table/TablePrinter.cs index a79b5efb..a8166510 100644 --- a/src/NuGetUtility/Output/Table/TablePrinter.cs +++ b/src/NuGetUtility/Output/Table/TablePrinter.cs @@ -1,6 +1,4 @@ -// ReSharper disable once CheckNamespace - -namespace Utilities +namespace NuGetUtility.Output.Table { /// /// Credits: https://stackoverflow.com/a/54943087/1199089 @@ -19,7 +17,7 @@ public TablePrinter(Stream stream, IEnumerable titles) _lengths = _titles.Select(t => t.Length).ToArray(); } - public void AddRow(string?[] row) + public void AddRow(object?[] row) { if (row.Length != _titles.Length) { @@ -27,7 +25,7 @@ public void AddRow(string?[] row) $"Added row length [{row.Length}] is not equal to title row length [{_titles.Length}]"); } - var rowElements = row.Select(item => SplitToLines(item?.ToString() ?? string.Empty).ToArray()).ToArray(); + var rowElements = row.Select(GetLines).ToArray(); for (var i = 0; i < _titles.Length; i++) { var maxLineLength = rowElements[i].Any() ? rowElements[i].Max(line => line.Length) : 0; @@ -39,6 +37,15 @@ public void AddRow(string?[] row) _rows.Add(rowElements); } + private string[] GetLines(object? lines) + { + if (lines is IEnumerable enumerable) + { + return enumerable.Select(o => o.ToString() ?? string.Empty).ToArray(); + } + return new[] { lines?.ToString() ?? string.Empty }; + } + public async Task Print() { await using var writer = new StreamWriter(_stream, leaveOpen: true); @@ -83,19 +90,5 @@ private async Task WriteSeparator(TextWriter writer) } await writer.WriteLineAsync("+"); } - - /// - /// Credit: https://stackoverflow.com/a/23408020/1199089 - /// - /// - /// - private static IEnumerable SplitToLines(string input) - { - using var reader = new StringReader(input); - while (reader.ReadLine() is { } line) - { - yield return line; - } - } } } diff --git a/src/NuGetUtility/Output/Table/TablePrinterExtensions.cs b/src/NuGetUtility/Output/Table/TablePrinterExtensions.cs index 5c4bdba9..0f49cf1d 100644 --- a/src/NuGetUtility/Output/Table/TablePrinterExtensions.cs +++ b/src/NuGetUtility/Output/Table/TablePrinterExtensions.cs @@ -1,5 +1,3 @@ -using Utilities; - namespace NuGetUtility.Output.Table { internal static class TablePrinterExtensions @@ -15,7 +13,7 @@ public static TablePrinter Create(Stream stream, IEnumerable headings) public static TablePrinter FromValues(this TablePrinter printer, IEnumerable values, - Func> formatter) + Func> formatter) { foreach (var value in values) { diff --git a/src/NuGetUtility/PackageInformationReader/CustomPackageInformation.cs b/src/NuGetUtility/PackageInformationReader/CustomPackageInformation.cs index 6b968c3d..b247672d 100644 --- a/src/NuGetUtility/PackageInformationReader/CustomPackageInformation.cs +++ b/src/NuGetUtility/PackageInformationReader/CustomPackageInformation.cs @@ -1,6 +1,6 @@ -using NuGet.Versioning; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; namespace NuGetUtility.PackageInformationReader { - public record struct CustomPackageInformation(string Id, NuGetVersion Version, string License); + public record struct CustomPackageInformation(string Id, INuGetVersion Version, string License); } diff --git a/src/NuGetUtility/PackageInformationReader/PackageInformationReader.cs b/src/NuGetUtility/PackageInformationReader/PackageInformationReader.cs index 989bc7d1..6415f21f 100644 --- a/src/NuGetUtility/PackageInformationReader/PackageInformationReader.cs +++ b/src/NuGetUtility/PackageInformationReader/PackageInformationReader.cs @@ -1,27 +1,24 @@ -using NuGet.Protocol.Core.Types; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; +using NuGetUtility.Wrapper.NuGetWrapper.Protocol; using NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types; using System.Runtime.CompilerServices; namespace NuGetUtility.PackageInformationReader { - public class PackageInformationReader : IDisposable + public class PackageInformationReader { + private readonly IGlobalPackagesFolderUtility _globalPackagesFolderUtility; private readonly IEnumerable _customPackageInformation; - private readonly IDisposableSourceRepository[] _sourceRepositories; + private readonly ISourceRepository[] _repositories; public PackageInformationReader(IWrappedSourceRepositoryProvider sourceRepositoryProvider, + IGlobalPackagesFolderUtility globalPackagesFolderUtility, IEnumerable customPackageInformation) { + _globalPackagesFolderUtility = globalPackagesFolderUtility; _customPackageInformation = customPackageInformation; - _sourceRepositories = sourceRepositoryProvider.GetRepositories().ToArray(); - } - - public void Dispose() - { - foreach (var repo in _sourceRepositories) - { - repo.Dispose(); - } + _repositories = sourceRepositoryProvider.GetRepositories(); } public async IAsyncEnumerable GetPackageInfo( @@ -30,23 +27,41 @@ public async IAsyncEnumerable GetPackageInfo( { foreach (var package in projectWithReferencedPackages.ReferencedPackages) { - if (TryGetPackageInfoFromCustomInformation(package, out var info)) + var result = TryGetPackageInfoFromCustomInformation(package); + if (result.Success) + { + yield return new ReferencedPackageWithContext(projectWithReferencedPackages.Project, result.Metadata!); + continue; + } + result = TryGetPackageInformationFromGlobalPackageFolder(package); + if (result.Success) { - yield return new ReferencedPackageWithContext(projectWithReferencedPackages.Project, info!); + yield return new ReferencedPackageWithContext(projectWithReferencedPackages.Project, result.Metadata!); + continue; } - else + result = await TryGetPackageInformationFromRepositories(_repositories, package, cancellation); + if (result.Success) { - yield return new ReferencedPackageWithContext(projectWithReferencedPackages.Project, - await TryGetPackageInformationFromRepositoriesOrReturnInput(_sourceRepositories, - package, - cancellation)); + yield return new ReferencedPackageWithContext(projectWithReferencedPackages.Project, result.Metadata!); + continue; } + // simply return input - validation will fail later, as the required fields are missing + yield return new ReferencedPackageWithContext(projectWithReferencedPackages.Project, new PackageMetadata(package)); + } + } + private PackageSearchResult TryGetPackageInformationFromGlobalPackageFolder(PackageIdentity package) + { + var metadata = _globalPackagesFolderUtility.GetPackage(package); + if (metadata != null) + { + return new PackageSearchResult(metadata); } + return new PackageSearchResult(); } - private async Task TryGetPackageInformationFromRepositoriesOrReturnInput( - IDisposableSourceRepository[] cachedRepositories, - IPackageSearchMetadata package, + private async Task TryGetPackageInformationFromRepositories( + ISourceRepository[] cachedRepositories, + PackageIdentity package, CancellationToken cancellation) { foreach (var repository in cachedRepositories) @@ -57,35 +72,30 @@ private async Task TryGetPackageInformationFromRepositor continue; } - var updatedPackageMetadata = await resource.TryGetMetadataAsync(package.Identity, cancellation); + var updatedPackageMetadata = await resource.TryGetMetadataAsync(package, cancellation); if (updatedPackageMetadata != null) { - return updatedPackageMetadata; + return new PackageSearchResult(updatedPackageMetadata); } } - // simply return input - validation will fail later, as the required fields are missing - return package; + return new PackageSearchResult(); } - private bool TryGetPackageInfoFromCustomInformation(IPackageSearchMetadata package, - out IPackageSearchMetadata? resolved) + private PackageSearchResult TryGetPackageInfoFromCustomInformation(PackageIdentity package) { - resolved = default; var resolvedCustomInformation = _customPackageInformation.FirstOrDefault(info => - info.Id.Equals(package.Identity.Id) && info.Version.Equals(package.Identity.Version)); + info.Id.Equals(package.Id) && info.Version.Equals(package.Version)); if (resolvedCustomInformation == default) { - return false; + return new PackageSearchResult(); } - resolved = new PackageMetadataWithLicenseInformation(package, resolvedCustomInformation.License); - return true; + return new PackageSearchResult(new PackageMetadata(package, resolvedCustomInformation.License)); } - private static async Task TryGetPackageMetadataResource( - IDisposableSourceRepository repository) + private static async Task TryGetPackageMetadataResource(ISourceRepository repository) { try { @@ -96,6 +106,22 @@ private bool TryGetPackageInfoFromCustomInformation(IPackageSearchMetadata packa return null; } } - } + private record PackageSearchResult + { + public bool Success { get; } + public IPackageMetadata? Metadata { get; } + + public PackageSearchResult(IPackageMetadata metadata) + { + Success = true; + Metadata = metadata; + } + + public PackageSearchResult() + { + Success = false; + } + } + } } diff --git a/src/NuGetUtility/PackageInformationReader/PackageMetadata.cs b/src/NuGetUtility/PackageInformationReader/PackageMetadata.cs new file mode 100644 index 00000000..718e89c7 --- /dev/null +++ b/src/NuGetUtility/PackageInformationReader/PackageMetadata.cs @@ -0,0 +1,33 @@ +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; + +namespace NuGetUtility.PackageInformationReader +{ + internal class PackageMetadata : IPackageMetadata + { + public PackageMetadata(PackageIdentity identity) + { + Identity = identity; + } + + public PackageMetadata(PackageIdentity identity, string licenseType) + { + Identity = identity; + LicenseMetadata = new LicenseMetadata(LicenseType.Expression, licenseType); + } + + public PackageIdentity Identity { get; } + + public string Title { get; } = string.Empty; + + public Uri? LicenseUrl => null; + + public string ProjectUrl => string.Empty; + + public string Description => string.Empty; + + public string Summary => string.Empty; + + public LicenseMetadata? LicenseMetadata { get; } = null; + } +} diff --git a/src/NuGetUtility/PackageInformationReader/PackageMetadataWithLicenseInformation.cs b/src/NuGetUtility/PackageInformationReader/PackageMetadataWithLicenseInformation.cs deleted file mode 100644 index de9e3f06..00000000 --- a/src/NuGetUtility/PackageInformationReader/PackageMetadataWithLicenseInformation.cs +++ /dev/null @@ -1,75 +0,0 @@ -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Packaging.Licenses; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; - -namespace NuGetUtility.PackageInformationReader -{ - internal class PackageMetadataWithLicenseInformation : IPackageSearchMetadata - { - private readonly IPackageSearchMetadata _baseMetadata; - - public PackageMetadataWithLicenseInformation(IPackageSearchMetadata baseMetadata, string licenseType) - { - _baseMetadata = baseMetadata; - LicenseMetadata = new LicenseMetadata(LicenseType.Expression, - licenseType, - NuGetLicenseExpression.Parse(licenseType), - new string[] { }, - LicenseMetadata.EmptyVersion); - } - - public Task GetDeprecationMetadataAsync() - { - return _baseMetadata.GetDeprecationMetadataAsync(); - } - - public Task> GetVersionsAsync() - { - return _baseMetadata.GetVersionsAsync(); - } - - public string Authors => _baseMetadata.Authors; - - public IEnumerable DependencySets => _baseMetadata.DependencySets; - - public string Description => _baseMetadata.Description; - - public long? DownloadCount => _baseMetadata.DownloadCount; - - public Uri IconUrl => _baseMetadata.IconUrl; - - public PackageIdentity Identity => _baseMetadata.Identity; - - public Uri LicenseUrl => LicenseMetadata.LicenseUrl; - - public Uri ProjectUrl => _baseMetadata.ProjectUrl; - - public Uri ReadmeUrl => _baseMetadata.ReadmeUrl; - - public Uri ReportAbuseUrl => _baseMetadata.ReportAbuseUrl; - - public Uri PackageDetailsUrl => _baseMetadata.PackageDetailsUrl; - - public DateTimeOffset? Published => _baseMetadata.Published; - - public string Owners => _baseMetadata.Owners; - - public bool RequireLicenseAcceptance => _baseMetadata.RequireLicenseAcceptance; - - public string Summary => _baseMetadata.Summary; - - public string Tags => _baseMetadata.Tags; - - public string Title => _baseMetadata.Title; - - public bool IsListed => _baseMetadata.IsListed; - - public bool PrefixReserved => _baseMetadata.PrefixReserved; - - public LicenseMetadata LicenseMetadata { get; } - - public IEnumerable Vulnerabilities => _baseMetadata.Vulnerabilities; - } -} diff --git a/src/NuGetUtility/PackageInformationReader/ProjectWithReferencedPackages.cs b/src/NuGetUtility/PackageInformationReader/ProjectWithReferencedPackages.cs index 635f8e32..196376ca 100644 --- a/src/NuGetUtility/PackageInformationReader/ProjectWithReferencedPackages.cs +++ b/src/NuGetUtility/PackageInformationReader/ProjectWithReferencedPackages.cs @@ -1,6 +1,6 @@ -using NuGet.Protocol.Core.Types; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; namespace NuGetUtility.PackageInformationReader { - public record ProjectWithReferencedPackages(string Project, IEnumerable ReferencedPackages); + public record ProjectWithReferencedPackages(string Project, IEnumerable ReferencedPackages); } diff --git a/src/NuGetUtility/PackageInformationReader/ReferencedPackageWithContext.cs b/src/NuGetUtility/PackageInformationReader/ReferencedPackageWithContext.cs index 33cc2317..4fc616a9 100644 --- a/src/NuGetUtility/PackageInformationReader/ReferencedPackageWithContext.cs +++ b/src/NuGetUtility/PackageInformationReader/ReferencedPackageWithContext.cs @@ -1,6 +1,6 @@ -using NuGet.Protocol.Core.Types; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; namespace NuGetUtility.PackageInformationReader { - public record ReferencedPackageWithContext(string Context, IPackageSearchMetadata PackageInfo); + public record ReferencedPackageWithContext(string Context, IPackageMetadata PackageInfo); } diff --git a/src/NuGetUtility/Program.cs b/src/NuGetUtility/Program.cs index 1fda6c6a..47bb6c97 100644 --- a/src/NuGetUtility/Program.cs +++ b/src/NuGetUtility/Program.cs @@ -1,4 +1,4 @@ -using McMaster.Extensions.CommandLineUtils; +using McMaster.Extensions.CommandLineUtils; using NuGet.Configuration; using NuGet.Protocol.Core.Types; using NuGetUtility.Extension; @@ -11,7 +11,9 @@ using NuGetUtility.Serialization; using NuGetUtility.Wrapper.HttpClientWrapper; using NuGetUtility.Wrapper.MsBuildWrapper; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; using NuGetUtility.Wrapper.NuGetWrapper.ProjectModel; +using NuGetUtility.Wrapper.NuGetWrapper.Protocol; using NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types; using System.Text.Json; @@ -109,10 +111,7 @@ private async Task OnExecuteAsync(CancellationToken cancellationToken) var msBuild = new MsBuildAbstraction(); var projectCollector = new ProjectsCollector(msBuild); - var projectReader = new ReferencedPackageReader(ignoredPackages, - msBuild, - new LockFileFactory(), - new PackageSearchMetadataBuilderFactory()); + var projectReader = new ReferencedPackageReader(ignoredPackages, msBuild, new LockFileFactory()); var validator = new LicenseValidator.LicenseValidator(licenseMappings, allowedLicenses, urlLicenseFileDownloader); @@ -121,7 +120,7 @@ private async Task OnExecuteAsync(CancellationToken cancellationToken) var projects = inputFiles.SelectMany(file => projectCollector.GetProjects(file)); var packagesForProject = projects.Select(p => { - IEnumerable? installedPackages = null; + IEnumerable? installedPackages = null; try { installedPackages = projectReader.GetInstalledPackages(p, IncludeTransitive); @@ -130,8 +129,7 @@ private async Task OnExecuteAsync(CancellationToken cancellationToken) { projectReaderExceptions.Add(e); } - return new ProjectWithReferencedPackages(p, - installedPackages ?? Enumerable.Empty()); + return new ProjectWithReferencedPackages(p, installedPackages ?? Enumerable.Empty()); }); var downloadedLicenseInformation = packagesForProject.SelectMany(p => GetPackageInfos(p, overridePackageInformation, cancellationToken)); @@ -145,7 +143,7 @@ private async Task OnExecuteAsync(CancellationToken cancellationToken) } await using var outputStream = Console.OpenStandardOutput(); - await output.Write(outputStream, results.ToList()); + await output.Write(outputStream, results.OrderBy(r => r.PackageId).ToList()); return 0; } private IAsyncEnumerable GetPackageInfos( @@ -155,13 +153,12 @@ private IAsyncEnumerable GetPackageInfos( { var settings = Settings.LoadDefaultSettings(projectWithReferences.Project); var sourceProvider = new PackageSourceProvider(settings); - using var informationReader = new PackageInformationReader.PackageInformationReader( - new WrappedSourceRepositoryProvider(new SourceRepositoryProvider(sourceProvider, - Repository.Provider.GetCoreV3())), - overridePackageInformation); - return informationReader.GetPackageInfo(new ProjectWithReferencedPackages(projectWithReferences.Project, - projectWithReferences.ReferencedPackages), - cancellation); + + using var sourceRepositoryProvider = new WrappedSourceRepositoryProvider(new SourceRepositoryProvider(sourceProvider, Repository.Provider.GetCoreV3())); + var globalPackagesFolderUtility = new GlobalPackagesFolderUtility(settings); + var informationReader = new PackageInformationReader.PackageInformationReader(sourceRepositoryProvider, globalPackagesFolderUtility, overridePackageInformation); + + return informationReader.GetPackageInfo(new ProjectWithReferencedPackages(projectWithReferences.Project, projectWithReferences.ReferencedPackages), cancellation); } private IOutputFormatter GetOutputFormatter() @@ -206,7 +203,7 @@ private IEnumerable GetOverridePackageInformation() } var serializerOptions = new JsonSerializerOptions(); - serializerOptions.Converters.Add(new NuGetVersionConverter()); + serializerOptions.Converters.Add(new NuGetVersionJsonConverter()); return JsonSerializer.Deserialize>( File.ReadAllText(OverridePackageInformation), serializerOptions)!; diff --git a/src/NuGetUtility/ReferencedPackagesReader/ReferencedPackageReader.cs b/src/NuGetUtility/ReferencedPackagesReader/ReferencedPackageReader.cs index c67c2fa4..be55357c 100644 --- a/src/NuGetUtility/ReferencedPackagesReader/ReferencedPackageReader.cs +++ b/src/NuGetUtility/ReferencedPackagesReader/ReferencedPackageReader.cs @@ -1,9 +1,7 @@ -using NuGet.Protocol.Core.Types; using NuGetUtility.Extensions; using NuGetUtility.Wrapper.MsBuildWrapper; using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; using NuGetUtility.Wrapper.NuGetWrapper.ProjectModel; -using NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types; namespace NuGetUtility.ReferencedPackagesReader { @@ -12,33 +10,30 @@ public class ReferencedPackageReader private const string ProjectReferenceIdentifier = "project"; private readonly IEnumerable _ignoredPackages; private readonly ILockFileFactory _lockFileFactory; - private readonly IPackageSearchMetadataBuilderFactory _metadataBuilderFactory; private readonly IMsBuildAbstraction _msBuild; public ReferencedPackageReader(IEnumerable ignoredPackages, IMsBuildAbstraction msBuild, - ILockFileFactory lockFileFactory, - IPackageSearchMetadataBuilderFactory metadataBuilderFactory) + ILockFileFactory lockFileFactory) { _ignoredPackages = ignoredPackages; _msBuild = msBuild; _lockFileFactory = lockFileFactory; - _metadataBuilderFactory = metadataBuilderFactory; } - public IEnumerable GetInstalledPackages(string projectPath, bool includeTransitive) + public IEnumerable GetInstalledPackages(string projectPath, bool includeTransitive) { var project = _msBuild.GetProject(projectPath); if (!project.HasNugetPackagesReferenced() && !includeTransitive) { - return Enumerable.Empty(); + return Enumerable.Empty(); } return GetInstalledPackagesFromAssetsFile(includeTransitive, project); } - private IEnumerable GetInstalledPackagesFromAssetsFile(bool includeTransitive, + private IEnumerable GetInstalledPackagesFromAssetsFile(bool includeTransitive, IProject project) { var assetsFile = LoadAssetsFile(project); @@ -53,8 +48,7 @@ private IEnumerable GetInstalledPackagesFromAssetsFile(b } return referencedLibraries.Where(IsNotIgnoredPackage) - .Select(r => - _metadataBuilderFactory.FromIdentity(new PackageIdentity(r.Name, r.Version)).Build()); + .Select(r => new PackageIdentity(r.Name, r.Version)); } private IEnumerable GetReferencedLibrariesForTarget(IProject project, diff --git a/src/NuGetUtility/Serialization/NuGetVersionConverter.cs b/src/NuGetUtility/Serialization/NuGetVersionConverter.cs deleted file mode 100644 index ca5d5624..00000000 --- a/src/NuGetUtility/Serialization/NuGetVersionConverter.cs +++ /dev/null @@ -1,25 +0,0 @@ -using NuGet.Versioning; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace NuGetUtility.Serialization -{ - internal class NuGetVersionConverter : JsonConverter - { - public override NuGetVersion? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var stringVersion = JsonSerializer.Deserialize(ref reader, options)!; - if (NuGetVersion.TryParse(stringVersion, out var version)) - { - return version; - } - - return null; - } - - public override void Write(Utf8JsonWriter writer, NuGetVersion value, JsonSerializerOptions options) - { - JsonSerializer.Serialize(writer, value.ToString(), options); - } - } -} diff --git a/src/NuGetUtility/Serialization/NuGetVersionJsonConverter.cs b/src/NuGetUtility/Serialization/NuGetVersionJsonConverter.cs new file mode 100644 index 00000000..26c0b1c7 --- /dev/null +++ b/src/NuGetUtility/Serialization/NuGetVersionJsonConverter.cs @@ -0,0 +1,30 @@ +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace NuGetUtility.Serialization +{ + internal class NuGetVersionJsonConverter : JsonConverter + { + public override INuGetVersion? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var stringVersion = JsonSerializer.Deserialize(ref reader, options)!; + if (WrappedNuGetVersion.TryParse(stringVersion, out var version)) + { + return version; + } + + return null; + } + + public override void Write(Utf8JsonWriter writer, INuGetVersion value, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, value.ToString(), options); + } + + public override bool CanConvert(Type typeToConvert) + { + return typeToConvert.IsAssignableTo(typeof(INuGetVersion)); + } + } +} diff --git a/src/NuGetUtility/Output/Json/ValidatedLicenseJsonConverterWithOmittingEmptyErrorList.cs b/src/NuGetUtility/Serialization/ValidatedLicenseJsonConverterWithOmittingEmptyErrorList.cs similarity index 94% rename from src/NuGetUtility/Output/Json/ValidatedLicenseJsonConverterWithOmittingEmptyErrorList.cs rename to src/NuGetUtility/Serialization/ValidatedLicenseJsonConverterWithOmittingEmptyErrorList.cs index d5e66f19..5fad0d59 100644 --- a/src/NuGetUtility/Output/Json/ValidatedLicenseJsonConverterWithOmittingEmptyErrorList.cs +++ b/src/NuGetUtility/Serialization/ValidatedLicenseJsonConverterWithOmittingEmptyErrorList.cs @@ -1,8 +1,8 @@ -using NuGetUtility.LicenseValidator; +using NuGetUtility.LicenseValidator; using System.Text.Json; using System.Text.Json.Serialization; -namespace NuGetUtility.Output.Json +namespace NuGetUtility.Serialization { public class ValidatedLicenseJsonConverterWithOmittingEmptyErrorList : JsonConverter { diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/Core/PackageIdentity.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/Core/PackageIdentity.cs index 5c46ca34..3f64e23e 100644 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/Core/PackageIdentity.cs +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/Core/PackageIdentity.cs @@ -1,6 +1,6 @@ -using NuGetUtility.Wrapper.NuGetWrapper.Versioning; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; namespace NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core { - public record PackageIdentity(string Name, INuGetVersion Version); + public record PackageIdentity(string Id, INuGetVersion Version); } diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/IPackageMetadata.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/IPackageMetadata.cs new file mode 100644 index 00000000..cb2cd39b --- /dev/null +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/IPackageMetadata.cs @@ -0,0 +1,15 @@ +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; + +namespace NuGetUtility.Wrapper.NuGetWrapper.Packaging +{ + public interface IPackageMetadata + { + PackageIdentity Identity { get; } + string Title { get; } + Uri? LicenseUrl { get; } + string ProjectUrl { get; } + string Description { get; } + string Summary { get; } + LicenseMetadata? LicenseMetadata { get; } + } +} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/LicenseMetadata.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/LicenseMetadata.cs new file mode 100644 index 00000000..3bdec780 --- /dev/null +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/LicenseMetadata.cs @@ -0,0 +1,21 @@ +using System.ComponentModel; +using OriginalLicenseType = NuGet.Packaging.LicenseType; +using WrappedLicenseType = NuGetUtility.Wrapper.NuGetWrapper.Packaging.LicenseType; + +namespace NuGetUtility.Wrapper.NuGetWrapper.Packaging +{ + public record LicenseMetadata(WrappedLicenseType Type, string License) + { + public static implicit operator LicenseMetadata?(NuGet.Packaging.LicenseMetadata? metadata) => metadata == null ? null : new LicenseMetadata(Convert(metadata.Type), metadata.License); + + private static WrappedLicenseType Convert(OriginalLicenseType type) + { + return type switch + { + OriginalLicenseType.Expression => WrappedLicenseType.Expression, + OriginalLicenseType.File => WrappedLicenseType.File, + _ => throw new InvalidEnumArgumentException(nameof(type), (int)type, typeof(OriginalLicenseType)), + }; + } + } +} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/LicenseType.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/LicenseType.cs new file mode 100644 index 00000000..09aedbcb --- /dev/null +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Packaging/LicenseType.cs @@ -0,0 +1,8 @@ +namespace NuGetUtility.Wrapper.NuGetWrapper.Packaging +{ + public enum LicenseType + { + File, + Expression + } +} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/CachingDisposableSourceRepository.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/CachingDisposableSourceRepository.cs index f8d129f4..396c06da 100644 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/CachingDisposableSourceRepository.cs +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/CachingDisposableSourceRepository.cs @@ -1,4 +1,4 @@ -using NuGet.Protocol.Core.Types; +using NuGet.Protocol.Core.Types; namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types { diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/CachingPackageMetadataResource.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/CachingPackageMetadataResource.cs index 80fa780b..e1eeb868 100644 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/CachingPackageMetadataResource.cs +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/CachingPackageMetadataResource.cs @@ -1,6 +1,10 @@ -using NuGet.Common; -using NuGet.Packaging.Core; +using NuGet.Common; using NuGet.Protocol.Core.Types; +using NuGet.Versioning; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; +using System.ComponentModel; namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types { @@ -15,20 +19,47 @@ public CachingPackageMetadataResource(PackageMetadataResource metadataResource, _cacheContext = cacheContext; } - public async Task TryGetMetadataAsync(PackageIdentity identity, + public async Task TryGetMetadataAsync(PackageIdentity identity, CancellationToken cancellationToken) { try { - return await _metadataResource.GetMetadataAsync(identity, + var result = await _metadataResource.GetMetadataAsync(new NuGet.Packaging.Core.PackageIdentity(identity.Id, new NuGetVersion(identity.Version.ToString())), _cacheContext, new NullLogger(), cancellationToken); + return new WrappedPackageSearchMetadata(result); } catch (Exception) { return null; } } + + private class WrappedPackageSearchMetadata : IPackageMetadata + { + private IPackageSearchMetadata _searchMetadata; + + public WrappedPackageSearchMetadata(IPackageSearchMetadata searchMetadata) + { + Identity = new PackageIdentity(searchMetadata.Identity.Id, new WrappedNuGetVersion(searchMetadata.Identity.Version)); + LicenseMetadata = searchMetadata.LicenseMetadata; + _searchMetadata = searchMetadata; + } + + public PackageIdentity Identity { get; } + + public string Title => _searchMetadata.Title; + + public Uri? LicenseUrl => _searchMetadata.LicenseUrl; + + public string ProjectUrl => _searchMetadata.ProjectUrl?.ToString() ?? string.Empty; + + public string Description => _searchMetadata.Description; + + public string Summary => _searchMetadata.Summary; + + public LicenseMetadata? LicenseMetadata { get; } + } } } diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IDisposableSourceRepository.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IDisposableSourceRepository.cs index c0fcb292..0bfe3b79 100644 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IDisposableSourceRepository.cs +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IDisposableSourceRepository.cs @@ -1,7 +1,6 @@ -namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types +namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types { - public interface IDisposableSourceRepository : IDisposable + public interface IDisposableSourceRepository : ISourceRepository, IDisposable { - Task GetPackageMetadataResourceAsync(); } } diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageMetadataResource.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageMetadataResource.cs index 0b072917..8a3a2352 100644 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageMetadataResource.cs +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageMetadataResource.cs @@ -1,11 +1,10 @@ -using NuGet.Packaging.Core; -using NuGet.Protocol.Core.Types; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types { public interface IPackageMetadataResource { - Task - TryGetMetadataAsync(PackageIdentity identity, CancellationToken cancellationToken); + Task TryGetMetadataAsync(PackageIdentity identity, CancellationToken cancellationToken); } } diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageSearchMetadataBuilder.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageSearchMetadataBuilder.cs deleted file mode 100644 index 78393b2d..00000000 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageSearchMetadataBuilder.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NuGet.Protocol.Core.Types; - -namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types -{ - public interface IPackageSearchMetadataBuilder - { - IPackageSearchMetadata Build(); - } -} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageSearchMetadataBuilderFactory.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageSearchMetadataBuilderFactory.cs deleted file mode 100644 index 79c86cf0..00000000 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IPackageSearchMetadataBuilderFactory.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; - -namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types -{ - public interface IPackageSearchMetadataBuilderFactory - { - IPackageSearchMetadataBuilder FromIdentity(PackageIdentity packageIdentity); - } -} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/ISourceRepository.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/ISourceRepository.cs new file mode 100644 index 00000000..af4d85df --- /dev/null +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/ISourceRepository.cs @@ -0,0 +1,7 @@ +namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types +{ + public interface ISourceRepository + { + Task GetPackageMetadataResourceAsync(); + } +} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IWrappedSourceRepositoryProvider.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IWrappedSourceRepositoryProvider.cs index 55af6c99..3d7495e3 100644 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IWrappedSourceRepositoryProvider.cs +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/IWrappedSourceRepositoryProvider.cs @@ -1,7 +1,7 @@ -namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types +namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types { public interface IWrappedSourceRepositoryProvider { - IEnumerable GetRepositories(); + ISourceRepository[] GetRepositories(); } } diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/PackageSearchMetadataBuilderFactory.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/PackageSearchMetadataBuilderFactory.cs deleted file mode 100644 index 153bce80..00000000 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/PackageSearchMetadataBuilderFactory.cs +++ /dev/null @@ -1,19 +0,0 @@ -using NuGet.Protocol.Core.Types; -using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; -using NuGetUtility.Wrapper.NuGetWrapper.Versioning; - -namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types -{ - public class PackageSearchMetadataBuilderFactory : IPackageSearchMetadataBuilderFactory - { - public IPackageSearchMetadataBuilder FromIdentity(PackageIdentity packageIdentity) - { - var wrappedNugetVersion = packageIdentity.Version as WrappedNuGetVersion; - - var transformedPackageIdentity = - new NuGet.Packaging.Core.PackageIdentity(packageIdentity.Name, wrappedNugetVersion!.Unwrap()); - return new WrappedPackageSearchMetadataBuilder( - PackageSearchMetadataBuilder.FromIdentity(transformedPackageIdentity)); - } - } -} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/WrappedPackageSearchMetadataBuilder.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/WrappedPackageSearchMetadataBuilder.cs deleted file mode 100644 index 65ff2622..00000000 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/WrappedPackageSearchMetadataBuilder.cs +++ /dev/null @@ -1,19 +0,0 @@ -using NuGet.Protocol.Core.Types; - -namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types -{ - internal class WrappedPackageSearchMetadataBuilder : IPackageSearchMetadataBuilder - { - private readonly PackageSearchMetadataBuilder _builder; - - public WrappedPackageSearchMetadataBuilder(PackageSearchMetadataBuilder builder) - { - _builder = builder; - } - - public IPackageSearchMetadata Build() - { - return _builder.Build(); - } - } -} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/WrappedSourceRepositoryProvider.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/WrappedSourceRepositoryProvider.cs index 9f8cc90d..88eac4fd 100644 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/WrappedSourceRepositoryProvider.cs +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/Core/Types/WrappedSourceRepositoryProvider.cs @@ -1,19 +1,27 @@ -using NuGet.Protocol.Core.Types; +using NuGet.Protocol.Core.Types; namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types { - internal class WrappedSourceRepositoryProvider : IWrappedSourceRepositoryProvider + internal class WrappedSourceRepositoryProvider : IWrappedSourceRepositoryProvider, IDisposable { - private readonly ISourceRepositoryProvider _provider; + private readonly IDisposableSourceRepository[] _repositories; public WrappedSourceRepositoryProvider(ISourceRepositoryProvider provider) { - _provider = provider; + _repositories = provider.GetRepositories().Where(r => r.PackageSource.IsEnabled).Select(r => new CachingDisposableSourceRepository(r)).ToArray(); } - public IEnumerable GetRepositories() + public void Dispose() { - return _provider.GetRepositories().Select(r => new CachingDisposableSourceRepository(r)).ToArray(); + foreach (var repository in _repositories) + { + repository.Dispose(); + } + } + + public ISourceRepository[] GetRepositories() + { + return _repositories; } } } diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/GlobalPackagesFolderUtility.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/GlobalPackagesFolderUtility.cs new file mode 100644 index 00000000..1a027dec --- /dev/null +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/GlobalPackagesFolderUtility.cs @@ -0,0 +1,38 @@ +using NuGet.Configuration; +using NuGet.Packaging; +using NuGet.Versioning; +using IWrappedPackageMetadata = NuGetUtility.Wrapper.NuGetWrapper.Packaging.IPackageMetadata; +using OriginalPackageIdentity = NuGet.Packaging.Core.PackageIdentity; +using PackageIdentity = NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core.PackageIdentity; + +namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol +{ + internal class GlobalPackagesFolderUtility : IGlobalPackagesFolderUtility + { + private readonly string _globalPackagesFolder; + + public GlobalPackagesFolderUtility(ISettings settings) + { + _globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(settings); + } + + public IWrappedPackageMetadata? GetPackage(PackageIdentity identity) + { + var cachedPackage = NuGet.Protocol.GlobalPackagesFolderUtility.GetPackage(new OriginalPackageIdentity(identity.Id, new NuGetVersion(identity.Version.ToString())), _globalPackagesFolder); + if (cachedPackage == null) + { + return null; + } + + using var pkgStream = cachedPackage.PackageReader; + var manifest = Manifest.ReadFrom(pkgStream.GetNuspec(), true); + + if (manifest.Metadata.Version.ToString() != identity.Version.ToString()) + { + return null; + } + + return new WrappedPackageMetadata(manifest.Metadata); + } + } +} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/IGlobalPackagesFolderUtility.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/IGlobalPackagesFolderUtility.cs new file mode 100644 index 00000000..cc313b24 --- /dev/null +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/IGlobalPackagesFolderUtility.cs @@ -0,0 +1,10 @@ +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; + +namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol +{ + public interface IGlobalPackagesFolderUtility + { + IPackageMetadata? GetPackage(PackageIdentity identity); + } +} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/WrappedPackageMetadata.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/WrappedPackageMetadata.cs new file mode 100644 index 00000000..2bd39dfd --- /dev/null +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Protocol/WrappedPackageMetadata.cs @@ -0,0 +1,33 @@ +using NuGet.Packaging; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; +using IWrappedPackageMetadata = NuGetUtility.Wrapper.NuGetWrapper.Packaging.IPackageMetadata; + +namespace NuGetUtility.Wrapper.NuGetWrapper.Protocol +{ + internal class WrappedPackageMetadata : IWrappedPackageMetadata + { + private ManifestMetadata _metadata; + + public WrappedPackageMetadata(ManifestMetadata metadata) + { + Identity = new PackageIdentity(metadata.Id, new WrappedNuGetVersion(metadata.Version)); + LicenseMetadata = metadata.LicenseMetadata; + _metadata = metadata; + } + + public PackageIdentity Identity { get; } + + public string Title => _metadata.Title; + + public Uri? LicenseUrl => _metadata.LicenseUrl; + + public string ProjectUrl => _metadata.ProjectUrl?.ToString() ?? string.Empty; + + public string Description => _metadata.Description; + + public string Summary => _metadata.Summary; + + public Packaging.LicenseMetadata? LicenseMetadata { get; } + } +} diff --git a/src/NuGetUtility/Wrapper/NuGetWrapper/Versioning/WrappedNuGetVersion.cs b/src/NuGetUtility/Wrapper/NuGetWrapper/Versioning/WrappedNuGetVersion.cs index c12bc3c5..082c480e 100644 --- a/src/NuGetUtility/Wrapper/NuGetWrapper/Versioning/WrappedNuGetVersion.cs +++ b/src/NuGetUtility/Wrapper/NuGetWrapper/Versioning/WrappedNuGetVersion.cs @@ -1,4 +1,4 @@ -using NuGet.Versioning; +using NuGet.Versioning; namespace NuGetUtility.Wrapper.NuGetWrapper.Versioning { @@ -55,5 +55,16 @@ public NuGetVersion Unwrap() { return _version; } + + internal static bool TryParse(string stringVersion, out WrappedNuGetVersion version) + { + if (NuGetVersion.TryParse(stringVersion, out var internalVersion)) + { + version = new WrappedNuGetVersion(internalVersion); + return true; + } + version = default!; + return false; + } } } diff --git a/tests/NuGetUtility.Test/Helper/AutoFixture/NuGet/Versioning/NuGetVersionBuilder.cs b/tests/NuGetUtility.Test/Helper/AutoFixture/NuGet/Versioning/NuGetVersionBuilder.cs index 46ae714e..1036fc46 100644 --- a/tests/NuGetUtility.Test/Helper/AutoFixture/NuGet/Versioning/NuGetVersionBuilder.cs +++ b/tests/NuGetUtility.Test/Helper/AutoFixture/NuGet/Versioning/NuGetVersionBuilder.cs @@ -1,5 +1,5 @@ -using AutoFixture.Kernel; -using NuGet.Versioning; +using AutoFixture.Kernel; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; namespace NuGetUtility.Test.Helper.AutoFixture.NuGet.Versioning { @@ -11,7 +11,7 @@ public object Create(object request, ISpecimenContext context) { if (request is System.Type t) { - if (t == typeof(NuGetVersion)) + if (t == typeof(INuGetVersion)) { return new NuGetVersion($"{_rnd.Next(100, 999)}.{_rnd.Next(100, 999)}{GetPatch()}{GetBeta()}"); } @@ -34,5 +34,20 @@ private bool RandomBool() { return (_rnd.Next() % 2) == 0; } + + private class NuGetVersion : INuGetVersion + { + private readonly string _version; + + public NuGetVersion(string version) + { + _version = version; + } + + public override string ToString() + { + return _version; + } + } } } diff --git a/tests/NuGetUtility.Test/Helper/NuGet/Protocol/Core/Types/PackageMetadataWithVersionInfo.cs b/tests/NuGetUtility.Test/Helper/NuGet/Protocol/Core/Types/PackageMetadataWithVersionInfo.cs deleted file mode 100644 index 311a436e..00000000 --- a/tests/NuGetUtility.Test/Helper/NuGet/Protocol/Core/Types/PackageMetadataWithVersionInfo.cs +++ /dev/null @@ -1,80 +0,0 @@ -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Packaging.Licenses; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; -using NuGet.Versioning; - -namespace NuGetUtility.Test.Helper.NuGet.Protocol.Core.Types -{ - internal class PackageMetadataWithVersionInfo : IPackageSearchMetadata - { - private readonly string _license; - private readonly string _packageId; - private readonly NuGetVersion _packageVersion; - - public PackageMetadataWithVersionInfo(string packageId, NuGetVersion packageVersion, string license) - { - _packageId = packageId; - _packageVersion = packageVersion; - _license = license; - } - - public Task GetDeprecationMetadataAsync() - { - throw new NotImplementedException(); - } - - public Task> GetVersionsAsync() - { - throw new NotImplementedException(); - } - - public string Authors => throw new NotImplementedException(); - - public IEnumerable DependencySets => throw new NotImplementedException(); - - public string Description => throw new NotImplementedException(); - - public long? DownloadCount => throw new NotImplementedException(); - - public Uri IconUrl => throw new NotImplementedException(); - - public PackageIdentity Identity => new PackageIdentity(_packageId, _packageVersion); - - public Uri LicenseUrl => throw new NotImplementedException(); - - public Uri ProjectUrl => throw new NotImplementedException(); - - public Uri ReadmeUrl => throw new NotImplementedException(); - - public Uri ReportAbuseUrl => throw new NotImplementedException(); - - public Uri PackageDetailsUrl => throw new NotImplementedException(); - - public DateTimeOffset? Published => throw new NotImplementedException(); - - public string Owners => throw new NotImplementedException(); - - public bool RequireLicenseAcceptance => throw new NotImplementedException(); - - public string Summary => throw new NotImplementedException(); - - public string Tags => throw new NotImplementedException(); - - public string Title => throw new NotImplementedException(); - - public bool IsListed => throw new NotImplementedException(); - - public bool PrefixReserved => throw new NotImplementedException(); - - public LicenseMetadata LicenseMetadata => - new LicenseMetadata(LicenseType.Expression, - _license, - NuGetLicenseExpression.Parse(_license), - new string[] { }, - LicenseMetadata.EmptyVersion); - - public IEnumerable Vulnerabilities => throw new NotImplementedException(); - } -} diff --git a/tests/NuGetUtility.Test/Helper/NuGet/Protocol/Core/Types/PackageSearchMetadataMock.cs b/tests/NuGetUtility.Test/Helper/NuGet/Protocol/Core/Types/PackageSearchMetadataMock.cs deleted file mode 100644 index b0bc84b7..00000000 --- a/tests/NuGetUtility.Test/Helper/NuGet/Protocol/Core/Types/PackageSearchMetadataMock.cs +++ /dev/null @@ -1,64 +0,0 @@ -using NuGet.Packaging; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; -using NuGet.Versioning; -using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; - -namespace NuGetUtility.Test.Helper.NuGet.Protocol.Core.Types -{ - internal record struct PackageSearchMetadataMock(PackageIdentity Id) : IPackageSearchMetadata - { - public Task GetDeprecationMetadataAsync() - { - throw new NotImplementedException(); - } - - public Task> GetVersionsAsync() - { - throw new NotImplementedException(); - } - - public string Authors => throw new NotImplementedException(); - - public IEnumerable DependencySets => throw new NotImplementedException(); - - public string Description => throw new NotImplementedException(); - - public long? DownloadCount => throw new NotImplementedException(); - - public Uri IconUrl => throw new NotImplementedException(); - - public global::NuGet.Packaging.Core.PackageIdentity Identity => - new global::NuGet.Packaging.Core.PackageIdentity(Id.Name, new NuGetVersion(Id.Version.ToString())); - - public Uri LicenseUrl => throw new NotImplementedException(); - - public Uri ProjectUrl => throw new NotImplementedException(); - - public Uri ReadmeUrl => throw new NotImplementedException(); - - public Uri ReportAbuseUrl => throw new NotImplementedException(); - - public Uri PackageDetailsUrl => throw new NotImplementedException(); - - public DateTimeOffset? Published => throw new NotImplementedException(); - - public string Owners => throw new NotImplementedException(); - - public bool RequireLicenseAcceptance => throw new NotImplementedException(); - - public string Summary => throw new NotImplementedException(); - - public string Tags => throw new NotImplementedException(); - - public string Title => throw new NotImplementedException(); - - public bool IsListed => throw new NotImplementedException(); - - public bool PrefixReserved => throw new NotImplementedException(); - - public LicenseMetadata LicenseMetadata => throw new NotImplementedException(); - - public IEnumerable Vulnerabilities => throw new NotImplementedException(); - } -} diff --git a/tests/NuGetUtility.Test/LicenseValidator/LicenseValidatorTest.cs b/tests/NuGetUtility.Test/LicenseValidator/LicenseValidatorTest.cs index 389124ea..40805662 100644 --- a/tests/NuGetUtility.Test/LicenseValidator/LicenseValidatorTest.cs +++ b/tests/NuGetUtility.Test/LicenseValidator/LicenseValidatorTest.cs @@ -1,10 +1,5 @@ -using AutoFixture; +using AutoFixture; using Moq; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Packaging.Licenses; -using NuGet.Protocol.Core.Types; -using NuGet.Versioning; using NuGetUtility.LicenseValidator; using NuGetUtility.PackageInformationReader; using NuGetUtility.Test.Helper.AsyncEnumerableExtension; @@ -12,6 +7,9 @@ using NuGetUtility.Test.Helper.NUnitExtension; using NuGetUtility.Test.Helper.ShuffelledEnumerable; using NuGetUtility.Wrapper.HttpClientWrapper; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; namespace NuGetUtility.Test.LicenseValidator { @@ -48,37 +46,33 @@ public async Task ValidatingEmptyList_Should_ReturnEmptyValidatedLicenses() CollectionAssert.AreEqual(Enumerable.Empty(), results); } - private Mock SetupPackage(string packageId, NuGetVersion packageVersion) + private Mock SetupPackage(string packageId, INuGetVersion packageVersion) { - var packageInfo = new Mock(); + var packageInfo = new Mock(); packageInfo.SetupGet(m => m.Identity).Returns(new PackageIdentity(packageId, packageVersion)); - packageInfo.SetupGet(m => m.ProjectUrl).Returns(_projectUrl); + packageInfo.SetupGet(m => m.ProjectUrl).Returns(_projectUrl.ToString()); return packageInfo; } - private Mock SetupPackageWithLicenseInformationOfType(string packageId, - NuGetVersion packageVersion, + private Mock SetupPackageWithLicenseInformationOfType(string packageId, + INuGetVersion packageVersion, string license, LicenseType type) { var packageInfo = SetupPackage(packageId, packageVersion); packageInfo.SetupGet(m => m.LicenseMetadata) - .Returns(new LicenseMetadata(type, - license, - NuGetLicenseExpression.Parse(license), - new string[] { }, - LicenseMetadata.EmptyVersion)); + .Returns(new LicenseMetadata(type, license)); return packageInfo; } - private Mock SetupPackageWithProperLicenseInformation(string packageId, - NuGetVersion packageVersion, + private Mock SetupPackageWithProperLicenseInformation(string packageId, + INuGetVersion packageVersion, string license) { return SetupPackageWithLicenseInformationOfType(packageId, packageVersion, license, LicenseType.Expression); } - private IAsyncEnumerable CreateInput(Mock metadata, + private IAsyncEnumerable CreateInput(Mock metadata, string context) { return new[] { new ReferencedPackageWithContext(context, metadata.Object) }.AsAsyncEnumerable(); @@ -88,7 +82,7 @@ private IAsyncEnumerable CreateInput(Mock SetupPackageWithLicenseUrl(string packageId, - NuGetVersion packageVersion, + private Mock SetupPackageWithLicenseUrl(string packageId, + INuGetVersion packageVersion, Uri url) { var packageInfo = SetupPackage(packageId, packageVersion); @@ -124,7 +118,7 @@ private Mock SetupPackageWithLicenseUrl(string packageId [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithMatchingLicenseUrl_Should_GiveCorrectValidatedLicenseList( string packageId, - NuGetVersion packageVersion) + INuGetVersion packageVersion) { _uut = new NuGetUtility.LicenseValidator.LicenseValidator(_licenseMapping, new string[] { }, @@ -151,7 +145,7 @@ public async Task ValidatingLicensesWithMatchingLicenseUrl_Should_GiveCorrectVal [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithMatchingLicenseUrl_Should_GiveCorrectValidatedLicenseList( string packageId, - NuGetVersion packageVersion, + INuGetVersion packageVersion, Uri licenseUrl) { _uut = new NuGetUtility.LicenseValidator.LicenseValidator(_licenseMapping, @@ -181,7 +175,7 @@ public async Task ValidatingLicensesWithNotSupportedLicenseMetadata_Should_GiveC var fixture = new Fixture(); fixture.Customizations.Add(new NuGetVersionBuilder()); var packageId = fixture.Create(); - var packageVersion = fixture.Create(); + var packageVersion = fixture.Create(); var license = fixture.Create(); _uut = new NuGetUtility.LicenseValidator.LicenseValidator(_licenseMapping, @@ -213,7 +207,7 @@ public async Task ValidatingLicensesWithNotSupportedLicenseMetadata_Should_GiveC [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithoutLicenseInformation_Should_GiveCorrectResult( string packageId, - NuGetVersion packageVersion) + INuGetVersion packageVersion) { _uut = new NuGetUtility.LicenseValidator.LicenseValidator(_licenseMapping, new string[] { }, @@ -244,7 +238,7 @@ public async Task ValidatingLicensesWithoutLicenseInformation_Should_GiveCorrect [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithProperLicenseInformation_Should_GiveCorrectResult_If_NotAllowed( string packageId, - NuGetVersion packageVersion, + INuGetVersion packageVersion, string license) { var package = SetupPackageWithProperLicenseInformation(packageId, packageVersion, license); @@ -272,7 +266,7 @@ public async Task ValidatingLicensesWithProperLicenseInformation_Should_GiveCorr [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithProperLicenseInformation_Should_GiveCorrectResult_If_Allowed( string packageId, - NuGetVersion packageVersion) + INuGetVersion packageVersion) { var validLicense = _allowedLicenses.Shuffle(135643).First(); var package = SetupPackageWithProperLicenseInformation(packageId, packageVersion, validLicense); @@ -295,7 +289,7 @@ public async Task ValidatingLicensesWithProperLicenseInformation_Should_GiveCorr [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithMatchingUrlInformation_Should_GiveCorrectResult_If_NotAllowed( string packageId, - NuGetVersion packageVersion) + INuGetVersion packageVersion) { var urlMatch = _licenseMapping.Shuffle(765).First(); var package = SetupPackageWithLicenseUrl(packageId, packageVersion, urlMatch.Key); @@ -323,14 +317,14 @@ public async Task ValidatingLicensesWithMatchingUrlInformation_Should_GiveCorrec [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithUrlInformation_Should_StartDownloadingSaidLicense( string packageId, - NuGetVersion packageVersion) + INuGetVersion packageVersion) { var urlMatch = _licenseMapping.Shuffle(4567).First(); var package = SetupPackageWithLicenseUrl(packageId, packageVersion, urlMatch.Key); _ = await _uut.Validate(CreateInput(package, _context)); - _fileDownloader.Verify(m => m.DownloadFile(package.Object.LicenseUrl, + _fileDownloader.Verify(m => m.DownloadFile(package.Object.LicenseUrl!, $"{package.Object.Identity.Id}__{package.Object.Identity.Version}.html"), Times.Once); } @@ -339,11 +333,11 @@ public async Task ValidatingLicensesWithUrlInformation_Should_StartDownloadingSa [ExtendedAutoData(typeof(NuGetVersionBuilder))] public void ValidatingLicensesWithUrlInformation_Should_ThrowLicenseDownloadInformation_If_DownloadThrows( string packageId, - NuGetVersion packageVersion) + INuGetVersion packageVersion) { var urlMatch = _licenseMapping.Shuffle(12345).First(); var package = SetupPackageWithLicenseUrl(packageId, packageVersion, urlMatch.Key); - _fileDownloader.Setup(m => m.DownloadFile(package.Object.LicenseUrl, It.IsAny())) + _fileDownloader.Setup(m => m.DownloadFile(package.Object.LicenseUrl!, It.IsAny())) .ThrowsAsync(new Exception()); var exception = @@ -358,7 +352,7 @@ public void ValidatingLicensesWithUrlInformation_Should_ThrowLicenseDownloadInfo [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithMatchingUrlInformation_Should_GiveCorrectResult_If_Allowed( string packageId, - NuGetVersion packageVersion) + INuGetVersion packageVersion) { var urlMatch = _licenseMapping.Shuffle(43562).First(); _uut = new NuGetUtility.LicenseValidator.LicenseValidator(_licenseMapping, @@ -384,7 +378,7 @@ public async Task ValidatingLicensesWithMatchingUrlInformation_Should_GiveCorrec [ExtendedAutoData(typeof(NuGetVersionBuilder))] public async Task ValidatingLicensesWithNotMatchingUrlInformation_Should_GiveCorrectResult_If_NotAllowed( string packageId, - NuGetVersion packageVersion, + INuGetVersion packageVersion, Uri licenseUrl) { var package = SetupPackageWithLicenseUrl(packageId, packageVersion, licenseUrl); diff --git a/tests/NuGetUtility.Test/NuGetUtility.Test.csproj b/tests/NuGetUtility.Test/NuGetUtility.Test.csproj index cddb5997..1fde499d 100644 --- a/tests/NuGetUtility.Test/NuGetUtility.Test.csproj +++ b/tests/NuGetUtility.Test/NuGetUtility.Test.csproj @@ -13,23 +13,23 @@ - - - - - - - - - + + + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + diff --git a/tests/NuGetUtility.Test/Output/TestBase.cs b/tests/NuGetUtility.Test/Output/TestBase.cs index 252b83ef..a8d0e7c9 100644 --- a/tests/NuGetUtility.Test/Output/TestBase.cs +++ b/tests/NuGetUtility.Test/Output/TestBase.cs @@ -1,9 +1,9 @@ -using Bogus; -using NuGet.Versioning; +using Bogus; using NuGetUtility.LicenseValidator; using NuGetUtility.Output; using NuGetUtility.Test.Extensions; using NuGetUtility.Test.Helper.ShuffelledEnumerable; +using NuGetUtility.Wrapper.NuGetWrapper.Versioning; namespace NuGetUtility.Test.Output { @@ -88,5 +88,20 @@ public async Task ValidatedLicenses_Should_PrintCorrectTable( await Verify(stream.AsString()); } + + private class NuGetVersion : INuGetVersion + { + private readonly string _version; + + public NuGetVersion(string version) + { + _version = version; + } + + public override string ToString() + { + return _version; + } + } } } diff --git a/tests/NuGetUtility.Test/PackageInformationReader/PackageInformationReaderTest.cs b/tests/NuGetUtility.Test/PackageInformationReader/PackageInformationReaderTest.cs index ce2eb8c7..3606f454 100644 --- a/tests/NuGetUtility.Test/PackageInformationReader/PackageInformationReaderTest.cs +++ b/tests/NuGetUtility.Test/PackageInformationReader/PackageInformationReaderTest.cs @@ -1,16 +1,14 @@ -using AutoFixture; +using AutoFixture; using Moq; -using NuGet.Protocol.Core.Types; -using NuGet.Versioning; using NuGetUtility.PackageInformationReader; using NuGetUtility.Test.Helper.AsyncEnumerableExtension; using NuGetUtility.Test.Helper.AutoFixture; using NuGetUtility.Test.Helper.AutoFixture.NuGet.Versioning; -using NuGetUtility.Test.Helper.NuGet.Protocol.Core.Types; using NuGetUtility.Test.Helper.ShuffelledEnumerable; +using NuGetUtility.Wrapper.NuGetWrapper.Packaging; using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; +using NuGetUtility.Wrapper.NuGetWrapper.Protocol; using NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types; -using NuGetUtility.Wrapper.NuGetWrapper.Versioning; namespace NuGetUtility.Test.PackageInformationReader { @@ -25,20 +23,16 @@ public void SetUp() _fixture = new Fixture(); _fixture.Customizations.Add(new NuGetVersionBuilder()); _fixture.Customizations.Add(new MockBuilder()); - _sourceRepositories = new List>(); + _repositories = Array.Empty>(); + _globalPackagesFolderUtility = new(); _sourceRepositoryProvider.Setup(m => m.GetRepositories()) - .Returns(() => + .Returns((Delegate)(() => { - foreach (var repository in _sourceRepositories ?? - Enumerable.Empty>()) - { - repository.Verify(m => m.Dispose(), Times.Once); - } - - _sourceRepositories = _fixture.CreateMany>().ToList(); - return _sourceRepositories.Select(r => r.Object); - }); + Assert.AreEqual(Array.Empty>(), _repositories); + _repositories = _fixture.CreateMany>().ToArray>(); + return _repositories.Select, ISourceRepository>(r => r.Object).ToArray(); + })); SetupUut(); } @@ -46,28 +40,22 @@ public void SetUp() [TearDown] public void TearDown() { - _uut?.Dispose(); - foreach (var repository in _sourceRepositories ?? Enumerable.Empty>()) - { - repository.Verify(m => m.Dispose(), Times.Once); - } - - _sourceRepositories?.Clear(); - _uut = null; + _repositories = Array.Empty>(); + _uut = null!; } private void SetupUut() { TearDown(); - _uut = new NuGetUtility.PackageInformationReader.PackageInformationReader(_sourceRepositoryProvider!.Object, - _customPackageInformation!); + _uut = new NuGetUtility.PackageInformationReader.PackageInformationReader(_sourceRepositoryProvider.Object, _globalPackagesFolderUtility.Object, _customPackageInformation); } - private NuGetUtility.PackageInformationReader.PackageInformationReader? _uut; - private Mock? _sourceRepositoryProvider; - private List? _customPackageInformation; - private Fixture? _fixture; - private List>? _sourceRepositories; + private NuGetUtility.PackageInformationReader.PackageInformationReader _uut = null!; + private Mock _sourceRepositoryProvider = null!; + private List _customPackageInformation = null!; + private Fixture _fixture = null!; + private Mock[] _repositories = null!; + private Mock _globalPackagesFolderUtility = null!; [Test] public async Task GetPackageInfo_Should_PreferProvidedCustomInformation() @@ -75,15 +63,14 @@ public async Task GetPackageInfo_Should_PreferProvidedCustomInformation() _customPackageInformation = _fixture.CreateMany().ToList(); SetupUut(); - var searchedPackages = _customPackageInformation.Select(p => - new PackageSearchMetadataMock(new PackageIdentity(p.Id, CreateMockedVersion(p.Version))) as - IPackageSearchMetadata); + var searchedPackages = _customPackageInformation.Select(p => new PackageIdentity(p.Id, p.Version)); var (project, result) = await PerformSearch(searchedPackages); CheckResult(result, project, _customPackageInformation); } + private async Task<(string Project, ReferencedPackageWithContext[] Result)> PerformSearch( - IEnumerable searchedPackages) + IEnumerable searchedPackages) { var project = _fixture.Create(); var packageSearchRequest = new ProjectWithReferencedPackages(project, searchedPackages); @@ -99,7 +86,7 @@ private static void CheckResult(ReferencedPackageWithContext[] result, CollectionAssert.AreEquivalent(packages, result.Select(s => new CustomPackageInformation(s.PackageInfo.Identity.Id, s.PackageInfo.Identity.Version, - s.PackageInfo.LicenseMetadata.License))); + s.PackageInfo.LicenseMetadata!.License))); foreach (var r in result) { Assert.AreEqual(project, r.Context); @@ -107,43 +94,49 @@ private static void CheckResult(ReferencedPackageWithContext[] result, } [Test] - public async Task GetPackageInfo_Should_IterateThroughRepositoriesToGetAdditionalInformation() + public async Task GetPackageInfo_Should_PreferLocalPackageCacheOverRepositories() { - var sourceRepositoriesWithPackageMetadataResource = _sourceRepositories!.Shuffle(2345).Take(2).ToArray(); - var packageMetadataResources = sourceRepositoriesWithPackageMetadataResource.Select(r => - { - var metadataResource = new Mock(); - r.Setup(m => m.GetPackageMetadataResourceAsync()).ReturnsAsync(metadataResource.Object); - return metadataResource; - }) - .ToArray(); var searchedPackagesAsPackageInformation = _fixture.CreateMany(20).ToArray(); - foreach (var package in searchedPackagesAsPackageInformation) + var searchedPackages = searchedPackagesAsPackageInformation.Select(info => { - var metadataReturningProperInformation = packageMetadataResources.Shuffle(6435).First(); - metadataReturningProperInformation - .Setup(m => m.TryGetMetadataAsync( - new NuGet.Packaging.Core.PackageIdentity(package.Id, package.Version), - It.IsAny())) - .ReturnsAsync(new PackageMetadataWithVersionInfo(package.Id, - package.Version, - package.License)); - } + var identity = new PackageIdentity(info.Id, info.Version); + var mockedInfo = new Mock(); + mockedInfo.SetupGet(m => m.Identity).Returns(identity); + mockedInfo.SetupGet(m => m.LicenseMetadata).Returns(new LicenseMetadata(LicenseType.Expression, info.License)); + _globalPackagesFolderUtility.Setup(m => m.GetPackage(identity)).Returns(mockedInfo.Object); - var searchedPackages = searchedPackagesAsPackageInformation.Select(i => - new PackageSearchMetadataMock(new PackageIdentity(i.Id, CreateMockedVersion(i.Version))) as - IPackageSearchMetadata); + return identity; + }); var (project, result) = await PerformSearch(searchedPackages); CheckResult(result, project, searchedPackagesAsPackageInformation); + + foreach (var repo in _repositories) + { + repo.Verify(m => m.GetPackageMetadataResourceAsync(), Times.Never); + } + } + + private void SetupPackagesForRepositories(IEnumerable packages, IEnumerable> packageMetadataResources) + { + foreach (var package in packages) + { + var metadataReturningProperInformation = packageMetadataResources.Shuffle(6435).First(); + var resultingInfo = new Mock(); + resultingInfo.SetupGet(m => m.Identity).Returns(new PackageIdentity(package.Id, package.Version)); + resultingInfo.SetupGet(m => m.LicenseMetadata).Returns(new LicenseMetadata(LicenseType.Expression, package.License)); + + metadataReturningProperInformation + .Setup(m => m.TryGetMetadataAsync(new PackageIdentity(package.Id, package.Version), It.IsAny())) + .ReturnsAsync(resultingInfo.Object); + } } [Test] - public async Task - GetPackageInfo_Should_IgnoreFailingPackageMetadataResourceGetting_if_IterateThroughRepositoriesToGetAdditionalInformation() + public async Task GetPackageInfo_Should_IterateThroughRepositoriesToGetAdditionalInformation() { - var shuffledRepositories = _sourceRepositories!.Shuffle(14563); + var shuffledRepositories = _repositories!.Shuffle(14563); var splitRepositories = shuffledRepositories.Select((repo, index) => (Index: index, Repo: repo)) .GroupBy(e => e.Index % 2) .ToArray(); @@ -165,56 +158,35 @@ public async Task var searchedPackagesAsPackageInformation = _fixture.CreateMany(20).ToArray(); - foreach (var package in searchedPackagesAsPackageInformation) - { - var metadataReturningProperInformation = packageMetadataResources.Shuffle(4361).First(); - metadataReturningProperInformation - .Setup(m => m.TryGetMetadataAsync( - new NuGet.Packaging.Core.PackageIdentity(package.Id, package.Version), - It.IsAny())) - .ReturnsAsync(new PackageMetadataWithVersionInfo(package.Id, - package.Version, - package.License)); - } + SetupPackagesForRepositories(searchedPackagesAsPackageInformation, packageMetadataResources); - var searchedPackages = searchedPackagesAsPackageInformation.Select(i => - new PackageSearchMetadataMock(new PackageIdentity(i.Id, CreateMockedVersion(i.Version))) as - IPackageSearchMetadata); + var searchedPackages = searchedPackagesAsPackageInformation.Select(i => new PackageIdentity(i.Id, i.Version)); var (project, result) = await PerformSearch(searchedPackages); CheckResult(result, project, searchedPackagesAsPackageInformation); } [Test] - public async Task GetPackageInfo_Should_ReturnInputForPackagesWithoutProperLicenseInformation() + public async Task GetPackageInfo_Should_ReturnDummyPackageMetadataForPackagesNotFound() { var searchedPackagesAsPackageInformation = _fixture.CreateMany().ToArray(); - var searchedPackages = searchedPackagesAsPackageInformation.Select(p => - new PackageSearchMetadataMock(new PackageIdentity(p.Id, CreateMockedVersion(p.Version))) as - IPackageSearchMetadata) - .ToArray(); + var searchedPackages = searchedPackagesAsPackageInformation.Select(p => new PackageIdentity(p.Id, p.Version)).ToArray(); - var (project, result) = await PerformSearch(searchedPackages); - CheckResult(result, project, searchedPackages); - } - private void CheckResult(ReferencedPackageWithContext[] result, - string project, - IPackageSearchMetadata[] packages) - { - CollectionAssert.AreEquivalent(packages, - result.Select(s => s.PackageInfo)); - foreach (var r in result) + var (project, results) = await PerformSearch(searchedPackages); + + Assert.AreEqual(searchedPackages.Count(), results.Length); + for (int i = 0; i < results.Length; i++) { - Assert.AreEqual(project, r.Context); + var expectation = searchedPackages[i]; + var result = results[i]; + Assert.AreEqual(project, result.Context); + Assert.AreEqual(expectation.Id, result.PackageInfo.Identity.Id); + Assert.AreEqual(expectation.Version, result.PackageInfo.Identity.Version); + Assert.IsNull(result.PackageInfo.LicenseMetadata); + Assert.IsNull(result.PackageInfo.LicenseUrl); + Assert.AreEqual(string.Empty, result.PackageInfo.Summary); + Assert.AreEqual(string.Empty, result.PackageInfo.Title); } } - - private INuGetVersion CreateMockedVersion(NuGetVersion innerVersion) - { - var mock = new Mock(); - mock.Setup(m => m.ToString()).Returns(innerVersion.ToString()); - - return mock.Object; - } } } diff --git a/tests/NuGetUtility.Test/ReferencedPackagesReader/ReferencedPackageReaderTest.cs b/tests/NuGetUtility.Test/ReferencedPackagesReader/ReferencedPackageReaderTest.cs index b2cebf72..858bd420 100644 --- a/tests/NuGetUtility.Test/ReferencedPackagesReader/ReferencedPackageReaderTest.cs +++ b/tests/NuGetUtility.Test/ReferencedPackagesReader/ReferencedPackageReaderTest.cs @@ -1,14 +1,12 @@ -using AutoFixture; +using AutoFixture; using Moq; using NuGetUtility.ReferencedPackagesReader; using NuGetUtility.Test.Helper.AutoFixture; -using NuGetUtility.Test.Helper.NuGet.Protocol.Core.Types; using NuGetUtility.Test.Helper.ShuffelledEnumerable; using NuGetUtility.Wrapper.MsBuildWrapper; using NuGetUtility.Wrapper.NuGetWrapper.Frameworks; using NuGetUtility.Wrapper.NuGetWrapper.Packaging.Core; using NuGetUtility.Wrapper.NuGetWrapper.ProjectModel; -using NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types; using NuGetUtility.Wrapper.NuGetWrapper.Versioning; namespace NuGetUtility.Test.ReferencedPackagesReader @@ -24,7 +22,6 @@ public void SetUp() _ignoredPackages = fixture.CreateMany(); _msBuild = new Mock(); _lockFileFactory = new Mock(); - _metadataBuilderFactory = new Mock(); _projectPath = fixture.Create(); _assetsFilePath = fixture.Create(); _projectMock = new Mock(); @@ -48,14 +45,6 @@ public void SetUp() _lockFileMock.SetupGet(m => m.Libraries).Returns(_lockFileLibraries.Select(l => l.Object)); _packageSpecMock.SetupGet(m => m.TargetFrameworks) .Returns(_packageSpecTargetFrameworks.Select(t => t.Object)); - _metadataBuilderFactory.Setup(m => m.FromIdentity(It.IsAny())) - .Returns( - (PackageIdentity id) => - { - var builder = new Mock(); - builder.Setup(m => m.Build()).Returns(new PackageSearchMetadataMock(id)); - return builder.Object; - }); _msBuild.Setup(m => m.GetPackageReferencesFromProjectForFramework(_projectMock.Object, It.IsAny())) .Returns((IProject _, string framework) => _packageReferencesFromProjectForFramework[framework]); @@ -102,36 +91,34 @@ public void SetUp() _uut = new ReferencedPackageReader(_ignoredPackages, _msBuild.Object, - _lockFileFactory.Object, - _metadataBuilderFactory.Object); + _lockFileFactory.Object); } private const int TargetFrameworkCount = 5; - private ReferencedPackageReader? _uut; - private IEnumerable? _ignoredPackages; - private Mock? _msBuild; - private Mock? _lockFileFactory; - private Mock? _metadataBuilderFactory; - private string? _projectPath; - private string? _assetsFilePath; - private Mock? _projectMock; - private Mock? _lockFileMock; - private Mock? _packageSpecMock; - private IEnumerable>? _lockFileTargets; - private IEnumerable>? _lockFileLibraries; - private IEnumerable>? _packageSpecTargetFrameworks; - private IEnumerable>? _targetFrameworks; - private Dictionary? _packageReferencesFromProjectForFramework; + private ReferencedPackageReader _uut = null!; + private IEnumerable _ignoredPackages = null!; + private Mock _msBuild = null!; + private Mock _lockFileFactory = null!; + private string _projectPath = null!; + private string _assetsFilePath = null!; + private Mock _projectMock = null!; + private Mock _lockFileMock = null!; + private Mock _packageSpecMock = null!; + private IEnumerable> _lockFileTargets = null!; + private IEnumerable> _lockFileLibraries = null!; + private IEnumerable> _packageSpecTargetFrameworks = null!; + private IEnumerable> _targetFrameworks = null!; + private Dictionary _packageReferencesFromProjectForFramework = null!; [Test] public void GetInstalledPackages_Should_ThrowReferencedPackageReaderException_If_PackageSpecificationIsInvalid( [Values] bool includeTransitive) { - _packageSpecMock!.Setup(m => m.IsValid()).Returns(false); - _projectMock!.SetupGet(m => m.FullPath).Returns(_projectPath!); + _packageSpecMock.Setup(m => m.IsValid()).Returns(false); + _projectMock.SetupGet(m => m.FullPath).Returns(_projectPath); var exception = Assert.Throws(() => - _uut!.GetInstalledPackages(_projectPath!, includeTransitive)); + _uut.GetInstalledPackages(_projectPath, includeTransitive)); Assert.AreEqual($"Failed to validate project assets for project {_projectPath}", exception!.Message); } @@ -140,10 +127,10 @@ public void GetInstalledPackages_Should_ThrowReferencedPackageReaderException_If public void GetInstalledPackages_Should_ThrowReferencedPackageReaderException_If_TargetsArrayIsNull( [Values] bool includeTransitive) { - _lockFileMock!.SetupGet(m => m.Targets).Returns((IEnumerable?)null); + _lockFileMock.SetupGet(m => m.Targets).Returns((IEnumerable?)null); var exception = Assert.Throws(() => - _uut!.GetInstalledPackages(_projectPath!, includeTransitive)); + _uut.GetInstalledPackages(_projectPath, includeTransitive)); Assert.AreEqual($"Failed to validate project assets for project {_projectPath}", exception!.Message); } @@ -153,10 +140,10 @@ public void GetInstalledPackages_Should_ThrowReferencedPackageReaderException_If_TargetsArrayDoesNotContainAnyElement( [Values] bool includeTransitive) { - _lockFileMock!.SetupGet(m => m.Targets).Returns(Enumerable.Empty()); + _lockFileMock.SetupGet(m => m.Targets).Returns(Enumerable.Empty()); var exception = Assert.Throws(() => - _uut!.GetInstalledPackages(_projectPath!, includeTransitive)); + _uut.GetInstalledPackages(_projectPath, includeTransitive)); Assert.AreEqual($"Failed to validate project assets for project {_projectPath}", exception!.Message); } @@ -165,13 +152,13 @@ public void public void GetInstalledPackages_Should_ThrowReferencedPackageReaderException_If_NotIncludingTransitive_And_PackageSpecFrameworkInformationGetFails() { - _packageSpecMock!.SetupGet(m => m.TargetFrameworks) + _packageSpecMock.SetupGet(m => m.TargetFrameworks) .Returns(Enumerable.Empty()); var exception = Assert.Throws(() => - _uut!.GetInstalledPackages(_projectPath!, false)); + _uut.GetInstalledPackages(_projectPath, false)); Assert.AreEqual( - $"Failed to identify the target framework information for {_lockFileTargets!.First().Object}", + $"Failed to identify the target framework information for {_lockFileTargets.First().Object}", exception!.Message); Assert.IsInstanceOf(typeof(InvalidOperationException), exception.InnerException); Assert.AreEqual(exception.InnerException!.Message, "Sequence contains no matching element"); @@ -181,57 +168,57 @@ public void public void GetInstalledPackages_Should_ThrowReferencedPackageReaderException_If_IncludingTransitive_And_PackageSpecFrameworkInformationGetFails() { - _packageSpecMock!.SetupGet(m => m.TargetFrameworks) + _packageSpecMock.SetupGet(m => m.TargetFrameworks) .Returns(Enumerable.Empty()); - var result = _uut!.GetInstalledPackages(_projectPath!, true); + var result = _uut.GetInstalledPackages(_projectPath, true); CollectionAssert.AreEquivalent( - _lockFileLibraries!.Select(l => - new PackageSearchMetadataMock(new PackageIdentity(l.Object.Name, l.Object.Version))), + _lockFileLibraries.Select(l => + new PackageIdentity(l.Object.Name, l.Object.Version)), result); } [Test] public void GetInstalledPackages_Should_GetProjectFromPath([Values] bool includeTransitive) { - _uut!.GetInstalledPackages(_projectPath!, includeTransitive); - _msBuild!.Verify(m => m.GetProject(It.IsAny()), Times.Once); - _msBuild!.Verify(m => m.GetProject(_projectPath!), Times.Once); + _uut.GetInstalledPackages(_projectPath, includeTransitive); + _msBuild.Verify(m => m.GetProject(It.IsAny()), Times.Once); + _msBuild.Verify(m => m.GetProject(_projectPath), Times.Once); } [Test] public void GetInstalledPackages_Should_LoadAssetsFileFromProject([Values] bool includeTransitive) { - _uut!.GetInstalledPackages(_projectPath!, includeTransitive); - _projectMock!.Verify(m => m.GetAssetsPath(), Times.Once); - _lockFileFactory!.Verify(m => m.GetFromFile(It.IsAny()), Times.Once); - _lockFileFactory!.Verify(m => m.GetFromFile(_assetsFilePath!), Times.Once); + _uut.GetInstalledPackages(_projectPath, includeTransitive); + _projectMock.Verify(m => m.GetAssetsPath(), Times.Once); + _lockFileFactory.Verify(m => m.GetFromFile(It.IsAny()), Times.Once); + _lockFileFactory.Verify(m => m.GetFromFile(_assetsFilePath), Times.Once); } [Test] public void GetInstalledPackages_Should_ReturnCorrectValues_If_IncludingTransitive() { - var result = _uut!.GetInstalledPackages(_projectPath!, true); + var result = _uut.GetInstalledPackages(_projectPath, true); CollectionAssert.AreEquivalent( - _lockFileLibraries!.Select(l => - new PackageSearchMetadataMock(new PackageIdentity(l.Object.Name, l.Object.Version))), + _lockFileLibraries.Select(l => + new PackageIdentity(l.Object.Name, l.Object.Version)), result); } [Test] public void GetInstalledPackages_Should_ReturnCorrectValues_If_NotIncludingTransitive() { - var result = _uut!.GetInstalledPackages(_projectPath!, false); + var result = _uut.GetInstalledPackages(_projectPath, false); - var expectedReferences = _packageReferencesFromProjectForFramework!.SelectMany(p => p.Value) + var expectedReferences = _packageReferencesFromProjectForFramework.SelectMany(p => p.Value) .Distinct() .ToArray(); - var expectedResult = _lockFileLibraries!.Where(l => + var expectedResult = _lockFileLibraries.Where(l => expectedReferences.Any(e => e.PackageName.Equals(l.Object.Name)) && expectedReferences.Any(e => e.Version!.Equals(l.Object.Version))) .ToArray(); CollectionAssert.AreEquivalent( expectedResult.Select(l => - new PackageSearchMetadataMock(new PackageIdentity(l.Object.Name, l.Object.Version))), + new PackageIdentity(l.Object.Name, l.Object.Version)), result); } @@ -242,25 +229,24 @@ public void GetInstalledPackages_Should_ReturnCorrectValues_If_IncludingTransiti _ignoredPackages = _ignoredPackages!.Append(ignoredPackageName); _uut = new ReferencedPackageReader(_ignoredPackages, - _msBuild!.Object, - _lockFileFactory!.Object, - _metadataBuilderFactory!.Object); - var result = _uut!.GetInstalledPackages(_projectPath!, true); + _msBuild.Object, + _lockFileFactory.Object); + var result = _uut.GetInstalledPackages(_projectPath, true); CollectionAssert.AreEquivalent( - _lockFileLibraries!.Where(l => l.Object.Name != ignoredPackageName) + _lockFileLibraries.Where(l => l.Object.Name != ignoredPackageName) .Select(l => - new PackageSearchMetadataMock(new PackageIdentity(l.Object.Name, l.Object.Version))), + new PackageIdentity(l.Object.Name, l.Object.Version)), result); } [Test] public void GetInstalledPackages_Should_ReturnCorrectValues_If_NotIncludingTransitive_If_IgnoringPackages() { - var directReferences = _packageReferencesFromProjectForFramework!.SelectMany(p => p.Value) + var directReferences = _packageReferencesFromProjectForFramework.SelectMany(p => p.Value) .Distinct() .ToArray(); - var directReferencesResult = _lockFileLibraries!.Where(l => + var directReferencesResult = _lockFileLibraries.Where(l => directReferences.Any(e => e.PackageName.Equals(l.Object.Name)) && directReferences.Any(e => e.Version!.Equals(l.Object.Version))) .ToArray(); @@ -269,15 +255,14 @@ public void GetInstalledPackages_Should_ReturnCorrectValues_If_NotIncludingTrans _ignoredPackages = _ignoredPackages!.Append(ignoredPackageName); _uut = new ReferencedPackageReader(_ignoredPackages, - _msBuild!.Object, - _lockFileFactory!.Object, - _metadataBuilderFactory!.Object); - var result = _uut!.GetInstalledPackages(_projectPath!, false); + _msBuild.Object, + _lockFileFactory.Object); + var result = _uut.GetInstalledPackages(_projectPath, false); CollectionAssert.AreEquivalent( directReferencesResult.Where(l => l.Object.Name != ignoredPackageName) .Select(l => - new PackageSearchMetadataMock(new PackageIdentity(l.Object.Name, l.Object.Version))), + new PackageIdentity(l.Object.Name, l.Object.Version)), result); } @@ -285,9 +270,9 @@ public void GetInstalledPackages_Should_ReturnCorrectValues_If_NotIncludingTrans public void GetInstalledPackages_Should_ReturnEmptyCollection_When_ProjectHasNoPackageReferences_And_IsNotTransitive() { - _projectMock!.Setup(m => m.GetPackageReferenceCount()).Returns(0); - _projectMock!.Setup(m => m.GetEvaluatedIncludes()).Returns(Enumerable.Empty()); - var result = _uut!.GetInstalledPackages(_projectPath!, false); + _projectMock.Setup(m => m.GetPackageReferenceCount()).Returns(0); + _projectMock.Setup(m => m.GetEvaluatedIncludes()).Returns(Enumerable.Empty()); + var result = _uut.GetInstalledPackages(_projectPath, false); Assert.That(result.Count(), Is.EqualTo(0)); } diff --git a/tests/NuGetUtility.Test/ReferencedPackagesReader/ReferencedPackagesReaderIntegrationTest.cs b/tests/NuGetUtility.Test/ReferencedPackagesReader/ReferencedPackagesReaderIntegrationTest.cs index 805c32ca..c409c553 100644 --- a/tests/NuGetUtility.Test/ReferencedPackagesReader/ReferencedPackagesReaderIntegrationTest.cs +++ b/tests/NuGetUtility.Test/ReferencedPackagesReader/ReferencedPackagesReaderIntegrationTest.cs @@ -1,7 +1,6 @@ -using NuGetUtility.ReferencedPackagesReader; +using NuGetUtility.ReferencedPackagesReader; using NuGetUtility.Wrapper.MsBuildWrapper; using NuGetUtility.Wrapper.NuGetWrapper.ProjectModel; -using NuGetUtility.Wrapper.NuGetWrapper.Protocol.Core.Types; namespace NuGetUtility.Test.ReferencedPackagesReader { @@ -13,8 +12,7 @@ public void SetUp() { _uut = new ReferencedPackageReader(Enumerable.Empty(), new MsBuildAbstraction(), - new LockFileFactory(), - new PackageSearchMetadataBuilderFactory()); + new LockFileFactory()); } private ReferencedPackageReader? _uut; @@ -49,7 +47,7 @@ public void GetInstalledPackagesShould_ReturnTransitiveNuget() var result = _uut!.GetInstalledPackages(path, true).ToArray(); Assert.That(result.Count, Is.EqualTo(3)); - var titles = result.Select(metadata => metadata.Title).ToArray(); + var titles = result.Select(metadata => metadata.Id).ToArray(); Assert.That(titles.Contains("Moq"), Is.True); Assert.That(titles.Contains("Castle.Core"), Is.True); Assert.That(titles.Contains("System.Diagnostics.EventLog"), Is.True);