Skip to content

Refactor GitVersion.Core for clear, maintainable methods #3804

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/GitVersion.App.Tests/Helpers/ExecutionResults.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ public virtual GitVersionVariables OutputVariables
{
get
{
var jsonStartIndex = Output.IndexOf("{", StringComparison.Ordinal);
var jsonEndIndex = Output.IndexOf("}", StringComparison.Ordinal);
var jsonStartIndex = Output.IndexOf('{');
var jsonEndIndex = Output.IndexOf('}');
var json = Output.Substring(jsonStartIndex, jsonEndIndex - jsonStartIndex + 1);

return VersionVariablesHelper.FromJson(json);
Expand Down
4 changes: 2 additions & 2 deletions src/GitVersion.Core.Tests/Core/GitVersionExecutorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class GitVersionExecutorTests : TestBase
{
private IFileSystem fileSystem;
private ILog log;
private IGitVersionCache gitVersionCache;
private GitVersionCache gitVersionCache;
private IServiceProvider sp;

[Test]
Expand Down Expand Up @@ -571,7 +571,7 @@ private IGitVersionCalculateTool GetGitVersionCalculator(GitVersionOptions gitVe

this.fileSystem = this.sp.GetRequiredService<IFileSystem>();
this.log = this.sp.GetRequiredService<ILog>();
this.gitVersionCache = this.sp.GetRequiredService<IGitVersionCache>();
this.gitVersionCache = (GitVersionCache)this.sp.GetRequiredService<IGitVersionCache>();

return this.sp.GetRequiredService<IGitVersionCalculateTool>();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public static void WriteVersionVariables(this RepositoryFixtureBase fixture, str

using var stream = File.Open(versionFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
using var writer = new StreamWriter(stream);
writer.Write(versionVariables.ToJsonString());
writer.Write(versionVariables.ToJson());
}

public static void AssertFullSemver(this RepositoryFixtureBase fixture, string fullSemver,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ public void Json()

var variableProvider = serviceProvider.GetRequiredService<IVariableProvider>();
var variables = variableProvider.GetVariablesFor(semanticVersion, configuration, null);
variables.ToJsonString().ShouldMatchApproved(c => c.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(c => c.SubFolder("Approved"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForPreRelease()
.GetEffectiveConfiguration(ReferenceName.FromBranchName("unstable"));
var variables = this.variableProvider.GetVariablesFor(semanticVersion, configuration, null);

variables.ToJsonString().ShouldMatchApproved(c => c.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(c => c.SubFolder("Approved"));
}

[Test]
Expand All @@ -77,7 +77,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForPreRelease()
.GetEffectiveConfiguration(ReferenceName.FromBranchName("unstable"));
var variables = this.variableProvider.GetVariablesFor(semanticVersion, configuration, null);

variables.ToJsonString().ShouldMatchApproved(c => c.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(c => c.SubFolder("Approved"));
}

[Test]
Expand All @@ -101,7 +101,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForStable()
.GetEffectiveConfiguration(ReferenceName.FromBranchName("develop"));
var variables = this.variableProvider.GetVariablesFor(semanticVersion, configuration, null);

variables.ToJsonString().ShouldMatchApproved(c => c.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(c => c.SubFolder("Approved"));
}

[Test]
Expand All @@ -127,7 +127,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForStable()
.GetEffectiveConfiguration(ReferenceName.FromBranchName("develop"));
var variables = this.variableProvider.GetVariablesFor(semanticVersion, configuration, null);

variables.ToJsonString().ShouldMatchApproved(c => c.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(c => c.SubFolder("Approved"));
}

[Test]
Expand All @@ -153,7 +153,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForStableWhenCurrentCommi
.GetEffectiveConfiguration(ReferenceName.FromBranchName("develop"));
var variables = this.variableProvider.GetVariablesFor(semanticVersion, configuration, SemanticVersion.Empty);

variables.ToJsonString().ShouldMatchApproved(c => c.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(c => c.SubFolder("Approved"));
}

[Test]
Expand Down Expand Up @@ -228,7 +228,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForFeatureBranch()
.GetEffectiveConfiguration(ReferenceName.FromBranchName("develop"));
var variables = this.variableProvider.GetVariablesFor(semanticVersion, configuration, null);

variables.ToJsonString().ShouldMatchApproved(c => c.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(c => c.SubFolder("Approved"));
}

[Test]
Expand All @@ -254,7 +254,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForFeatureBranchWithCustomA
.Build().GetEffectiveConfiguration(ReferenceName.FromBranchName("develop"));
var variables = this.variableProvider.GetVariablesFor(semanticVersion, configuration, null);

variables.ToJsonString().ShouldMatchApproved(c => c.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(c => c.SubFolder("Approved"));
}

[Test]
Expand All @@ -281,6 +281,6 @@ public void ProvidesVariablesInContinuousDeploymentModeForMainBranchWithEmptyLab
.GetEffectiveConfiguration(ReferenceName.FromBranchName("main"));
var variables = this.variableProvider.GetVariablesFor(semanticVersion, configuration, null);

variables.ToJsonString().ShouldMatchApproved(_ => _.SubFolder("Approved"));
variables.ToJson().ShouldMatchApproved(_ => _.SubFolder("Approved"));
}
}
38 changes: 17 additions & 21 deletions src/GitVersion.Core/OutputVariables/VersionVariablesHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,22 @@ public static GitVersionVariables FromJson(string json)
return FromDictionary(variablePairs);
}

public static string ToJson(this GitVersionVariables gitVersionVariables)
{
var variablesType = typeof(VersionVariablesJsonModel);
var variables = new VersionVariablesJsonModel();

foreach (var (key, value) in gitVersionVariables.OrderBy(x => x.Key))
{
var propertyInfo = variablesType.GetProperty(key);
propertyInfo?.SetValue(variables, ChangeType(value, propertyInfo.PropertyType));
}

var serializeOptions = JsonSerializerOptions();

return JsonSerializer.Serialize(variables, serializeOptions);
}

public static GitVersionVariables FromFile(string filePath, IFileSystem fileSystem)
{
try
Expand All @@ -33,22 +49,6 @@ public static GitVersionVariables FromFile(string filePath, IFileSystem fileSyst
}
}

public static string ToJsonString(this GitVersionVariables gitVersionVariables)
{
var variablesType = typeof(VersionVariablesJsonModel);
var variables = new VersionVariablesJsonModel();

foreach (var (key, value) in gitVersionVariables.OrderBy(x => x.Key))
{
var propertyInfo = variablesType.GetProperty(key);
propertyInfo?.SetValue(variables, ChangeType(value, propertyInfo.PropertyType));
}

var serializeOptions = JsonSerializerOptions();

return JsonSerializer.Serialize(variables, serializeOptions);
}

private static GitVersionVariables FromDictionary(IEnumerable<KeyValuePair<string, string>>? properties)
{
var type = typeof(GitVersionVariables);
Expand All @@ -72,11 +72,7 @@ private static GitVersionVariables FromFileInternal(string filePath, IFileSystem
return versionVariables;
}

private static JsonSerializerOptions JsonSerializerOptions()
{
var serializeOptions = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, Converters = { new VersionVariablesJsonStringConverter() } };
return serializeOptions;
}
private static JsonSerializerOptions JsonSerializerOptions() => new() { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, Converters = { new VersionVariablesJsonStringConverter() } };

private static object? ChangeType(object? value, Type type)
{
Expand Down
14 changes: 5 additions & 9 deletions src/GitVersion.Core/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -688,19 +688,15 @@ GitVersion.VersionCalculation.BaseVersion.ShouldIncrement.init -> void
GitVersion.VersionCalculation.BaseVersion.Source.get -> string!
GitVersion.VersionCalculation.BaseVersion.Source.init -> void
GitVersion.VersionCalculation.Caching.GitVersionCache
GitVersion.VersionCalculation.Caching.GitVersionCache.GetCacheDirectory() -> string!
GitVersion.VersionCalculation.Caching.GitVersionCache.GetCacheFileName(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! cacheKey) -> string!
GitVersion.VersionCalculation.Caching.GitVersionCache.GitVersionCache(GitVersion.IFileSystem! fileSystem, GitVersion.Logging.ILog! log, GitVersion.IGitRepositoryInfo! repositoryInfo) -> void
GitVersion.VersionCalculation.Caching.GitVersionCache.LoadVersionVariablesFromDiskCache(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! key) -> GitVersion.OutputVariables.GitVersionVariables?
GitVersion.VersionCalculation.Caching.GitVersionCache.WriteVariablesToDiskCache(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! cacheKey, GitVersion.OutputVariables.GitVersionVariables! variablesFromCache) -> void
GitVersion.VersionCalculation.Caching.GitVersionCache.LoadVersionVariablesFromDiskCache(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! cacheKey) -> GitVersion.OutputVariables.GitVersionVariables?
GitVersion.VersionCalculation.Caching.GitVersionCache.WriteVariablesToDiskCache(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! cacheKey, GitVersion.OutputVariables.GitVersionVariables! versionVariables) -> void
GitVersion.VersionCalculation.Caching.GitVersionCacheKey
GitVersion.VersionCalculation.Caching.GitVersionCacheKey.GitVersionCacheKey(string! value) -> void
GitVersion.VersionCalculation.Caching.GitVersionCacheKey.Value.get -> string!
GitVersion.VersionCalculation.Caching.IGitVersionCache
GitVersion.VersionCalculation.Caching.IGitVersionCache.GetCacheDirectory() -> string!
GitVersion.VersionCalculation.Caching.IGitVersionCache.GetCacheFileName(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! cacheKey) -> string!
GitVersion.VersionCalculation.Caching.IGitVersionCache.LoadVersionVariablesFromDiskCache(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! key) -> GitVersion.OutputVariables.GitVersionVariables?
GitVersion.VersionCalculation.Caching.IGitVersionCache.WriteVariablesToDiskCache(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! cacheKey, GitVersion.OutputVariables.GitVersionVariables! variablesFromCache) -> void
GitVersion.VersionCalculation.Caching.IGitVersionCache.LoadVersionVariablesFromDiskCache(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! cacheKey) -> GitVersion.OutputVariables.GitVersionVariables?
GitVersion.VersionCalculation.Caching.IGitVersionCache.WriteVariablesToDiskCache(GitVersion.VersionCalculation.Caching.GitVersionCacheKey! cacheKey, GitVersion.OutputVariables.GitVersionVariables! versionVariables) -> void
GitVersion.VersionCalculation.CommitMessageIncrementMode
GitVersion.VersionCalculation.CommitMessageIncrementMode.Disabled = 1 -> GitVersion.VersionCalculation.CommitMessageIncrementMode
GitVersion.VersionCalculation.CommitMessageIncrementMode.Enabled = 0 -> GitVersion.VersionCalculation.CommitMessageIncrementMode
Expand Down Expand Up @@ -869,7 +865,7 @@ static GitVersion.Logging.LogExtensions.Warning(this GitVersion.Logging.ILog! lo
static GitVersion.Logging.LogExtensions.Write(this GitVersion.Logging.ILog! log, GitVersion.Logging.LogLevel level, string! format, params object![]! args) -> void
static GitVersion.OutputVariables.VersionVariablesHelper.FromFile(string! filePath, GitVersion.IFileSystem! fileSystem) -> GitVersion.OutputVariables.GitVersionVariables!
static GitVersion.OutputVariables.VersionVariablesHelper.FromJson(string! json) -> GitVersion.OutputVariables.GitVersionVariables!
static GitVersion.OutputVariables.VersionVariablesHelper.ToJsonString(this GitVersion.OutputVariables.GitVersionVariables! gitVersionVariables) -> string!
static GitVersion.OutputVariables.VersionVariablesHelper.ToJson(this GitVersion.OutputVariables.GitVersionVariables! gitVersionVariables) -> string!
static GitVersion.ReferenceName.FromBranchName(string! branchName) -> GitVersion.ReferenceName!
static GitVersion.ReferenceName.Parse(string! canonicalName) -> GitVersion.ReferenceName!
static GitVersion.ReferenceName.TryParse(out GitVersion.ReferenceName? value, string! canonicalName) -> bool
Expand Down
35 changes: 16 additions & 19 deletions src/GitVersion.Core/VersionCalculation/Caching/GitVersionCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ public GitVersionCache(IFileSystem fileSystem, ILog log, IGitRepositoryInfo repo
this.repositoryInfo = repositoryInfo.NotNull();
}

public void WriteVariablesToDiskCache(GitVersionCacheKey cacheKey, GitVersionVariables variablesFromCache)
public void WriteVariablesToDiskCache(GitVersionCacheKey cacheKey, GitVersionVariables versionVariables)
{
var cacheFileName = GetCacheFileName(cacheKey);

Dictionary<string, string?> dictionary;
using (this.log.IndentLog("Creating dictionary"))
{
dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value);
dictionary = versionVariables.ToDictionary(x => x.Key, x => x.Value);
}

void WriteCacheOperation()
Expand All @@ -44,26 +44,11 @@ void WriteCacheOperation()
retryOperation.Execute(WriteCacheOperation);
}

public string GetCacheFileName(GitVersionCacheKey cacheKey)
{
var cacheDir = PrepareCacheDirectory();
var cacheFileName = GetCacheFileName(cacheKey, cacheDir);
return cacheFileName;
}

public string GetCacheDirectory()
{
var gitDir = this.repositoryInfo.DotGitDirectory;
return PathHelper.Combine(gitDir, "gitversion_cache");
}

public GitVersionVariables? LoadVersionVariablesFromDiskCache(GitVersionCacheKey key)
public GitVersionVariables? LoadVersionVariablesFromDiskCache(GitVersionCacheKey cacheKey)
{
using (this.log.IndentLog("Loading version variables from disk cache"))
{
var cacheDir = PrepareCacheDirectory();

var cacheFileName = GetCacheFileName(key, cacheDir);
var cacheFileName = GetCacheFileName(cacheKey);
if (!this.fileSystem.Exists(cacheFileName))
{
this.log.Info("Cache file " + cacheFileName + " not found.");
Expand Down Expand Up @@ -96,6 +81,18 @@ public string GetCacheDirectory()
}
}

internal string GetCacheFileName(GitVersionCacheKey cacheKey)
{
var cacheDir = PrepareCacheDirectory();
return GetCacheFileName(cacheKey, cacheDir);
}

internal string GetCacheDirectory()
{
var gitDir = this.repositoryInfo.DotGitDirectory;
return PathHelper.Combine(gitDir, "gitversion_cache");
}

private string PrepareCacheDirectory()
{
var cacheDir = GetCacheDirectory();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ namespace GitVersion.VersionCalculation.Caching;

public interface IGitVersionCache
{
void WriteVariablesToDiskCache(GitVersionCacheKey cacheKey, GitVersionVariables variablesFromCache);
string GetCacheDirectory();
GitVersionVariables? LoadVersionVariablesFromDiskCache(GitVersionCacheKey key);
string GetCacheFileName(GitVersionCacheKey cacheKey);
void WriteVariablesToDiskCache(GitVersionCacheKey cacheKey, GitVersionVariables versionVariables);
GitVersionVariables? LoadVersionVariablesFromDiskCache(GitVersionCacheKey cacheKey);
}
21 changes: 14 additions & 7 deletions src/GitVersion.MsBuild/GitVersionTaskExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public GitVersionTaskExecutor(IFileSystem fileSystem, IGitVersionOutputTool gitV

public void GetVersion(GetVersion task)
{
var versionVariables = VersionVariablesHelper.FromFile(task.VersionFile, fileSystem);
var versionVariables = GitVersionVariables(task);
var outputType = typeof(GetVersion);
foreach (var (key, value) in versionVariables)
{
Expand All @@ -35,7 +35,7 @@ public void GetVersion(GetVersion task)

public void UpdateAssemblyInfo(UpdateAssemblyInfo task)
{
var versionVariables = VersionVariablesHelper.FromFile(task.VersionFile, fileSystem);
var versionVariables = GitVersionVariables(task);
FileHelper.DeleteTempFiles();
FileHelper.CheckForInvalidFiles(task.CompileFiles, task.ProjectFile);

Expand All @@ -59,7 +59,7 @@ public void UpdateAssemblyInfo(UpdateAssemblyInfo task)

public void GenerateGitVersionInformation(GenerateGitVersionInformation task)
{
var versionVariables = VersionVariablesHelper.FromFile(task.VersionFile, fileSystem);
var versionVariables = GitVersionVariables(task);

if (!string.IsNullOrEmpty(task.IntermediateOutputPath))
{
Expand All @@ -72,13 +72,14 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task)

var gitVersionOptions = this.options.Value;
gitVersionOptions.WorkingDirectory = fileWriteInfo.WorkingDirectory;
var targetNamespace = getTargetNamespace(task);
var targetNamespace = GetTargetNamespace(task);
gitVersionOutputTool.GenerateGitVersionInformation(versionVariables, fileWriteInfo, targetNamespace);
return;

static string? getTargetNamespace(GenerateGitVersionInformation task)
static string? GetTargetNamespace(GenerateGitVersionInformation task)
{
string? targetNamespace = null;
if (string.Equals(task.UseProjectNamespaceForGitVersionInformation, "true", StringComparison.OrdinalIgnoreCase))
if (bool.TryParse(task.UseProjectNamespaceForGitVersionInformation, out var useTargetPathAsRootNamespace) && useTargetPathAsRootNamespace)
{
targetNamespace = task.RootNamespace;
if (string.IsNullOrWhiteSpace(targetNamespace))
Expand All @@ -93,11 +94,17 @@ public void GenerateGitVersionInformation(GenerateGitVersionInformation task)

public void WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task)
{
var versionVariables = VersionVariablesHelper.FromFile(task.VersionFile, fileSystem);
var versionVariables = GitVersionVariables(task);

var gitVersionOptions = this.options.Value;
var configuration = this.configurationProvider.Provide(gitVersionOptions.ConfigurationInfo.OverrideConfiguration);

gitVersionOutputTool.OutputVariables(versionVariables, configuration.UpdateBuildNumber);
}

private GitVersionVariables GitVersionVariables(GitVersionTaskBase task)
{
var versionVariables = VersionVariablesHelper.FromFile(task.VersionFile, this.fileSystem);
return versionVariables;
}
}
4 changes: 2 additions & 2 deletions src/GitVersion.Output/OutputGenerator/OutputGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ public void Execute(GitVersionVariables variables, OutputContext context)
if (gitVersionOptions.Output.Contains(OutputType.File))
{
var retryOperation = new RetryAction<IOException>();
retryOperation.Execute(() => this.fileSystem.WriteAllText(context.OutputFile, variables.ToJsonString()));
retryOperation.Execute(() => this.fileSystem.WriteAllText(context.OutputFile, variables.ToJson()));
}

if (!gitVersionOptions.Output.Contains(OutputType.Json)) return;

if (gitVersionOptions.ShowVariable is null && gitVersionOptions.Format is null)
{
this.console.WriteLine(variables.ToJsonString());
this.console.WriteLine(variables.ToJson());
return;
}

Expand Down
Loading