Skip to content

Commit 3019076

Browse files
Fix tag normalization for Azure Pipelines
1 parent 81425de commit 3019076

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

src/GitVersion.BuildAgents.Tests/Agents/AzurePipelinesTests.cs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,43 @@ public void AzurePipelinesBuildNumberWithSemVer(string buildNumberFormat, string
7777
var logMessage = this.buildServer.GenerateSetVersionMessage(vars);
7878
logMessage.ShouldBe(logPrefix + expectedBuildNumber);
7979
}
80+
81+
[Test]
82+
public void GetCurrentBranchShouldHandleBranches()
83+
{
84+
// Arrange
85+
this.environment.SetEnvironmentVariable("BUILD_SOURCEBRANCH", $"refs/heads/{MainBranch}");
86+
87+
// Act
88+
var result = this.buildServer.GetCurrentBranch(false);
89+
90+
// Assert
91+
result.ShouldBe($"refs/heads/{MainBranch}");
92+
}
93+
94+
[Test]
95+
public void GetCurrentBranchShouldHandleTags()
96+
{
97+
// Arrange
98+
this.environment.SetEnvironmentVariable("BUILD_SOURCEBRANCH", "refs/tags/1.0.0");
99+
100+
// Act
101+
var result = this.buildServer.GetCurrentBranch(false);
102+
103+
// Assert
104+
result.ShouldBeNull();
105+
}
106+
107+
[Test]
108+
public void GetCurrentBranchShouldHandlePullRequests()
109+
{
110+
// Arrange
111+
this.environment.SetEnvironmentVariable("BUILD_SOURCEBRANCH", "refs/pull/1/merge");
112+
113+
// Act
114+
var result = this.buildServer.GetCurrentBranch(false);
115+
116+
// Assert
117+
result.ShouldBe("refs/pull/1/merge");
118+
}
80119
}

src/GitVersion.BuildAgents/Agents/AzurePipelines.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,24 @@ public override string[] GenerateSetParameterMessage(string name, string? value)
1616
$"##vso[task.setvariable variable=GitVersion.{name};isOutput=true]{value}"
1717
];
1818

19-
public override string? GetCurrentBranch(bool usingDynamicRepos) => Environment.GetEnvironmentVariable("GIT_BRANCH")
20-
?? Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH");
19+
public override string? GetCurrentBranch(bool usingDynamicRepos)
20+
{
21+
var gitBranch = Environment.GetEnvironmentVariable("GIT_BRANCH");
22+
if (gitBranch is not null)
23+
return gitBranch;
24+
25+
var sourceBranch = Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH");
26+
27+
// https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml
28+
// BUILD_SOURCEBRANCH must be used only for "real" branches, not for tags.
29+
// Azure Pipelines sets BUILD_SOURCEBRANCH to refs/tags/<tag> when the pipeline is triggered for a tag.
30+
if (sourceBranch?.StartsWith("refs/tags", StringComparison.OrdinalIgnoreCase) == true)
31+
{
32+
return null;
33+
}
34+
35+
return sourceBranch;
36+
}
2137

2238
public override bool PreventFetch() => true;
2339

0 commit comments

Comments
 (0)