Skip to content
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
22 changes: 22 additions & 0 deletions docs/input/docs/reference/build-servers/gitlab.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@ To use GitVersion with GitLab CI, either use the [MSBuild
Task](/docs/usage/msbuild) or put the GitVersion executable in your
runner's `PATH`.

### Tag pipelines

GitVersion uses GitLab's [`CI_COMMIT_TAG` predefined variable](https://docs.gitlab.com/ci/variables/predefined_variables/)
to identify the selected tag. This variable contains the tag name, such as
`1.2.3`, rather than the full `refs/tags/1.2.3` reference. When it is nonempty,
GitVersion treats the build as a tag pipeline rather than using
`CI_COMMIT_REF_NAME` as a branch name.

Rerunning a historical tag pipeline after the branch has advanced can leave HEAD
detached at a commit that is no longer the tip of any branch. If normalization
cannot attach HEAD to a local branch, it checks the selected local tag. When
that tag resolves to the checked-out commit, GitVersion keeps HEAD detached and
avoids a remote lookup that could be ambiguous because GitLab advertises
`refs/pipelines/*` and `refs/environments/*/deployments/*` at the same commit.
Existing branch selection takes precedence when a local branch identifies HEAD.

The selected tag must exist locally and resolve to HEAD for this behavior to
apply. A missing or empty `CI_COMMIT_TAG`, a missing local tag, or a tag pointing
to a different commit does not bypass normal ref discovery. An unrelated local
tag does not identify the build. This behavior does not replace the full Git
history required for version calculation.

### Merge Request pipelines

In merge request pipelines GitLab sets `CI_MERGE_REQUEST_REF_PATH` (for example
Expand Down
15 changes: 15 additions & 0 deletions src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ public void ShouldSetBuildNumber()
this.buildServer.SetBuildNumber(vars).ShouldBe("0.0.0-Beta4.7");
}

[TestCase(null, null)]
[TestCase("", null)]
[TestCase("v1.2.3", "refs/tags/v1.2.3")]
[TestCase("release/1.2.3", "refs/tags/release/1.2.3")]
[TestCase("refs/tags/1.2.3", "refs/tags/refs/tags/1.2.3")]
public void GetCurrentTagShouldUseCommitTagName(string? tagName, string? expected)
{
this.environment.SetEnvironmentVariable(GitLabCi.CommitTagEnvironmentVariableName, tagName);
this.environment.SetEnvironmentVariable(GitLabCi.CommitRefNameEnvironmentVariableName, "different-ref");

this.buildServer.GetCurrentTag().ShouldBe(expected);
}

[Test]
public void ShouldSetOutputVariables()
{
Expand All @@ -62,6 +75,7 @@ public void GetCurrentBranchShouldHandleBranches(string branchName, string expec
var result = this.buildServer.GetCurrentBranch(false);

result.ShouldBe(expectedResult);
this.buildServer.GetCurrentTag().ShouldBeNull();
}

[TestCase("main", "", "main")]
Expand Down Expand Up @@ -93,6 +107,7 @@ public void GetCurrentBranchShouldHandleMergeRequestRefPaths(string refPath, str
this.environment.SetEnvironmentVariable(GitLabCi.CommitRefNameEnvironmentVariableName, "developer");

this.buildServer.GetCurrentBranch(false).ShouldBe(expected);
this.buildServer.GetCurrentTag().ShouldBeNull();
}

[Test]
Expand Down
7 changes: 7 additions & 0 deletions src/GitVersion.BuildAgents/Agents/GitLabCi.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO.Abstractions;
using GitVersion.Git;
using GitVersion.OutputVariables;

namespace GitVersion.Agents;
Expand Down Expand Up @@ -43,6 +44,12 @@ public override string[] SetOutputVariables(string name, string? value) =>
return this.environment.GetEnvironmentVariable(CommitRefNameEnvironmentVariableName);
}

public override string? GetCurrentTag()
{
var tagName = this.environment.GetEnvironmentVariable(CommitTagEnvironmentVariableName);
return string.IsNullOrEmpty(tagName) ? null : ReferenceName.FromTagName(tagName).Canonical;
}

public override bool PreventFetch() => true;

public override void WriteIntegration(Action<string?> writer, GitVersionVariables variables, bool updateBuildNumber = true)
Expand Down
22 changes: 22 additions & 0 deletions src/GitVersion.Core.Tests/Core/ReferenceNameTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,28 @@ namespace GitVersion.Tests;
[TestFixture]
public class ReferenceNameTests
{
[TestCase("1.2.3", "refs/tags/1.2.3")]
[TestCase("release/1.2.3", "refs/tags/release/1.2.3")]
[TestCase("refs/tags/1.2.3", "refs/tags/refs/tags/1.2.3")]
[TestCase("refs/heads/main", "refs/tags/refs/heads/main")]
public void FromTagName_PreservesLiteralName(string tagName, string canonicalName)
{
var referenceName = ReferenceName.FromTagName(tagName);

referenceName.Canonical.ShouldBe(canonicalName);
referenceName.Friendly.ShouldBe(tagName);
referenceName.IsTag.ShouldBeTrue();
referenceName.IsLocalBranch.ShouldBeFalse();
}

[Test]
public void FromTagName_RejectsNull() =>
Should.Throw<ArgumentNullException>(() => ReferenceName.FromTagName(null!)).ParamName.ShouldBe("tagName");

[Test]
public void FromTagName_RejectsEmpty() =>
Should.Throw<ArgumentException>(() => ReferenceName.FromTagName("")).ParamName.ShouldBe("tagName");

[TestCase("refs/remotes/origin/release/1.0.0", "release/1.0.0", true)]
[TestCase("refs/remotes/upstream/release/1.0.0", "release/1.0.0", false)]
public void EquivalentTo_UsesOriginStrippedName(string canonicalName, string name, bool expected)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,118 @@ namespace GitVersion.Tests.IntegrationTests;
[TestFixture]
public class RemoteRepositoryScenarios : TestBase
{
[TestCase(false, false)]
[TestCase(true, false)]
[TestCase(false, true)]
[TestCase(true, true)]
public void GitLabHistoricalTagIgnoresPipelineAndDeploymentRefs(bool annotated, bool unavailableRemote)
{
using var fixture = new RemoteRepositoryFixture(path =>
{
Repository.Init(path);
var repository = new Repository(path);
repository.MakeACommit();
if (annotated)
{
repository.ApplyTag("1.2.3", repository.Head.Tip.Author, "Release");
}
else
{
repository.ApplyTag("1.2.3");
}
repository.Refs.Add("refs/pipelines/42", repository.Head.Tip.Id);
repository.Refs.Add("refs/environments/production/deployments/1", repository.Head.Tip.Id);
repository.Refs.Add("refs/environments/production/deployments/2", repository.Head.Tip.Id);
repository.MakeACommit();
return repository;
});
var repository = fixture.LocalRepositoryFixture.Repository;
var commit = (Commit)repository.Tags["1.2.3"].PeeledTarget;
Commands.Checkout(repository, commit);
if (unavailableRemote)
{
repository.Network.Remotes.Update("origin", remote =>
remote.Url = Path.Combine(fixture.LocalRepositoryFixture.RepositoryPath, "missing-remote"));
}

PrepareOnGitLab(fixture.LocalRepositoryFixture.RepositoryPath, "1.2.3", "1.2.3");

repository.Head.Tip.Sha.ShouldBe(commit.Sha);
repository.Info.IsHeadDetached.ShouldBeTrue();
fixture.AssertFullSemver("1.2.3", repository: repository);
}

[TestCase(null)]
[TestCase("")]
[TestCase("missing")]
[TestCase("1.2.3")]
public void GitLabHistoricalCommitWithoutMatchingTagStillDiscoversRemoteRefs(string? tagName)
{
using var fixture = new RemoteRepositoryFixture(path =>
{
Repository.Init(path);
var repository = new Repository(path);
repository.MakeACommit();
repository.Refs.Add("refs/pipelines/42", repository.Head.Tip.Id);
repository.Refs.Add("refs/environments/production/deployments/1", repository.Head.Tip.Id);
repository.MakeATaggedCommit("1.2.3");
return repository;
});
var repository = fixture.LocalRepositoryFixture.Repository;
var commit = repository.Head.Tip.Parents.Single();
Commands.Checkout(repository, commit);
repository.ApplyTag("local-only");

var exception = Should.Throw<WarningException>(() =>
PrepareOnGitLab(fixture.LocalRepositoryFixture.RepositoryPath, tagName));

exception.Message.ShouldContain("Found more than one remote tip");
exception.Message.ShouldContain("refs/pipelines/42");
exception.Message.ShouldContain("refs/environments/production/deployments/1");
repository.Head.Tip.Sha.ShouldBe(commit.Sha);
repository.Info.IsHeadDetached.ShouldBeTrue();
}

[TestCase("feature/work", null, "feature/work")]
[TestCase("feature/work", "refs/merge-requests/42/head", "merge-requests/42/head")]
public void GitLabTaggedCommitPreservesBranchAndMergeRequestContext(string refName, string? mergeRequest, string expectedBranch)
{
using var fixture = new RemoteRepositoryFixture();
var repository = fixture.LocalRepositoryFixture.Repository;
var commit = repository.Head.Tip;
repository.ApplyTag("1.2.3");
repository.MakeACommit();
Commands.Checkout(repository, commit);
repository.Refs.Remove("refs/remotes/origin/main");

PrepareOnGitLab(fixture.LocalRepositoryFixture.RepositoryPath, null, refName, mergeRequest);

repository.Head.Tip.Sha.ShouldBe(commit.Sha);
repository.Info.IsHeadDetached.ShouldBeFalse();
repository.Head.FriendlyName.ShouldBe(expectedBranch);
}

private static void PrepareOnGitLab(string workingDirectory, string? tagName, string? refName = null, string? mergeRequest = null)
{
var options = Options.Create(new GitVersionOptions
{
WorkingDirectory = workingDirectory,
Settings = { NoNormalize = false, NoFetch = true }
});
var environment = new TestEnvironment();
environment.SetEnvironmentVariable(GitLabCi.EnvironmentVariableName, "true");
environment.SetEnvironmentVariable(GitLabCi.CommitTagEnvironmentVariableName, tagName);
environment.SetEnvironmentVariable(GitLabCi.CommitRefNameEnvironmentVariableName, refName);
environment.SetEnvironmentVariable(GitLabCi.MergeRequestRefPathEnvironmentVariableName, mergeRequest);
var sp = ConfigureServices(services =>
{
services.AddSingleton(options);
services.AddSingleton<IEnvironment>(environment);
});
sp.DiscoverRepository();
sp.GetRequiredService<IGitPreparer>().Prepare();
}

[TestCase(false, false)]
[TestCase(true, false)]
[TestCase(false, true)]
Expand Down
7 changes: 7 additions & 0 deletions src/GitVersion.Core/Git/ReferenceName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ public static ReferenceName FromBranchName(string branchName)
? value
: Parse(LocalBranchPrefix + branchName);

/// <summary>Creates a <see cref="ReferenceName"/> from a literal tag name, always prepending <c>refs/tags/</c>.</summary>
public static ReferenceName FromTagName(string tagName)
{
ArgumentException.ThrowIfNullOrEmpty(tagName);
return new ReferenceName(TagPrefix + tagName);
}

/// <summary>Gets the canonical reference name (e.g. <c>refs/heads/main</c>).</summary>
public string Canonical { get; }

Expand Down
1 change: 1 addition & 0 deletions src/GitVersion.Core/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#nullable enable
static GitVersion.Git.ReferenceName.FromTagName(string! tagName) -> GitVersion.Git.ReferenceName!
GitVersion.Agents.IBuildAgent.GetCurrentTag() -> string?
GitVersion.ConfigurationMigrationInfo
GitVersion.ConfigurationMigrationInfo.ConfigurationMigrationInfo() -> void
Expand Down
Loading