Skip to content

Commit

Permalink
GitTools#3334 - fix nullable warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
arturcic committed Feb 17, 2023
1 parent f6bae02 commit 6de89f0
Show file tree
Hide file tree
Showing 21 changed files with 63 additions and 60 deletions.
5 changes: 4 additions & 1 deletion src/GitVersion.Core/Core/GitVersionModule.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using GitVersion.Extensions;
using Microsoft.Extensions.DependencyInjection;

namespace GitVersion;
Expand All @@ -6,8 +7,10 @@ public abstract class GitVersionModule : IGitVersionModule
{
public abstract void RegisterTypes(IServiceCollection services);

protected static IEnumerable<Type> FindAllDerivedTypes<T>(Assembly assembly)
protected static IEnumerable<Type> FindAllDerivedTypes<T>(Assembly? assembly)
{
assembly.NotNull();

var derivedType = typeof(T);
return assembly.GetTypes().Where(t => t != derivedType && derivedType.IsAssignableFrom(t));
}
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersion.Core/Core/MergeCommitFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ internal class MergeCommitFinder
{
private readonly IEnumerable<IBranch> excludedBranches;
private readonly ILog log;
private readonly Dictionary<IBranch?, List<BranchCommit>> mergeBaseCommitsCache = new();
private readonly Dictionary<IBranch, List<BranchCommit>> mergeBaseCommitsCache = new();
private readonly RepositoryStore repositoryStore;
private readonly GitVersionConfiguration configuration;

Expand Down
8 changes: 2 additions & 6 deletions src/GitVersion.Core/Extensions/CommonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ public static string NotNullOrEmpty([NotNull] this string? value, [CallerArgumen
throw new ArgumentException("The parameter is null or empty.", name);
}

#pragma warning disable CS8777 // Parameter must have a non-null value when exiting.
return value!;
#pragma warning restore CS8777 // Parameter must have a non-null value when exiting.
return value;
}

public static string NotNullOrWhitespace([NotNull] this string? value, [CallerArgumentExpression("value")] string name = "")
Expand All @@ -27,8 +25,6 @@ public static string NotNullOrWhitespace([NotNull] this string? value, [CallerAr
throw new ArgumentException("The parameter is null or empty or contains only white space.", name);
}

#pragma warning disable CS8777 // Parameter must have a non-null value when exiting.
return value!;
#pragma warning restore CS8777 // Parameter must have a non-null value when exiting.
return value;
}
}
4 changes: 2 additions & 2 deletions src/GitVersion.Core/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ public static IServiceCollection AddModule(this IServiceCollection serviceCollec
return serviceCollection;
}

public static TService? GetServiceForType<TService, TType>(this IServiceProvider serviceProvider) =>
serviceProvider.GetServices<TService>().SingleOrDefault(t => t?.GetType() == typeof(TType));
public static TService GetServiceForType<TService, TType>(this IServiceProvider serviceProvider) =>
serviceProvider.GetServices<TService>().Single(t => t?.GetType() == typeof(TType));
}
4 changes: 2 additions & 2 deletions src/GitVersion.Core/Git/ReferenceName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ public static ReferenceName Parse(string canonicalName)
public bool IsPullRequest { get; }

public bool Equals(ReferenceName? other) => equalityHelper.Equals(this, other);
public int CompareTo(ReferenceName other) => comparerHelper.Compare(this, other);
public override bool Equals(object obj) => Equals((obj as ReferenceName));
public int CompareTo(ReferenceName? other) => comparerHelper.Compare(this, other);
public override bool Equals(object? obj) => Equals((obj as ReferenceName));
public override int GetHashCode() => equalityHelper.GetHashCode(this);
public override string ToString() => Friendly;

Expand Down
4 changes: 3 additions & 1 deletion src/GitVersion.Core/OutputVariables/VersionVariables.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using GitVersion.Extensions;
using GitVersion.Helpers;
using YamlDotNet.Serialization;
using static GitVersion.Extensions.ObjectExtensions;
Expand Down Expand Up @@ -115,7 +116,8 @@ private static VersionVariables FromDictionary(IEnumerable<KeyValuePair<string,
.Select(p => properties?.Single(v => string.Equals(v.Key, p.Name, StringComparison.InvariantCultureIgnoreCase)).Value)
.Cast<object>()
.ToArray();
return (VersionVariables)Activator.CreateInstance(type, ctorArgs);
var instance = Activator.CreateInstance(type, ctorArgs).NotNull();
return (VersionVariables)instance;
}

public static VersionVariables FromJson(string json)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class VersionStrategyModule : GitVersionModule
public override void RegisterTypes(IServiceCollection services)
{
var versionStrategies = FindAllDerivedTypes<IVersionStrategy>(Assembly.GetAssembly(GetType()))
.Where(x => !x.IsAbstract && !x.IsInterface);
.Where(x => x is { IsAbstract: false, IsInterface: false });

foreach (var versionStrategy in versionStrategies)
{
Expand Down
25 changes: 12 additions & 13 deletions src/GitVersion.Core/VersionCalculation/IncrementStrategyFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public VersionField DetermineIncrementedField(GitVersionContext context, BaseVer
{
configuration.NotNull();

var commitMessageIncrement = FindCommitMessageIncrement(this.repository, context, configuration, baseVersion.BaseVersionSource);
var commitMessageIncrement = FindCommitMessageIncrement(context, configuration, baseVersion.BaseVersionSource);

var defaultIncrement = configuration.Increment.ToVersionField();

Expand Down Expand Up @@ -73,8 +73,7 @@ public VersionField DetermineIncrementedField(GitVersionContext context, BaseVer
: null;
}

private VersionField? FindCommitMessageIncrement(IGitRepository repository, GitVersionContext context,
EffectiveConfiguration configuration, ICommit? baseCommit)
private VersionField? FindCommitMessageIncrement(GitVersionContext context, EffectiveConfiguration configuration, ICommit? baseCommit)
{
if (baseCommit == null) return null;

Expand All @@ -83,7 +82,7 @@ public VersionField DetermineIncrementedField(GitVersionContext context, BaseVer
return null;
}

var commits = GetIntermediateCommits(repository, baseCommit, context.CurrentCommit);
var commits = GetIntermediateCommits(baseCommit, context.CurrentCommit);

// consider commit messages since latest tag only (see #3071)
var tags = new HashSet<string?>(repository.Tags.Select(t => t.TargetSha));
Expand All @@ -106,33 +105,33 @@ private static Regex TryGetRegexOrDefault(string? messageRegex, Regex defaultReg
: CompiledRegexCache.GetOrAdd(messageRegex, pattern => new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase));

/// <summary>
/// Get the sequence of commits in a <paramref name="repository"/> between a <paramref name="baseCommit"/> (exclusive)
/// Get the sequence of commits in a repository between a <paramref name="baseCommit"/> (exclusive)
/// and a particular <paramref name="headCommit"/> (inclusive)
/// </summary>
private IEnumerable<ICommit> GetIntermediateCommits(IGitRepository repository, IGitObject baseCommit, ICommit? headCommit)
private IEnumerable<ICommit> GetIntermediateCommits(IGitObject baseCommit, ICommit? headCommit)
{
var map = GetHeadCommitsMap(repository, headCommit);
var map = GetHeadCommitsMap(headCommit);
if (!map.TryGetValue(baseCommit.Sha, out var baseIndex)) return Enumerable.Empty<ICommit>();
var commitAfterBaseIndex = baseIndex + 1;
var headCommits = GetHeadCommits(repository, headCommit);
var headCommits = GetHeadCommits(headCommit);
return new ArraySegment<ICommit>(headCommits, commitAfterBaseIndex, headCommits.Length - commitAfterBaseIndex);
}

/// <summary>
/// Get a mapping of commit shas to their zero-based position in the sequence of commits from the beginning of a
/// <paramref name="repository"/> to a particular <paramref name="headCommit"/>
/// repository to a particular <paramref name="headCommit"/>
/// </summary>
private Dictionary<string, int> GetHeadCommitsMap(IGitRepository repository, ICommit? headCommit) =>
private Dictionary<string, int> GetHeadCommitsMap(ICommit? headCommit) =>
this.headCommitsMapCache.GetOrAdd(headCommit?.Sha ?? "NULL", () =>
GetHeadCommits(repository, headCommit)
GetHeadCommits(headCommit)
.Select((commit, index) => (commit.Sha, Index: index))
.ToDictionary(t => t.Sha, t => t.Index));

/// <summary>
/// Get the sequence of commits from the beginning of a <paramref name="repository"/> to a particular
/// Get the sequence of commits from the beginning of a repository to a particular
/// <paramref name="headCommit"/> (inclusive)
/// </summary>
private ICommit[] GetHeadCommits(IGitRepository repository, ICommit? headCommit) =>
private ICommit[] GetHeadCommits(ICommit? headCommit) =>
this.headCommitsCache.GetOrAdd(headCommit?.Sha ?? "NULL", () =>
GetCommitsReacheableFromHead(repository, headCommit).ToArray());

Expand Down
8 changes: 4 additions & 4 deletions src/GitVersion.Core/VersionCalculation/NextVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ public NextVersion(SemanticVersion incrementedVersion, BaseVersion baseVersion,
Branch = branch.NotNull();
}

public int CompareTo(NextVersion other) => IncrementedVersion.CompareTo(other.IncrementedVersion);
public int CompareTo(NextVersion? other) => IncrementedVersion.CompareTo(other?.IncrementedVersion);

public static bool operator ==(NextVersion left, NextVersion right) => left.CompareTo(right) == 0;
public static bool operator ==(NextVersion left, NextVersion? right) => left.CompareTo(right) == 0;

public static bool operator !=(NextVersion left, NextVersion right) => left.CompareTo(right) != 0;

Expand All @@ -40,9 +40,9 @@ public NextVersion(SemanticVersion incrementedVersion, BaseVersion baseVersion,

public static bool operator >=(NextVersion left, NextVersion right) => left.CompareTo(right) >= 0;

public bool Equals(NextVersion other) => this == other;
public bool Equals(NextVersion? other) => this == other;

public override bool Equals(object other) => other is NextVersion nextVersion && Equals(nextVersion);
public override bool Equals(object? other) => other is NextVersion nextVersion && Equals(nextVersion);

public override string ToString() => $"{BaseVersion} | {IncrementedVersion}";

Expand Down
16 changes: 10 additions & 6 deletions src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public virtual NextVersion FindVersion()
if (Context.IsCurrentCommitTagged)
{
// Will always be 0, don't bother with the +0 on tags
var semanticVersionBuildMetaData = this.mainlineVersionCalculator.CreateVersionBuildMetaData(Context.CurrentCommit!);
var semanticVersionBuildMetaData = this.mainlineVersionCalculator.CreateVersionBuildMetaData(Context.CurrentCommit);
semanticVersionBuildMetaData.CommitsSinceTag = null;
var semanticVersion = new SemanticVersion(Context.CurrentCommitTaggedVersion) { BuildMetaData = semanticVersionBuildMetaData };
taggedSemanticVersion = semanticVersion;
Expand Down Expand Up @@ -135,15 +135,16 @@ private void UpdatePreReleaseTag(EffectiveBranchConfiguration configuration, Sem

if (lastTag != null && MajorMinorPatchEqual(lastTag, semanticVersion) && lastTag.HasPreReleaseTagWithLabel)
{
number = lastTag.PreReleaseTag!.Number + 1;
number = lastTag.PreReleaseTag?.Number + 1;
}

number ??= 1;

semanticVersion.PreReleaseTag = new SemanticVersionPreReleaseTag(tagToUse, number);
}

private static bool MajorMinorPatchEqual(SemanticVersion lastTag, SemanticVersion baseVersion) => lastTag.Major == baseVersion.Major && lastTag.Minor == baseVersion.Minor && lastTag.Patch == baseVersion.Patch;
private static bool MajorMinorPatchEqual(SemanticVersion lastTag, SemanticVersion baseVersion) =>
lastTag.Major == baseVersion.Major && lastTag.Minor == baseVersion.Minor && lastTag.Patch == baseVersion.Patch;

private NextVersion Calculate(IBranch branch, GitVersionConfiguration configuration)
{
Expand All @@ -152,6 +153,8 @@ private NextVersion Calculate(IBranch branch, GitVersionConfiguration configurat
var nextVersions = GetNextVersions(branch, configuration).ToArray();
var maxVersion = nextVersions.Max();

maxVersion.NotNull();

var matchingVersionsOnceIncremented = nextVersions
.Where(v => v.BaseVersion.BaseVersionSource != null && v.IncrementedVersion == maxVersion.IncrementedVersion)
.ToList();
Expand Down Expand Up @@ -192,13 +195,14 @@ static NextVersion CompareVersions(
filteredVersions = filteredVersions.Where(v => !v.BaseVersion.SemanticVersion.HasPreReleaseTagWithLabel);
}

var version = filteredVersions
var versions = filteredVersions as NextVersion[] ?? filteredVersions.ToArray();
var version = versions
.Where(v => v.BaseVersion.BaseVersionSource != null)
.OrderByDescending(v => v.IncrementedVersion)
.ThenByDescending(v => v.BaseVersion.BaseVersionSource!.When)
.ThenByDescending(v => v.BaseVersion.BaseVersionSource?.When)
.FirstOrDefault();

version ??= filteredVersions.Where(v => v.BaseVersion.BaseVersionSource == null)
version ??= versions.Where(v => v.BaseVersion.BaseVersionSource == null)
.OrderByDescending(v => v.IncrementedVersion)
.First();
latestBaseVersionSource = version.BaseVersion.BaseVersionSource;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ private static bool TryParseLoose(string version, [NotNullWhen(true)] out Semant
return true;
}

public int CompareTo(SemanticVersion value) => CompareTo(value, true);
public int CompareTo(SemanticVersion? value) => CompareTo(value, true);

public int CompareTo(SemanticVersion? value, bool includePrerelease)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public SemanticVersionBuildMetaData(SemanticVersionBuildMetaData? buildMetaData)
this.UncommittedChanges = buildMetaData?.UncommittedChanges ?? 0;
}

public override bool Equals(object obj) => Equals(obj as SemanticVersionBuildMetaData);
public override bool Equals(object? obj) => Equals(obj as SemanticVersionBuildMetaData);

public bool Equals(SemanticVersionBuildMetaData? other) => EqualityHelper.Equals(this, other);

Expand Down
9 changes: 4 additions & 5 deletions src/GitVersion.Core/VersionConverters/TemplateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ internal class TemplateManager

public TemplateManager(TemplateType templateType)
{
this.templates = GetEmbeddedTemplates(templateType, "Templates").ToDictionary(Path.GetExtension, v => v, StringComparer.OrdinalIgnoreCase);
this.addFormats = GetEmbeddedTemplates(templateType, "AddFormats").ToDictionary(Path.GetExtension, v => v, StringComparer.OrdinalIgnoreCase);
this.templates = GetEmbeddedTemplates(templateType, "Templates").ToDictionary(file => Path.GetExtension(file)!, v => v, StringComparer.OrdinalIgnoreCase);
this.addFormats = GetEmbeddedTemplates(templateType, "AddFormats").ToDictionary(file => Path.GetExtension(file)!, v => v, StringComparer.OrdinalIgnoreCase);
}

public string? GetTemplateFor(string fileExtension)
Expand All @@ -28,7 +28,7 @@ public TemplateManager(TemplateType templateType)

string? result = null;

if (this.templates.TryGetValue(fileExtension, out var template) && template != null)
if (this.templates.TryGetValue(fileExtension, out var template))
{
result = template.ReadAsStringFromEmbeddedResource<TemplateManager>();
}
Expand All @@ -45,7 +45,7 @@ public TemplateManager(TemplateType templateType)

string? result = null;

if (this.addFormats.TryGetValue(fileExtension, out var addFormat) && addFormat != null)
if (this.addFormats.TryGetValue(fileExtension, out var addFormat))
{
result = addFormat.ReadAsStringFromEmbeddedResource<TemplateManager>().TrimEnd('\r', '\n');
}
Expand All @@ -65,7 +65,6 @@ public bool IsSupported(string fileExtension)

private static IEnumerable<string> GetEmbeddedTemplates(TemplateType templateType, string templateCategory)
{

var assembly = typeof(TemplateManager).Assembly;

foreach (var name in assembly.GetManifestResourceNames())
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.LibGit2Sharp/Git/Branch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ internal Branch(LibGit2Sharp.Branch branch)
public ReferenceName Name { get; }
public ICommit? Tip { get; }
public ICommitCollection? Commits { get; }
public int CompareTo(IBranch other) => comparerHelper.Compare(this, other);
public int CompareTo(IBranch? other) => comparerHelper.Compare(this, other);
public bool Equals(IBranch? other) => equalityHelper.Equals(this, other);
public bool IsDetachedHead => Name.Canonical.Equals("(no branch)", StringComparison.OrdinalIgnoreCase);
public bool IsRemote => this.innerBranch.IsRemote;
public bool IsTracking => this.innerBranch.IsTracking;
public override bool Equals(object obj) => Equals((obj as IBranch));
public override bool Equals(object? obj) => Equals((obj as IBranch));
public override int GetHashCode() => equalityHelper.GetHashCode(this);
public override string ToString() => Name.ToString();
public static implicit operator LibGit2Sharp.Branch(Branch d) => d.innerBranch;
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.LibGit2Sharp/Git/Commit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ internal Commit(LibGit2Sharp.Commit innerCommit) : base(innerCommit)
When = innerCommit.Committer.When;
}

public int CompareTo(ICommit other) => comparerHelper.Compare(this, other);
public int CompareTo(ICommit? other) => comparerHelper.Compare(this, other);
public bool Equals(ICommit? other) => equalityHelper.Equals(this, other);
public IEnumerable<ICommit> Parents { get; }
public DateTimeOffset When { get; }
public string Message => this.innerCommit.Message;
public override bool Equals(object obj) => Equals((obj as ICommit));
public override bool Equals(object? obj) => Equals((obj as ICommit));
public override int GetHashCode() => equalityHelper.GetHashCode(this);
public override string ToString() => $"{Id.ToString(7)} {this.innerCommit.MessageShort}";
public static implicit operator LibGit2Sharp.Commit(Commit d) => d.innerCommit;
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.LibGit2Sharp/Git/GitObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ internal GitObject(LibGit2Sharp.GitObject innerGitObject)
Sha = innerGitObject.Sha;
}

public int CompareTo(IGitObject other) => comparerHelper.Compare(this, other);
public int CompareTo(IGitObject? other) => comparerHelper.Compare(this, other);
public bool Equals(IGitObject? other) => equalityHelper.Equals(this, other);
public override bool Equals(object obj) => Equals((obj as IGitObject));
public override bool Equals(object? obj) => Equals((obj as IGitObject));
public override int GetHashCode() => equalityHelper.GetHashCode(this);
public override string ToString() => Id.ToString(7);

Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.LibGit2Sharp/Git/ObjectId.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ public ObjectId(string sha) : this(new LibGit2Sharp.ObjectId(sha))
{
}

public int CompareTo(IObjectId other) => comparerHelper.Compare(this, other);
public int CompareTo(IObjectId? other) => comparerHelper.Compare(this, other);
public bool Equals(IObjectId? other) => equalityHelper.Equals(this, other);
public override bool Equals(object obj) => Equals((obj as IObjectId));
public override bool Equals(object? obj) => Equals((obj as IObjectId));
public override int GetHashCode() => equalityHelper.GetHashCode(this);
public override string ToString() => ToString(7);
public static implicit operator LibGit2Sharp.ObjectId(ObjectId d) => d.innerObjectId;
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.LibGit2Sharp/Git/RefSpec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ public class RefSpec : IRefSpec
private readonly LibGit2Sharp.RefSpec innerRefSpec;

internal RefSpec(LibGit2Sharp.RefSpec refSpec) => this.innerRefSpec = refSpec.NotNull();
public int CompareTo(IRefSpec other) => comparerHelper.Compare(this, other);
public int CompareTo(IRefSpec? other) => comparerHelper.Compare(this, other);
public bool Equals(IRefSpec? other) => equalityHelper.Equals(this, other);
public string Specification => this.innerRefSpec.Specification;
public RefSpecDirection Direction => (RefSpecDirection)this.innerRefSpec.Direction;
public string Source => this.innerRefSpec.Source;
public string Destination => this.innerRefSpec.Destination;
public override bool Equals(object obj) => Equals((obj as IRefSpec));
public override bool Equals(object? obj) => Equals((obj as IRefSpec));
public override int GetHashCode() => equalityHelper.GetHashCode(this);
public override string ToString() => Specification;
}
Loading

0 comments on commit 6de89f0

Please sign in to comment.