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 bdcfd1b commit 2f9f503
Show file tree
Hide file tree
Showing 26 changed files with 86 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ public void ConfigNextVersionTest(string nextVersion, string expectedVersion)
var branchMock = GitToolsTestingExtensions.CreateMockBranch("main", GitToolsTestingExtensions.CreateMockCommit());
var branchConfiguration = context.Configuration.GetBranchConfiguration(branchMock);
var effectiveConfiguration = new EffectiveConfiguration(context.Configuration, branchConfiguration);

strategy.ShouldNotBeNull();
return strategy.GetBaseVersions(new(branchMock, effectiveConfiguration)).SingleOrDefault();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ public void ShouldNotAllowIncrementOfVersion()
var context = contextBuilder.ServicesProvider.GetRequiredService<Lazy<GitVersionContext>>().Value;
var branchConfiguration = context.Configuration.GetBranchConfiguration(mockBranch);
var effectiveConfiguration = new EffectiveConfiguration(context.Configuration, branchConfiguration);

strategy.ShouldNotBeNull();
var baseVersion = strategy.GetBaseVersions(new(mockBranch, effectiveConfiguration)).Single();

baseVersion.ShouldIncrement.ShouldBe(false);
Expand Down Expand Up @@ -173,6 +175,8 @@ private static void AssertMergeMessage(string message, string? expectedVersion,
var context = contextBuilder.ServicesProvider.GetRequiredService<Lazy<GitVersionContext>>().Value;
var branchConfiguration = context.Configuration.GetBranchConfiguration(mockBranch);
var effectiveConfiguration = new EffectiveConfiguration(context.Configuration, branchConfiguration);

strategy.ShouldNotBeNull();
var baseVersion = strategy.GetBaseVersions(new(mockBranch, effectiveConfiguration)).SingleOrDefault();

if (expectedVersion == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public void CanTakeVersionFromNameOfReleaseBranch(string branchName, string expe
var configuration = GitFlowConfigurationBuilder.New.Build();
var branchConfiguration = configuration.GetBranchConfiguration(branchName);
var effectiveConfiguration = new EffectiveConfiguration(configuration, branchConfiguration);

strategy.ShouldNotBeNull();
var baseVersion = strategy.GetBaseVersions(new(gitRepository.FindBranch(branchName)!, effectiveConfiguration)).Single();

baseVersion.SemanticVersion.ToString().ShouldBe(expectedBaseVersion);
Expand All @@ -45,6 +47,8 @@ public void ShouldNotTakeVersionFromNameOfNonReleaseBranch(string branchName)
var configuration = GitFlowConfigurationBuilder.New.Build();
var branchConfiguration = configuration.GetBranchConfiguration(branchName);
var effectiveConfiguration = new EffectiveConfiguration(configuration, branchConfiguration);

strategy.ShouldNotBeNull();
var baseVersions = strategy.GetBaseVersions(new(gitRepository.FindBranch(branchName)!, effectiveConfiguration));

baseVersions.ShouldBeEmpty();
Expand All @@ -67,6 +71,9 @@ public void CanTakeVersionFromNameOfConfiguredReleaseBranch(string branchName, s
var configuration = GitFlowConfigurationBuilder.New.Build();
var branchConfiguration = configuration.GetBranchConfiguration(branchName);
var effectiveConfiguration = new EffectiveConfiguration(configuration, branchConfiguration);

strategy.ShouldNotBeNull();

var baseVersion = strategy.GetBaseVersions(new(gitRepository.FindBranch(branchName)!, effectiveConfiguration)).Single();

baseVersion.SemanticVersion.ToString().ShouldBe(expectedBaseVersion);
Expand All @@ -90,12 +97,15 @@ public void CanTakeVersionFromNameOfRemoteReleaseBranch(string branchName, strin
var configuration = GitFlowConfigurationBuilder.New.Build();
var branchConfiguration = configuration.GetBranchConfiguration(branchName);
var effectiveConfiguration = new EffectiveConfiguration(configuration, branchConfiguration);

strategy.ShouldNotBeNull();

var baseVersion = strategy.GetBaseVersions(new(gitRepository.FindBranch(branchName)!, effectiveConfiguration)).Single();

baseVersion.SemanticVersion.ToString().ShouldBe(expectedBaseVersion);
}

private static IVersionStrategy GetVersionStrategy(string workingDirectory, IGitRepository repository, string branch, GitVersionConfiguration? configuration = null)
private static IVersionStrategy? GetVersionStrategy(string workingDirectory, IGitRepository repository, string branch, GitVersionConfiguration? configuration = null)
{
var sp = BuildServiceProvider(workingDirectory, repository, branch, configuration);
return sp.GetServiceForType<IVersionStrategy, VersionInBranchNameVersionStrategy>();
Expand Down
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
8 changes: 4 additions & 4 deletions 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 All @@ -24,10 +24,10 @@ public IEnumerable<BranchCommit> FindMergeCommitsFor(IBranch branch)
{
branch = branch.NotNull();

if (this.mergeBaseCommitsCache.ContainsKey(branch))
if (this.mergeBaseCommitsCache.TryGetValue(branch, out var mergeCommitsFor))
{
this.log.Debug($"Cache hit for getting merge commits for branch {branch?.Name.Canonical}.");
return this.mergeBaseCommitsCache[branch];
this.log.Debug($"Cache hit for getting merge commits for branch {branch.Name.Canonical}.");
return mergeCommitsFor;
}

var branchMergeBases = FindMergeBases(branch)
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;
}
}
3 changes: 2 additions & 1 deletion src/GitVersion.Core/Extensions/DictionaryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict,
{
if (dict is null) throw new ArgumentNullException(nameof(dict));
if (getValue is null) throw new ArgumentNullException(nameof(getValue));
if (!dict.TryGetValue(key, out TValue value))

if (!dict.TryGetValue(key, out var value))
{
value = getValue();
dict.Add(key, value);
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.Core/Extensions/ObjectExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ public static void Deconstruct<TKey, TValue>(
value = kvp.Value;
}

public static IEnumerable<KeyValuePair<string, string>> GetProperties(this object obj)
public static Dictionary<string, string> GetProperties(this object obj)
{
var type = typeof(string);
return obj.GetType().GetProperties()
.Where(p => p.PropertyType == type && !p.GetIndexParameters().Any() && !p.GetCustomAttributes(typeof(ReflectionIgnoreAttribute), false).Any())
.Select(p => new KeyValuePair<string, string>(p.Name, (string)p.GetValue(obj, null)));
.ToDictionary(p => p.Name, p => Convert.ToString(p.GetValue(obj, null))!);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ public static IServiceCollection AddModule(this IServiceCollection serviceCollec
}

public static TService GetServiceForType<TService, TType>(this IServiceProvider serviceProvider) =>
serviceProvider.GetServices<TService>().SingleOrDefault(t => t?.GetType() == typeof(TType));
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
Loading

0 comments on commit 2f9f503

Please sign in to comment.