Skip to content

Commit

Permalink
added unique namespace generation (see issue GitTools#3606)
Browse files Browse the repository at this point in the history
  • Loading branch information
apmoskevitz committed Jul 5, 2023
1 parent 9998780 commit fb8a162
Show file tree
Hide file tree
Showing 16 changed files with 207 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ public interface IGitVersionOutputTool
void UpdateAssemblyInfo(VersionVariables variables);
void UpdateWixVersionFile(VersionVariables variables);
void GenerateGitVersionInformation(VersionVariables variables, FileWriteInfo fileWriteInfo);
void GenerateGitVersionInformation(VersionVariables variables, FileWriteInfo fileWriteInfo, string? targetNamespace = null);

}
26 changes: 14 additions & 12 deletions src/GitVersion.Core/Core/GitVersionOutputTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public GitVersionOutputTool(IOptions<GitVersionOptions> options,
IGitVersionInfoGenerator gitVersionInfoGenerator, IAssemblyInfoFileUpdater assemblyInfoFileUpdater,
IProjectFileUpdater projectFileUpdater)
{
this.gitVersionOptions = options.Value.NotNull();
gitVersionOptions = options.Value.NotNull();

this.outputGenerator = outputGenerator.NotNull();

Expand All @@ -34,9 +34,9 @@ public GitVersionOutputTool(IOptions<GitVersionOptions> options,

public void OutputVariables(VersionVariables variables, bool updateBuildNumber)
{
using (this.outputGenerator)
using (outputGenerator)
{
this.outputGenerator.Execute(variables, new OutputContext(gitVersionOptions.WorkingDirectory, gitVersionOptions.OutputFile, updateBuildNumber));
outputGenerator.Execute(variables, new OutputContext(gitVersionOptions.WorkingDirectory, gitVersionOptions.OutputFile, updateBuildNumber));
}
}

Expand All @@ -46,16 +46,16 @@ public void UpdateAssemblyInfo(VersionVariables variables)

if (gitVersionOptions.AssemblyInfo.UpdateProjectFiles)
{
using (this.projectFileUpdater)
using (projectFileUpdater)
{
this.projectFileUpdater.Execute(variables, assemblyInfoContext);
projectFileUpdater.Execute(variables, assemblyInfoContext);
}
}
else if (gitVersionOptions.AssemblyInfo.UpdateAssemblyInfo)
{
using (this.assemblyInfoFileUpdater)
using (assemblyInfoFileUpdater)
{
this.assemblyInfoFileUpdater.Execute(variables, assemblyInfoContext);
assemblyInfoFileUpdater.Execute(variables, assemblyInfoContext);
}
}
}
Expand All @@ -64,18 +64,20 @@ public void UpdateWixVersionFile(VersionVariables variables)
{
if (gitVersionOptions.WixInfo.ShouldUpdate)
{
using (this.wixVersionFileUpdater)
using (wixVersionFileUpdater)
{
this.wixVersionFileUpdater.Execute(variables, new WixVersionContext(gitVersionOptions.WorkingDirectory));
wixVersionFileUpdater.Execute(variables, new WixVersionContext(gitVersionOptions.WorkingDirectory));
}
}
}

public void GenerateGitVersionInformation(VersionVariables variables, FileWriteInfo fileWriteInfo)
public void GenerateGitVersionInformation(VersionVariables variables, FileWriteInfo fileWriteInfo, string? targetNamespace = null)
{
using (this.gitVersionInfoGenerator)
using (gitVersionInfoGenerator)
{
this.gitVersionInfoGenerator.Execute(variables, new GitVersionInfoContext(gitVersionOptions.WorkingDirectory, fileWriteInfo.FileName, fileWriteInfo.FileExtension));
gitVersionInfoGenerator.Execute(variables, new GitVersionInfoContext(gitVersionOptions.WorkingDirectory, fileWriteInfo.FileName, fileWriteInfo.FileExtension, targetNamespace));
}
}

public void GenerateGitVersionInformation(VersionVariables variables, FileWriteInfo fileWriteInfo) => GenerateGitVersionInformation(variables, fileWriteInfo, null);
}
1 change: 1 addition & 0 deletions src/GitVersion.Core/Model/FileWriteInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ public FileWriteInfo(string workingDirectory, string fileName, string fileExtens
public string WorkingDirectory { get; }
public string FileName { get; }
public string FileExtension { get; }

}
2 changes: 2 additions & 0 deletions src/GitVersion.Core/Model/GitVersionOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public class GitVersionOptions
public WixInfo WixInfo { get; } = new();
public Settings Settings { get; } = new();

public bool UniqueNamespace { get; set; }

public bool Init;
public bool Diag;
public bool IsVersion;
Expand Down
6 changes: 6 additions & 0 deletions src/GitVersion.Core/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
GitVersion.GitVersionOptions.UniqueNamespace.get -> bool
GitVersion.GitVersionOptions.UniqueNamespace.set -> void
GitVersion.GitVersionOutputTool.GenerateGitVersionInformation(GitVersion.OutputVariables.VersionVariables! variables, GitVersion.FileWriteInfo! fileWriteInfo, string? targetNamespace = null) -> void
GitVersion.IGitVersionOutputTool.GenerateGitVersionInformation(GitVersion.OutputVariables.VersionVariables! variables, GitVersion.FileWriteInfo! fileWriteInfo, string? targetNamespace = null) -> void
GitVersion.VersionConverters.GitVersionInfo.GitVersionInfoContext.GitVersionInfoContext(string! workingDirectory, string! fileName, string! fileExtension, string? targetNamespace = null) -> void
GitVersion.VersionConverters.GitVersionInfo.GitVersionInfoContext.TargetNamespace.get -> string?
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ namespace GitVersion.VersionConverters.GitVersionInfo;

public readonly struct GitVersionInfoContext : IConverterContext
{
public GitVersionInfoContext(string workingDirectory, string fileName, string fileExtension)
public GitVersionInfoContext(string workingDirectory, string fileName, string fileExtension) : this(workingDirectory, fileName, fileExtension, null)
{
}

public GitVersionInfoContext(string workingDirectory, string fileName, string fileExtension, string? targetNamespace = null)
{
WorkingDirectory = workingDirectory;
FileName = fileName;
FileExtension = fileExtension;
TargetNamespace = targetNamespace;
}

public string WorkingDirectory { get; }
public string FileName { get; }
public string FileExtension { get; }
public string? TargetNamespace { get; }
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using GitVersion.Extensions;
using GitVersion.Helpers;
using GitVersion.OutputVariables;
using Polly.CircuitBreaker;

namespace GitVersion.VersionConverters.GitVersionInfo;

Expand All @@ -10,13 +11,14 @@ public interface IGitVersionInfoGenerator : IVersionConverter<GitVersionInfoCont

public sealed class GitVersionInfoGenerator : IGitVersionInfoGenerator
{
private const string targetNamespaceSentinelValue = "<unset>";
private readonly IFileSystem fileSystem;
private readonly TemplateManager templateManager;

public GitVersionInfoGenerator(IFileSystem fileSystem)
{
this.fileSystem = fileSystem.NotNull();
this.templateManager = new TemplateManager(TemplateType.GitVersionInfo);
templateManager = new TemplateManager(TemplateType.GitVersionInfo);
}

public void Execute(VersionVariables variables, GitVersionInfoContext context)
Expand All @@ -27,28 +29,51 @@ public void Execute(VersionVariables variables, GitVersionInfoContext context)

string? originalFileContents = null;


if (File.Exists(filePath))
{
originalFileContents = this.fileSystem.ReadAllText(filePath);
originalFileContents = fileSystem.ReadAllText(filePath);
}

var fileExtension = Path.GetExtension(filePath);
var template = this.templateManager.GetTemplateFor(fileExtension);
var addFormat = this.templateManager.GetAddFormatFor(fileExtension);
var template = templateManager.GetTemplateFor(fileExtension);
var addFormat = templateManager.GetAddFormatFor(fileExtension);
var targetNamespace = getTargetNamespace(fileExtension);

if (string.IsNullOrWhiteSpace(template) || string.IsNullOrWhiteSpace(addFormat))
if (string.IsNullOrWhiteSpace(template) || string.IsNullOrWhiteSpace(addFormat) || targetNamespace == targetNamespaceSentinelValue)
return;



var indentation = GetIndentation(fileExtension);
string? closeBracket = null;
string? openBracket = null;
string indent = "";

if (!string.IsNullOrWhiteSpace(targetNamespace) && fileExtension == ".cs")
{
indent = " ";
closeBracket = System.Environment.NewLine + "}";
openBracket = System.Environment.NewLine + "{";
indentation += " ";
}
var members = string.Join(System.Environment.NewLine, variables.Select(v => string.Format(indentation + addFormat, v.Key, v.Value)));

var fileContents = string.Format(template, members);

var fileContents = string.Format(template, members, targetNamespace, openBracket, closeBracket, indent);

if (fileContents != originalFileContents)
{
this.fileSystem.WriteAllText(filePath, fileContents);
fileSystem.WriteAllText(filePath, fileContents);
}

string getTargetNamespace(string fileExtension) => fileExtension switch
{
".vb" => context.TargetNamespace ?? "Global",
".cs" => context.TargetNamespace != null ? $"{System.Environment.NewLine}namespace {context.TargetNamespace};" : "",
".fs" => context.TargetNamespace ?? "global",
_ => targetNamespaceSentinelValue,
};
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ namespace System.Diagnostics.CodeAnalysis
internal sealed class ExcludeFromCodeCoverageAttribute : global::System.Attribute {{ }}
}}
#endif

[global::System.Runtime.CompilerServices.CompilerGenerated]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
static class GitVersionInformation
{{
{1}{2}
{4}[global::System.Runtime.CompilerServices.CompilerGenerated]
{4}[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
{4}static class GitVersionInformation
{4}{{
{0}
}}
{4}}}{3}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace System.Diagnostics.CodeAnalysis
type ExcludeFromCodeCoverageAttribute() = inherit global.System.Attribute()
#endif

namespace global
namespace {1}

[<AbstractClass; Sealed>]
[<global.System.Runtime.CompilerServices.CompilerGenerated>]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Namespace Global.System.Diagnostics.CodeAnalysis
End Namespace
#End If

Namespace Global
Namespace {1}

<Global.System.Runtime.CompilerServices.CompilerGenerated()>
<Global.System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage()>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public void GenerateGitVersionInformationTaskShouldCreateFile()
fileContent.ShouldContain($@"{nameof(VersionVariables.FullSemVer)} = ""1.2.4+1""");
}



[Test]
public void GenerateGitVersionInformationTaskShouldCreateFileInBuildServer()
{
Expand All @@ -50,6 +52,52 @@ public void GenerateGitVersionInformationTaskShouldCreateFileInBuildServer()
fileContent.ShouldContain($@"{nameof(VersionVariables.FullSemVer)} = ""1.0.1+1""");
}

[Test]
public void GenerateGitVersionInformationTaskShouldCreateFileWithUniqueNamespaceSetAndRootNamespaceUnSet()
{
var task = new GenerateGitVersionInformation();
task.ProjectFile = "App.Project.csproj";
task.GenerateGitVersionInformationInUniqueNamespace = "true";
using var result = ExecuteMsBuildTask(task);

result.Success.ShouldBe(true);
result.Errors.ShouldBe(0);
result.Task.GitVersionInformationFilePath.ShouldNotBeNull();

var fileContent = File.ReadAllText(result.Task.GitVersionInformationFilePath);
TestContext.WriteLine(fileContent);
fileContent.ShouldContain($@"{nameof(VersionVariables.Major)} = ""1""");
fileContent.ShouldContain($@"{nameof(VersionVariables.Minor)} = ""2""");
fileContent.ShouldContain($@"{nameof(VersionVariables.Patch)} = ""4""");
fileContent.ShouldContain($@"{nameof(VersionVariables.MajorMinorPatch)} = ""1.2.4""");
fileContent.ShouldContain($@"{nameof(VersionVariables.FullSemVer)} = ""1.2.4+1""");
fileContent.ShouldContain("namespace App.Project");
}

[Test]
public void GenerateGitVersionInformationTaskShouldCreateFileWithUniqueNamespaceSetAndRootNamespaceIsSet()
{
var task = new GenerateGitVersionInformation();
task.ProjectFile = "App.Project.csproj";
task.RootNamespace = "App.Project.RootNamespace";
task.GenerateGitVersionInformationInUniqueNamespace = "true";
using var result = ExecuteMsBuildTask(task);

result.Success.ShouldBe(true);
result.Errors.ShouldBe(0);
result.Task.GitVersionInformationFilePath.ShouldNotBeNull();

var fileContent = File.ReadAllText(result.Task.GitVersionInformationFilePath);
TestContext.WriteLine(fileContent);
fileContent.ShouldContain($@"{nameof(VersionVariables.Major)} = ""1""");
fileContent.ShouldContain($@"{nameof(VersionVariables.Minor)} = ""2""");
fileContent.ShouldContain($@"{nameof(VersionVariables.Patch)} = ""4""");
fileContent.ShouldContain($@"{nameof(VersionVariables.MajorMinorPatch)} = ""1.2.4""");
fileContent.ShouldContain($@"{nameof(VersionVariables.FullSemVer)} = ""1.2.4+1""");

fileContent.ShouldContain("namespace App.Project.RootNamespace");
}

[Test]
public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuild()
{
Expand Down Expand Up @@ -190,10 +238,66 @@ public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildA
fileContent.ShouldContain($@"{nameof(VersionVariables.FullSemVer)} = ""1.0.1+1""");
}

private static void AddGenerateGitVersionInformationTask(ProjectCreator project, string targetToRun, string taskName, string outputProperty, string intermediateOutputPath = "$(MSBuildProjectDirectory)")
[Test]
public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildAndUniqueNamespaceIsSpecifiedAndRootNamespaceIsNotSet()
{
const string taskName = nameof(GenerateGitVersionInformation);
const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath);
var randDir = Guid.NewGuid().ToString("N");

using var result = ExecuteMsBuildExeInAzurePipeline(project => AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty, Path.Combine("$(MSBuildProjectDirectory)", randDir)).Property("GenerateGitVersionInformationInUniqueNamespace", "True"));

result.ProjectPath.ShouldNotBeNullOrWhiteSpace();
result.MsBuild.Count.ShouldBeGreaterThan(0);
result.MsBuild.OverallSuccess.ShouldBe(true);
result.MsBuild.ShouldAllBe(x => x.Succeeded);
result.Output.ShouldNotBeNullOrWhiteSpace();

var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), randDir, "GitVersionInformation.g.cs");
result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}");

var fileContent = File.ReadAllText(generatedFilePath);
fileContent.ShouldContain($@"{nameof(VersionVariables.Major)} = ""1""");
fileContent.ShouldContain($@"{nameof(VersionVariables.Minor)} = ""0""");
fileContent.ShouldContain($@"{nameof(VersionVariables.Patch)} = ""1""");
fileContent.ShouldContain($@"{nameof(VersionVariables.MajorMinorPatch)} = ""1.0.1""");
fileContent.ShouldContain($@"{nameof(VersionVariables.FullSemVer)} = ""1.0.1+1""");
fileContent.ShouldContain($@"namespace App");
}

[Test]
public void GenerateGitVersionInformationTaskShouldCreateFileWhenRunWithMsBuildAndUniqueNamespaceIsSpecifiedAndRootNamespaceIsSet()
{
const string taskName = nameof(GenerateGitVersionInformation);
const string outputProperty = nameof(GenerateGitVersionInformation.GitVersionInformationFilePath);
var randDir = Guid.NewGuid().ToString("N");

using var result = ExecuteMsBuildExe(project => AddGenerateGitVersionInformationTask(project, taskName, taskName, outputProperty, Path.Combine("$(MSBuildProjectDirectory)", randDir)).Property("GenerateGitVersionInformationInUniqueNamespace", "True").Property("RootNamespace", "Test.Root"));

result.ProjectPath.ShouldNotBeNullOrWhiteSpace();
result.MsBuild.Count.ShouldBeGreaterThan(0);
result.MsBuild.OverallSuccess.ShouldBe(true);
result.MsBuild.ShouldAllBe(x => x.Succeeded);
result.Output.ShouldNotBeNullOrWhiteSpace();

var generatedFilePath = PathHelper.Combine(Path.GetDirectoryName(result.ProjectPath), randDir, "GitVersionInformation.g.cs");
result.Output.ShouldContain($"{outputProperty}: {generatedFilePath}");

var fileContent = File.ReadAllText(generatedFilePath);
TestContext.WriteLine(fileContent);
fileContent.ShouldContain($@"{nameof(VersionVariables.Major)} = ""1""");
fileContent.ShouldContain($@"{nameof(VersionVariables.Minor)} = ""2""");
fileContent.ShouldContain($@"{nameof(VersionVariables.Patch)} = ""4""");
fileContent.ShouldContain($@"{nameof(VersionVariables.MajorMinorPatch)} = ""1.2.4""");
fileContent.ShouldContain($@"{nameof(VersionVariables.FullSemVer)} = ""1.2.4+1""");
fileContent.ShouldContain($@"namespace Test.Root");

}

private static ProjectCreator AddGenerateGitVersionInformationTask(ProjectCreator project, string targetToRun, string taskName, string outputProperty, string intermediateOutputPath = "$(MSBuildProjectDirectory)")
{
var assemblyFileLocation = typeof(GitVersionTaskBase).Assembly.Location;
project.UsingTaskAssemblyFile(taskName, assemblyFileLocation)
return project.UsingTaskAssemblyFile(taskName, assemblyFileLocation)
.Property("GenerateAssemblyInfo", "false")
.Target(targetToRun, beforeTargets: "CoreCompile;GetAssemblyVersion;GenerateNuspec")
.Task(taskName, parameters: new Dictionary<string, string?>
Expand All @@ -202,7 +306,9 @@ private static void AddGenerateGitVersionInformationTask(ProjectCreator project,
{ "VersionFile", "$(MSBuildProjectDirectory)/gitversion.json" },
{ "ProjectFile", "$(MSBuildProjectFullPath)" },
{ "IntermediateOutputPath", intermediateOutputPath },
{ "Language", "$(Language)" }
{ "Language", "$(Language)" },
{ "GenerateGitVersionInformationInUniqueNamespace", "$(GenerateGitVersionInformationInUniqueNamespace)" },
{ "RootNamespace", "$(RootNamespace)" },
})
.TaskOutputProperty(outputProperty, outputProperty)
.ItemGroup()
Expand All @@ -212,4 +318,6 @@ private static void AddGenerateGitVersionInformationTask(ProjectCreator project,
.Target(MsBuildExeFixture.OutputTarget, dependsOnTargets: targetToRun)
.TaskMessage($"{outputProperty}: $({outputProperty})", MessageImportance.High);
}


}
1 change: 1 addition & 0 deletions src/GitVersion.MsBuild/GitVersionTaskBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public abstract class GitVersionTaskBase : ITask

public string VersionFile { get; set; }


public TaskLoggingHelper Log { get; }

public bool Execute() => OnExecute();
Expand Down
Loading

0 comments on commit fb8a162

Please sign in to comment.