Skip to content

Commit

Permalink
improved logging information when finding for the version
Browse files Browse the repository at this point in the history
  • Loading branch information
arturcic committed Oct 6, 2023
1 parent ea00a28 commit e0f1db2
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 99 deletions.
8 changes: 4 additions & 4 deletions src/GitVersion.Core/Core/MergeBaseFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ public MergeBaseFinder(IRepositoryStore repositoryStore, IGitRepository gitRepos

if (findMergeBase == null)
{
this.log.Info($"No merge base of {first}' and '{second} could be found.");
this.log.Info($"No merge base of '{first}' and '{second}' could be found.");
return null;
}

// Store in cache.
this.mergeBaseCache.Add(key, findMergeBase);

this.log.Info($"Merge base of {first}' and '{second} is {findMergeBase}");
this.log.Info($"Merge base of '{first}' and '{second}' is '{findMergeBase}'");
return findMergeBase;
}
}
Expand All @@ -70,7 +70,7 @@ public MergeBaseFinder(IRepositoryStore repositoryStore, IGitRepository gitRepos
if (findMergeBase == null)
return null;

this.log.Info($"Found merge base of {findMergeBase}");
this.log.Info($"Found merge base of '{findMergeBase}'");

// We do not want to include merge base commits which got forward merged into the other branch
ICommit? forwardMerge;
Expand Down Expand Up @@ -103,7 +103,7 @@ public MergeBaseFinder(IRepositoryStore repositoryStore, IGitRepository gitRepos

findMergeBase = mergeBase;
commitToFindCommonBase = second;
this.log.Info($"Merge base was due to a forward merge, next merge base is {findMergeBase}");
this.log.Info($"next merge base --> {findMergeBase}");
} while (forwardMerge != null);

return findMergeBase;
Expand Down
8 changes: 3 additions & 5 deletions src/GitVersion.Core/Core/RepositoryStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -283,11 +283,9 @@ public IReadOnlyList<SemanticVersionWithTag> GetTaggedSemanticVersions(string? t
return this.taggedSemanticVersionsCache;
}

using (this.log.IndentLog($"Getting tagged semantic versions. TagPrefix: {tagPrefix} and Format: {format}"))
{
this.taggedSemanticVersionsCache = GetTaggedSemanticVersionsInternal().ToList();
return this.taggedSemanticVersionsCache;
}
this.log.Info($"Getting tagged semantic versions. TagPrefix: {tagPrefix} and Format: {format}");
this.taggedSemanticVersionsCache = GetTaggedSemanticVersionsInternal().ToList();
return this.taggedSemanticVersionsCache;

IEnumerable<SemanticVersionWithTag> GetTaggedSemanticVersionsInternal()
{
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.Core/Git/SemanticVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class SemanticVersion : IFormattable, IComparable<SemanticVersion>, IEqua
public bool IsLabeledWith(string value) => PreReleaseTag.HasTag() && PreReleaseTag.Name.IsEquivalentTo(value);

public bool IsMatchForBranchSpecificLabel(string? value)
=> PreReleaseTag.Name == string.Empty || value is null || IsLabeledWith(value);
=> PreReleaseTag.Name.Length == 0 || value is null || IsLabeledWith(value);

public SemanticVersion(long major = 0, long minor = 0, long patch = 0)
{
Expand Down Expand Up @@ -292,7 +292,7 @@ public string ToString(string? format, IFormatProvider? formatProvider)
case "s":
return this.PreReleaseTag.HasTag() ? $"{ToString("j")}-{this.PreReleaseTag}" : ToString("j");
case "t":
return this.PreReleaseTag.HasTag() ? $"{ToString("j")}-{this.PreReleaseTag.ToString("t")}" : ToString("j");
return this.PreReleaseTag.HasTag() ? $"{ToString("j")}-{this.PreReleaseTag:t}" : ToString("j");
case "f":
{
var buildMetadata = this.BuildMetaData.ToString();
Expand Down
1 change: 1 addition & 0 deletions src/GitVersion.Core/Logging/Abstractions/ILog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ public interface ILog
void Write(Verbosity verbosity, LogLevel level, string format, params object[] args);
IDisposable IndentLog(string operationDescription);
void AddLogAppender(ILogAppender logAppender);
void Separator();
}
8 changes: 5 additions & 3 deletions src/GitVersion.Core/Logging/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,19 @@ public void Write(Verbosity verbosity, LogLevel level, string format, params obj
public IDisposable IndentLog(string operationDescription)
{
var start = DateTime.Now;
Write(Verbosity.Normal, LogLevel.Info, $"Begin: {operationDescription}");
Write(Verbosity.Normal, LogLevel.Info, $"-< Begin: {operationDescription} >-");
this.indent += " ";

return Disposable.Create(() =>
{
var length = this.indent.Length - 2;
this.indent = length > 0 ? this.indent[..length] : this.indent;
Write(Verbosity.Normal, LogLevel.Info, string.Format(CultureInfo.InvariantCulture, "End: {0} (Took: {1:N}ms)", operationDescription, DateTime.Now.Subtract(start).TotalMilliseconds));
this.indent = length > 0 ? this.indent[..length] : "";
Write(Verbosity.Normal, LogLevel.Info, string.Format(CultureInfo.InvariantCulture, "-< End: {0} (Took: {1:N}ms) >-", operationDescription, DateTime.Now.Subtract(start).TotalMilliseconds));
});
}

public void Separator() => Write(Verbosity.Normal, LogLevel.Info, "-------------------------------------------------------");

public void AddLogAppender(ILogAppender logAppender) => this.appenders = this.appenders.Concat(new[] { logAppender });

public override string ToString() => this.sb.ToString();
Expand Down
4 changes: 4 additions & 0 deletions src/GitVersion.Core/Logging/NullLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@ public void AddLogAppender(ILogAppender logAppender)
{
}

public void Separator()
{
}

public string? Indent { get; set; }
}
1 change: 1 addition & 0 deletions src/GitVersion.Core/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ GitVersion.Logging.IConsole.WriteLine(string? msg) -> void
GitVersion.Logging.ILog
GitVersion.Logging.ILog.AddLogAppender(GitVersion.Logging.ILogAppender! logAppender) -> void
GitVersion.Logging.ILog.IndentLog(string! operationDescription) -> System.IDisposable!
GitVersion.Logging.ILog.Separator() -> void
GitVersion.Logging.ILog.Verbosity.get -> GitVersion.Logging.Verbosity
GitVersion.Logging.ILog.Verbosity.set -> void
GitVersion.Logging.ILog.Write(GitVersion.Logging.Verbosity verbosity, GitVersion.Logging.LogLevel level, string! format, params object![]! args) -> void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,6 @@ public BaseVersion(BaseVersion baseVersion)
public override string ToString()
{
var externalSource = BaseVersionSource == null ? "External Source" : BaseVersionSource.Sha;
return $"{Source}: {SemanticVersion.ToString("f")} with commit count source {externalSource}";
return $"{Source}: {SemanticVersion:f} with commit source '{externalSource}'";
}
}
163 changes: 84 additions & 79 deletions src/GitVersion.Core/VersionCalculation/NextVersionCalculator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,129 +50,132 @@ public virtual NextVersion FindVersion()
this.log.Info($"Current commit is tagged with version {Context.CurrentCommitTaggedVersion}, version calculation is for meta data only.");
}

var nextVersion = Calculate(Context.CurrentBranch, Context.Configuration);
var nextVersion = CalculateNextVersion(Context.CurrentBranch, Context.Configuration);
var incrementedVersion = CalculateIncrementedVersion(nextVersion.Configuration.VersioningMode, nextVersion);
return new(incrementedVersion, nextVersion.BaseVersion, new(nextVersion.Branch, nextVersion.Configuration));
}

private SemanticVersion CalculateIncrementedVersion(VersioningMode versioningMode, NextVersion nextVersion) => versioningMode switch
{
VersioningMode.ContinuousDelivery => this.manualDeploymentVersionCalculator.Calculate(nextVersion),
VersioningMode.ContinuousDeployment => nextVersion.Configuration.IsMainline && nextVersion.Configuration.Label is null
VersioningMode.ContinuousDeployment => nextVersion.Configuration is { IsMainline: true, Label: null }
? this.continuousDeploymentVersionCalculator.Calculate(nextVersion)
: this.continuousDeliveryVersionCalculator.Calculate(nextVersion),
VersioningMode.Mainline => this.mainlineVersionCalculator.FindMainlineModeVersion(nextVersion),
_ => throw new InvalidEnumArgumentException(nameof(versioningMode), (int)versioningMode, typeof(VersioningMode)),
};

private NextVersion Calculate(IBranch branch, IGitVersionConfiguration configuration)
private NextVersion CalculateNextVersion(IBranch branch, IGitVersionConfiguration configuration)
{
using (log.IndentLog("Calculating the base versions"))
{
var nextVersions = GetNextVersions(branch, configuration).ToArray();
var maxVersion = nextVersions.Max()!;
var nextVersions = GetNextVersions(branch, configuration).ToArray();
log.Separator();
var maxVersion = nextVersions.Max()!;

var matchingVersionsOnceIncremented = nextVersions
.Where(v => v.BaseVersion.BaseVersionSource != null && v.IncrementedVersion == maxVersion.IncrementedVersion)
.ToList();
ICommit? latestBaseVersionSource;
var matchingVersionsOnceIncremented = nextVersions
.Where(v => v.BaseVersion.BaseVersionSource != null && v.IncrementedVersion == maxVersion.IncrementedVersion)
.ToList();
ICommit? latestBaseVersionSource;

if (matchingVersionsOnceIncremented.Any())
if (matchingVersionsOnceIncremented.Any())
{
var latestVersion = matchingVersionsOnceIncremented.Aggregate(CompareVersions);
latestBaseVersionSource = latestVersion.BaseVersion.BaseVersionSource;
maxVersion = latestVersion;
log.Info(
$"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), " +
$"taking oldest source for commit counting ({latestVersion.BaseVersion.Source})");
}
else
{
IEnumerable<NextVersion> filteredVersions = nextVersions;
if (!maxVersion.IncrementedVersion.PreReleaseTag.HasTag())
{
static NextVersion CompareVersions(
NextVersion versions1,
NextVersion version2)
{
if (versions1.BaseVersion.BaseVersionSource == null)
{
return version2;
}
if (version2.BaseVersion.BaseVersionSource == null)
{
return versions1;
}
// If the maximal version has no pre-release tag defined than we want to determine just the latest previous
// base source which are not coming from pre-release tag.
filteredVersions = filteredVersions.Where(v => !v.BaseVersion.SemanticVersion.PreReleaseTag.HasTag());
}

return versions1.BaseVersion.BaseVersionSource.When
< version2.BaseVersion.BaseVersionSource.When ? versions1 : version2;
}
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)
.FirstOrDefault();

version ??= versions.Where(v => v.BaseVersion.BaseVersionSource == null)
.OrderByDescending(v => v.IncrementedVersion)
.First();
latestBaseVersionSource = version.BaseVersion.BaseVersionSource;
}

var latestVersion = matchingVersionsOnceIncremented.Aggregate(CompareVersions);
latestBaseVersionSource = latestVersion.BaseVersion.BaseVersionSource;
maxVersion = latestVersion;
log.Info($"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion})," +
$" taking oldest source for commit counting ({latestVersion.BaseVersion.Source})");
}
else
{
IEnumerable<NextVersion> filteredVersions = nextVersions;
if (!maxVersion.IncrementedVersion.PreReleaseTag.HasTag())
{
// If the maximal version has no pre-release tag defined than we want to determine just the latest previous
// base source which are not coming from pre-release tag.
filteredVersions = filteredVersions.Where(v => !v.BaseVersion.SemanticVersion.PreReleaseTag.HasTag());
}
var calculatedBase = new BaseVersion(
maxVersion.BaseVersion.Source,
maxVersion.BaseVersion.ShouldIncrement,
maxVersion.BaseVersion.SemanticVersion,
latestBaseVersionSource,
maxVersion.BaseVersion.BranchNameOverride
);

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)
.FirstOrDefault();

version ??= versions.Where(v => v.BaseVersion.BaseVersionSource == null)
.OrderByDescending(v => v.IncrementedVersion)
.First();
latestBaseVersionSource = version.BaseVersion.BaseVersionSource;
}
log.Info($"Base version used: {calculatedBase}");
log.Separator();
return new NextVersion(maxVersion.IncrementedVersion, calculatedBase, maxVersion.Branch, maxVersion.Configuration);
}

var calculatedBase = new BaseVersion(
maxVersion.BaseVersion.Source,
maxVersion.BaseVersion.ShouldIncrement,
maxVersion.BaseVersion.SemanticVersion,
latestBaseVersionSource,
maxVersion.BaseVersion.BranchNameOverride
);
private static NextVersion CompareVersions(NextVersion versions1, NextVersion version2)
{
if (versions1.BaseVersion.BaseVersionSource == null)
return version2;

log.Info($"Base version used: {calculatedBase}");
if (version2.BaseVersion.BaseVersionSource == null)
return versions1;

return new NextVersion(maxVersion.IncrementedVersion, calculatedBase, maxVersion.Branch, maxVersion.Configuration);
}
return versions1.BaseVersion.BaseVersionSource.When < version2.BaseVersion.BaseVersionSource.When
? versions1
: version2;
}

private IReadOnlyCollection<NextVersion> GetNextVersions(IBranch branch, IGitVersionConfiguration configuration)
{
if (branch.Tip == null)
throw new GitVersionException("No commits found on the current branch.");
using (log.IndentLog("Fetching the base versions for version calculation..."))
{
if (branch.Tip == null)
throw new GitVersionException("No commits found on the current branch.");

var nextVersions = GetNextVersionsInternal().ToList();
if (nextVersions.Count == 0)
throw new GitVersionException("No base versions determined on the current branch.");
return nextVersions;
var nextVersions = GetNextVersionsInternal().ToList();
if (nextVersions.Count == 0)
throw new GitVersionException("No base versions determined on the current branch.");
return nextVersions;
}

IEnumerable<NextVersion> GetNextVersionsInternal()
{
foreach (var effectiveConfiguration in effectiveBranchConfigurationFinder.GetConfigurations(branch, configuration))
var effectiveBranchConfigurations = this.effectiveBranchConfigurationFinder.GetConfigurations(branch, configuration).ToArray();
foreach (var effectiveBranchConfiguration in effectiveBranchConfigurations)
{
this.log.Info($"Calculating base versions for '{effectiveBranchConfiguration.Branch.Name}'");
var atLeastOneBaseVersionReturned = false;
foreach (var versionStrategy in this.versionStrategies)
{
foreach (var baseVersion in versionStrategy.GetBaseVersions(effectiveConfiguration))
using (this.log.IndentLog($"[Using '{versionStrategy.GetType().Name}' strategy]"))
{
log.Info(baseVersion.ToString());

if (IncludeVersion(baseVersion, configuration.Ignore)
&& TryGetNextVersion(out var nextVersion, effectiveConfiguration, baseVersion))
foreach (var baseVersion in versionStrategy.GetBaseVersions(effectiveBranchConfiguration))
{
yield return nextVersion;
atLeastOneBaseVersionReturned = true;
log.Info(baseVersion.ToString());
if (IncludeVersion(baseVersion, configuration.Ignore)
&& TryGetNextVersion(out var nextVersion, effectiveBranchConfiguration, baseVersion))
{
yield return nextVersion;
atLeastOneBaseVersionReturned = true;
}
}
}
}

if (!atLeastOneBaseVersionReturned)
{
var baseVersion = new BaseVersion("Fallback base version", true, SemanticVersion.Empty, null, null);
if (TryGetNextVersion(out var nextVersion, effectiveConfiguration, baseVersion)) yield return nextVersion;
if (TryGetNextVersion(out var nextVersion, effectiveBranchConfiguration, baseVersion))
yield return nextVersion;
}
}
}
Expand All @@ -187,7 +190,9 @@ private bool TryGetNextVersion([NotNullWhen(true)] out NextVersion? result,
Context.CurrentBranch.Name, baseVersion.BranchNameOverride
);
if (effectiveConfiguration.Value.Label != label)
{
log.Info("Using current branch name to calculate version tag");
}

var incrementedVersion = GetIncrementedVersion(effectiveConfiguration, baseVersion, label);
if (incrementedVersion.IsMatchForBranchSpecificLabel(label))
Expand Down
6 changes: 3 additions & 3 deletions src/GitVersion.Core/VersionCalculation/ShaVersionFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ namespace GitVersion.VersionCalculation;

internal class ShaVersionFilter : IVersionFilter
{
private readonly IEnumerable<string> shas;
private readonly IEnumerable<string> shaList;

public ShaVersionFilter(IEnumerable<string> shas) => this.shas = shas.NotNull();
public ShaVersionFilter(IEnumerable<string> shaList) => this.shaList = shaList.NotNull();

public bool Exclude(BaseVersion? version, [NotNullWhen(true)] out string? reason)
{
version.NotNull();

reason = null;

if (version.BaseVersionSource == null || !this.shas.Any(sha => version.BaseVersionSource.Sha.StartsWith(sha, StringComparison.OrdinalIgnoreCase)))
if (version.BaseVersionSource == null || !this.shaList.Any(sha => version.BaseVersionSource.Sha.StartsWith(sha, StringComparison.OrdinalIgnoreCase)))
return false;

reason = $"Sha {version.BaseVersionSource} was ignored due to commit having been excluded by configuration";
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersion.LibGit2Sharp/Git/Commit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ internal Commit(LibGit2Sharp.Commit innerCommit) : base(innerCommit)
public string Message => this.innerCommit.Message;
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 override string ToString() => $"'{Id.ToString(7)}' - {this.innerCommit.MessageShort}";
public static implicit operator LibGit2Sharp.Commit(Commit d) => d.innerCommit;
}
Loading

0 comments on commit e0f1db2

Please sign in to comment.