Skip to content

Commit d587fce

Browse files
ChristopherMannasbjornu
authored andcommitted
Fix tag normalization for Azure Pipelines
1 parent c2bc09f commit d587fce

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

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

+39
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,43 @@ public void AzurePipelinesBuildNumberWithSemVer(string buildNumberFormat, string
7777
var logMessage = this.buildServer.SetBuildNumber(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

+18-2
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,24 @@ public override string[] SetOutputVariables(string name, string? value) =>
1717
$"##vso[task.setvariable variable=GitVersion.{name};isOutput=true]{value}"
1818
];
1919

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

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

0 commit comments

Comments
 (0)