Skip to content

Commit

Permalink
Fix sonarcloud complaints
Browse files Browse the repository at this point in the history
  • Loading branch information
sensslen committed Dec 28, 2023
1 parent 3abb6af commit 7ccedad
Show file tree
Hide file tree
Showing 12 changed files with 109 additions and 100 deletions.
3 changes: 2 additions & 1 deletion src/NuGetUtility/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ public static bool Like(this string str, string pattern)
{
return new Regex(
"^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
RegexOptions.IgnoreCase | RegexOptions.Singleline
RegexOptions.IgnoreCase | RegexOptions.Singleline,
TimeSpan.FromMilliseconds(100)
).IsMatch(str);
}
}
Expand Down
31 changes: 9 additions & 22 deletions src/NuGetUtility/LicenseValidator/LicenseValidator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using System.Collections.Immutable;
using NuGetUtility.Extensions;
using NuGetUtility.PackageInformationReader;
using NuGetUtility.Wrapper.HttpClientWrapper;
Expand All @@ -13,9 +14,9 @@ public class LicenseValidator
private readonly IEnumerable<string> _allowedLicenses;
private readonly IFileDownloader _fileDownloader;
private readonly string[] _ignoredPackages;
private readonly Dictionary<Uri, string> _licenseMapping;
private readonly IImmutableDictionary<Uri, string> _licenseMapping;

public LicenseValidator(Dictionary<Uri, string> licenseMapping,
public LicenseValidator(IImmutableDictionary<Uri, string> licenseMapping,
IEnumerable<string> allowedLicenses,
IFileDownloader fileDownloader,
string[] ignoredPackages)
Expand Down Expand Up @@ -77,8 +78,8 @@ private void AddOrUpdateLicense(
origin,
new List<ValidationError> { error });
result.AddOrUpdate(new LicenseNameAndVersion(info.Identity.Id, info.Identity.Version),
key => CreateResult(key, newValue),
(key, oldValue) => UpdateResult(key, oldValue, newValue));
newValue,
(key, oldValue) => UpdateResult(oldValue, newValue));
}

private void AddOrUpdateLicense(
Expand All @@ -94,12 +95,11 @@ private void AddOrUpdateLicense(
license,
origin);
result.AddOrUpdate(new LicenseNameAndVersion(info.Identity.Id, info.Identity.Version),
key => CreateResult(key, newValue),
(key, oldValue) => UpdateResult(key, oldValue, newValue));
newValue,
(key, oldValue) => UpdateResult(oldValue, newValue));
}

private LicenseValidationResult UpdateResult(LicenseNameAndVersion _,
LicenseValidationResult oldValue,
private LicenseValidationResult UpdateResult(LicenseValidationResult oldValue,
LicenseValidationResult newValue)
{
oldValue.ValidationErrors.AddRange(newValue.ValidationErrors);
Expand All @@ -111,11 +111,6 @@ private LicenseValidationResult UpdateResult(LicenseNameAndVersion _,
return oldValue;
}

private LicenseValidationResult CreateResult(LicenseNameAndVersion _, LicenseValidationResult newValue)
{
return newValue;
}

private void ValidateLicenseByMetadata(IPackageMetadata info,
string context,
ConcurrentDictionary<LicenseNameAndVersion, LicenseValidationResult> result)
Expand Down Expand Up @@ -212,15 +207,7 @@ private bool IsLicenseValid(string licenseId)
return true;
}

foreach (string allowedLicense in _allowedLicenses)
{
if (allowedLicense.Equals(licenseId))
{
return true;
}
}

return false;
return _allowedLicenses.Any(l => l.Equals(licenseId));
}

private string GetLicenseNotAllowedMessage(string license)
Expand Down
80 changes: 42 additions & 38 deletions src/NuGetUtility/LicenseValidator/UrlToLicenseMapping.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Collections.Immutable;

namespace NuGetUtility.LicenseValidator
{
public static class UrlToLicenseMapping
Expand All @@ -10,44 +12,46 @@ public static class UrlToLicenseMapping
private const string MsEula = "MS-EULA";
private const string MsEulaNonRedistributable = "MS-EULA-Non-Redistributable";

public static Dictionary<Uri, string> Default = new Dictionary<Uri, string>
{
{ new Uri("http://www.apache.org/licenses/LICENSE-2.0.html"), Apache20 },
{ new Uri("http://www.apache.org/licenses/LICENSE-2.0"), Apache20 },
{ new Uri("http://opensource.org/licenses/Apache-2.0"), Apache20 },
{ new Uri("http://aws.amazon.com/apache2.0/"), Apache20 },
{ new Uri("http://logging.apache.org/log4net/license.html"), Apache20 },
{ new Uri("https://github.com/owin-contrib/owin-hosting/blob/master/LICENSE.txt"), Apache20 },
{ new Uri("https://raw.githubusercontent.com/aspnet/Home/2.0.0/LICENSE.txt"), Apache20 },
{ new Uri("http://opensource.org/licenses/BSD-3-Clause"), Bsd3Clause },
{
new Uri("https://github.com/Microsoft/Microsoft.IO.RecyclableMemoryStream/blob/master/LICENSE"), Mit
},
{ new Uri("https://github.com/AutoMapper/AutoMapper/blob/master/LICENSE.txt"), Mit },
{ new Uri("https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE"), Mit },
{ new Uri("https://raw.githubusercontent.com/hey-red/markdownsharp/master/LICENSE"), Mit },
{ new Uri("https://raw.github.com/JamesNK/Newtonsoft.Json/master/LICENSE.md"), Mit },
{ new Uri("https://licenses.nuget.org/MIT"), Mit },
{ new Uri("http://opensource.org/licenses/MIT"), Mit },
{ new Uri("http://opensource.org/licenses/mit-license.php"), Mit },
{ new Uri("http://www.opensource.org/licenses/mit-license.php"), Mit },
{ new Uri("http://max.mit-license.org/"), Mit },
{ new Uri("https://github.com/dotnet/corefx/blob/master/LICENSE.TXT"), Mit },
{ new Uri("http://go.microsoft.com/fwlink/?linkid=833178"), Mit },
{ new Uri("http://sourceforge.net/directory/license:mit/"), Mit },
{ new Uri("http://www.gnu.org/licenses/old-licenses/gpl-2.0.html"), Gpl20 },
{ new Uri("http://opensource.org/licenses/MS-PL"), MsPl },
{ new Uri("http://www.opensource.org/licenses/ms-pl"), MsPl },
{ new Uri("https://www.microsoft.com/web/webpi/eula/aspnetmvc3update-eula.htm"), MsEula },
{ new Uri("http://go.microsoft.com/fwlink/?LinkID=214339"), MsEula },
{ new Uri("https://www.microsoft.com/web/webpi/eula/net_library_eula_enu.htm"), MsEula },
{ new Uri("http://go.microsoft.com/fwlink/?LinkId=329770"), MsEula },
{ new Uri("http://go.microsoft.com/fwlink/?LinkId=529443"), MsEula },
public static IImmutableDictionary<Uri, string> Default { get; } = ImmutableDictionary.CreateRange(
new[]
{
new Uri("https://www.microsoft.com/web/webpi/eula/dotnet_library_license_non_redistributable.htm"),
MsEulaNonRedistributable
},
{ new Uri("http://go.microsoft.com/fwlink/?LinkId=529444"), MsEulaNonRedistributable }
};
KeyValuePair.Create( new Uri("http://www.apache.org/licenses/LICENSE-2.0.html"), Apache20 ),
KeyValuePair.Create( new Uri("http://www.apache.org/licenses/LICENSE-2.0"), Apache20 ),
KeyValuePair.Create( new Uri("http://opensource.org/licenses/Apache-2.0"), Apache20 ),
KeyValuePair.Create( new Uri("http://aws.amazon.com/apache2.0/"), Apache20 ),
KeyValuePair.Create( new Uri("http://logging.apache.org/log4net/license.html"), Apache20 ),
KeyValuePair.Create( new Uri("https://github.com/owin-contrib/owin-hosting/blob/master/LICENSE.txt"), Apache20 ),
KeyValuePair.Create( new Uri("https://raw.githubusercontent.com/aspnet/Home/2.0.0/LICENSE.txt"), Apache20 ),
KeyValuePair.Create( new Uri("http://opensource.org/licenses/BSD-3-Clause"), Bsd3Clause ),
KeyValuePair.Create(
new Uri("https://github.com/Microsoft/Microsoft.IO.RecyclableMemoryStream/blob/master/LICENSE"), Mit
),
KeyValuePair.Create( new Uri("https://github.com/AutoMapper/AutoMapper/blob/master/LICENSE.txt"), Mit ),
KeyValuePair.Create( new Uri("https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE"), Mit ),
KeyValuePair.Create( new Uri("https://raw.githubusercontent.com/hey-red/markdownsharp/master/LICENSE"), Mit ),
KeyValuePair.Create( new Uri("https://raw.github.com/JamesNK/Newtonsoft.Json/master/LICENSE.md"), Mit ),
KeyValuePair.Create( new Uri("https://licenses.nuget.org/MIT"), Mit ),
KeyValuePair.Create( new Uri("http://opensource.org/licenses/MIT"), Mit ),
KeyValuePair.Create( new Uri("http://opensource.org/licenses/mit-license.php"), Mit ),
KeyValuePair.Create( new Uri("http://www.opensource.org/licenses/mit-license.php"), Mit ),
KeyValuePair.Create( new Uri("http://max.mit-license.org/"), Mit ),
KeyValuePair.Create( new Uri("https://github.com/dotnet/corefx/blob/master/LICENSE.TXT"), Mit ),
KeyValuePair.Create( new Uri("http://go.microsoft.com/fwlink/?linkid=833178"), Mit ),
KeyValuePair.Create( new Uri("http://sourceforge.net/directory/license:mit/"), Mit ),
KeyValuePair.Create( new Uri("http://www.gnu.org/licenses/old-licenses/gpl-2.0.html"), Gpl20 ),
KeyValuePair.Create( new Uri("http://opensource.org/licenses/MS-PL"), MsPl ),
KeyValuePair.Create( new Uri("http://www.opensource.org/licenses/ms-pl"), MsPl ),
KeyValuePair.Create( new Uri("https://www.microsoft.com/web/webpi/eula/aspnetmvc3update-eula.htm"), MsEula ),
KeyValuePair.Create( new Uri("http://go.microsoft.com/fwlink/?LinkID=214339"), MsEula ),
KeyValuePair.Create( new Uri("https://www.microsoft.com/web/webpi/eula/net_library_eula_enu.htm"), MsEula ),
KeyValuePair.Create( new Uri("http://go.microsoft.com/fwlink/?LinkId=329770"), MsEula ),
KeyValuePair.Create( new Uri("http://go.microsoft.com/fwlink/?LinkId=529443"), MsEula ),
KeyValuePair.Create(
new Uri("https://www.microsoft.com/web/webpi/eula/dotnet_library_license_non_redistributable.htm"),
MsEulaNonRedistributable
),
KeyValuePair.Create( new Uri("http://go.microsoft.com/fwlink/?LinkId=529444"), MsEulaNonRedistributable )
}
);
}
}
2 changes: 1 addition & 1 deletion src/NuGetUtility/Output/Table/TableOutputFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ await TablePrinterExtensions
.Print();
}

private record ColumnDefinition(string Title, Func<LicenseValidationResult, object?> PropertyAccessor, Func<LicenseValidationResult, bool> IsRelevant, bool Enabled = false)
private sealed record ColumnDefinition(string Title, Func<LicenseValidationResult, object?> PropertyAccessor, Func<LicenseValidationResult, bool> IsRelevant, bool Enabled = false)
{
public bool Enabled { get; set; } = Enabled;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private PackageSearchResult TryGetPackageInfoFromCustomInformation(PackageIdenti
}
}

private record PackageSearchResult
private sealed record PackageSearchResult
{
public bool Success { get; }
public IPackageMetadata? Metadata { get; }
Expand Down
16 changes: 5 additions & 11 deletions src/NuGetUtility/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json;
using System.Collections.Immutable;
using System.Text.Json;
using McMaster.Extensions.CommandLineUtils;
using NuGet.Configuration;
using NuGet.Protocol.Core.Types;
Expand Down Expand Up @@ -92,7 +93,7 @@ private async Task<int> OnExecuteAsync(CancellationToken cancellationToken)
using var httpClient = new HttpClient();
string[] inputFiles = GetInputFiles();
string[] ignoredPackages = GetIgnoredPackages();
Dictionary<Uri, string> licenseMappings = GetLicenseMappings();
IImmutableDictionary<Uri, string> licenseMappings = GetLicenseMappings();
string[] allowedLicenses = GetAllowedLicenses();
CustomPackageInformation[] overridePackageInformation = GetOverridePackageInformation();
IFileDownloader urlLicenseFileDownloader = GetFileDownloader(httpClient);
Expand Down Expand Up @@ -207,7 +208,7 @@ private string[] GetAllowedLicenses()
return JsonSerializer.Deserialize<string[]>(File.ReadAllText(AllowedLicenses))!;
}

private Dictionary<Uri, string> GetLicenseMappings()
private IImmutableDictionary<Uri, string> GetLicenseMappings()
{
if (LicenseMapping == null)
{
Expand All @@ -219,14 +220,7 @@ private Dictionary<Uri, string> GetLicenseMappings()
Dictionary<Uri, string> userDictionary = JsonSerializer.Deserialize<Dictionary<Uri, string>>(File.ReadAllText(LicenseMapping),
serializerOptions)!;

UrlToLicenseMapping.Default.ToList().ForEach(x =>
{
if (!userDictionary.ContainsKey(x.Key))
{
userDictionary.Add(x.Key, x.Value);
}
});
return userDictionary;
return UrlToLicenseMapping.Default.SetItems(userDictionary);
}

private string[] GetIgnoredPackages()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,9 @@ public override void Write(Utf8JsonWriter writer, LicenseValidationResult value,
writer.WriteStartObject();
foreach (System.Reflection.PropertyInfo propertyInfo in value.GetType().GetProperties())
{
if (propertyInfo.Name == nameof(value.ValidationErrors))
if (propertyInfo.Name == nameof(value.ValidationErrors) && !value.ValidationErrors.Any())
{
if (!value.ValidationErrors.Any())
{
continue;
}
continue;
}
object? writeValue = propertyInfo.GetValue(value);
if (writeValue != null)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace NuGetUtility.Wrapper.NuGetWrapper.Versioning
{
public interface INuGetVersion { }
public interface INuGetVersion : IComparable<INuGetVersion> { }
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace NuGetUtility.Wrapper.NuGetWrapper.Versioning
{
internal class WrappedNuGetVersion : INuGetVersion, IComparable
internal class WrappedNuGetVersion : INuGetVersion
{
private readonly NuGetVersion _version;

Expand All @@ -16,24 +16,14 @@ public WrappedNuGetVersion(string version)
_version = new NuGetVersion(version);
}

public override bool Equals(object? other)
public override bool Equals(object? obj)
{
if (other == null)
if (obj is WrappedNuGetVersion other)
{
return false;
return Equals(other);
}

if (other.GetType() != GetType())
{
return false;
}

if (ReferenceEquals(this, other))
{
return true;
}

return Equals((other as WrappedNuGetVersion)!);
return false;
}

private bool Equals(WrappedNuGetVersion other)
Expand All @@ -51,15 +41,17 @@ public override string ToString()
return _version.ToString();
}

public int CompareTo(object? other)
public int CompareTo(object? obj)
{
if (other is not WrappedNuGetVersion wrappedNuGetVersion)
if (obj is not WrappedNuGetVersion wrappedNuGetVersion)
{
throw new ArgumentException($"{nameof(other)} must be of type {nameof(WrappedNuGetVersion)} to be comparable.");
throw new ArgumentException($"{nameof(obj)} must be of type {nameof(WrappedNuGetVersion)} to be comparable.");
}
return _version.CompareTo(wrappedNuGetVersion._version);
}

public int CompareTo(INuGetVersion? other) => _version.CompareTo((other as WrappedNuGetVersion)?._version);

public NuGetVersion Unwrap()
{
return _version;
Expand All @@ -75,5 +67,34 @@ internal static bool TryParse(string stringVersion, out WrappedNuGetVersion vers
version = default!;
return false;
}

public static bool operator ==(WrappedNuGetVersion left, WrappedNuGetVersion right)
{
if (left is null)
{
return right is null;
}
return left.Equals(right);
}
public static bool operator !=(WrappedNuGetVersion left, WrappedNuGetVersion right)
{
return !(left == right);
}
public static bool operator >(WrappedNuGetVersion left, WrappedNuGetVersion right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <(WrappedNuGetVersion left, WrappedNuGetVersion right)
{
return left.CompareTo(right) < 0;
}
public static bool operator >=(WrappedNuGetVersion left, WrappedNuGetVersion right)
{
return !(left < right);
}
public static bool operator <=(WrappedNuGetVersion left, WrappedNuGetVersion right)
{
return !(left > right);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public NuGetVersion(string version)
_version = version;
}

public int CompareTo(INuGetVersion? other) => throw new NotImplementedException();

public override string ToString()
{
return _version;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Immutable;
using AutoFixture;
using NSubstitute;
using NuGetUtility.LicenseValidator;
Expand All @@ -21,7 +22,7 @@ public void SetUp()
{
var fixture = new Fixture();
_fileDownloader = Substitute.For<IFileDownloader>();
_licenseMapping = fixture.Create<Dictionary<Uri, string>>();
_licenseMapping = ImmutableDictionary.CreateRange(fixture.Create<Dictionary<Uri, string>>());
_allowedLicenses = fixture.CreateMany<string>();
_context = fixture.Create<string>();
_projectUrl = fixture.Create<Uri>();
Expand All @@ -34,7 +35,7 @@ public void SetUp()
}

private NuGetUtility.LicenseValidator.LicenseValidator _uut = null!;
private Dictionary<Uri, string> _licenseMapping = null!;
private IImmutableDictionary<Uri, string> _licenseMapping = null!;
private IEnumerable<string> _allowedLicenses = null!;
private string _context = null!;
private IFileDownloader _fileDownloader = null!;
Expand Down
2 changes: 2 additions & 0 deletions tests/NuGetUtility.Test/Output/TestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ public NuGetVersion(string version)
_version = version;
}

public int CompareTo(INuGetVersion? other) => throw new NotImplementedException();

public override string ToString()
{
return _version;
Expand Down

0 comments on commit 7ccedad

Please sign in to comment.