diff --git a/docs/input/docs/reference/build-servers/gitlab.md b/docs/input/docs/reference/build-servers/gitlab.md index 7be73bc32e..2c00f5ba67 100755 --- a/docs/input/docs/reference/build-servers/gitlab.md +++ b/docs/input/docs/reference/build-servers/gitlab.md @@ -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 diff --git a/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs b/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs index 380c476cf8..881c0c5765 100644 --- a/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs +++ b/src/GitVersion.BuildAgents.Tests/Agents/GitLabCiTests.cs @@ -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() { @@ -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")] @@ -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] diff --git a/src/GitVersion.BuildAgents/Agents/GitLabCi.cs b/src/GitVersion.BuildAgents/Agents/GitLabCi.cs index 3627e1ce12..f11652dc23 100644 --- a/src/GitVersion.BuildAgents/Agents/GitLabCi.cs +++ b/src/GitVersion.BuildAgents/Agents/GitLabCi.cs @@ -1,4 +1,5 @@ using System.IO.Abstractions; +using GitVersion.Git; using GitVersion.OutputVariables; namespace GitVersion.Agents; @@ -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 writer, GitVersionVariables variables, bool updateBuildNumber = true) diff --git a/src/GitVersion.Core.Tests/Core/ReferenceNameTests.cs b/src/GitVersion.Core.Tests/Core/ReferenceNameTests.cs index 7c25fb12c7..c7de807bc6 100644 --- a/src/GitVersion.Core.Tests/Core/ReferenceNameTests.cs +++ b/src/GitVersion.Core.Tests/Core/ReferenceNameTests.cs @@ -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(() => ReferenceName.FromTagName(null!)).ParamName.ShouldBe("tagName"); + + [Test] + public void FromTagName_RejectsEmpty() => + Should.Throw(() => 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) diff --git a/src/GitVersion.Core.Tests/IntegrationTests/RemoteRepositoryScenarios.cs b/src/GitVersion.Core.Tests/IntegrationTests/RemoteRepositoryScenarios.cs index 66f9d9cd44..eeb2d82f60 100644 --- a/src/GitVersion.Core.Tests/IntegrationTests/RemoteRepositoryScenarios.cs +++ b/src/GitVersion.Core.Tests/IntegrationTests/RemoteRepositoryScenarios.cs @@ -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(() => + 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(environment); + }); + sp.DiscoverRepository(); + sp.GetRequiredService().Prepare(); + } + [TestCase(false, false)] [TestCase(true, false)] [TestCase(false, true)] diff --git a/src/GitVersion.Core/Git/ReferenceName.cs b/src/GitVersion.Core/Git/ReferenceName.cs index 5f5267328e..0347441b69 100644 --- a/src/GitVersion.Core/Git/ReferenceName.cs +++ b/src/GitVersion.Core/Git/ReferenceName.cs @@ -58,6 +58,13 @@ public static ReferenceName FromBranchName(string branchName) ? value : Parse(LocalBranchPrefix + branchName); + /// Creates a from a literal tag name, always prepending refs/tags/. + public static ReferenceName FromTagName(string tagName) + { + ArgumentException.ThrowIfNullOrEmpty(tagName); + return new ReferenceName(TagPrefix + tagName); + } + /// Gets the canonical reference name (e.g. refs/heads/main). public string Canonical { get; } diff --git a/src/GitVersion.Core/PublicAPI.Unshipped.txt b/src/GitVersion.Core/PublicAPI.Unshipped.txt index b463674315..3af92616af 100644 --- a/src/GitVersion.Core/PublicAPI.Unshipped.txt +++ b/src/GitVersion.Core/PublicAPI.Unshipped.txt @@ -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