Skip to content

Use the environment variable GIT_BRANCH as the current branch everywhere #3049

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
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
24 changes: 19 additions & 5 deletions src/GitVersion.Core.Tests/Extensions/GitToolsTestingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,16 @@ public static IBranch CreateMockBranch(string name, params ICommit[] commits)

public static void DumpGraph(this IRepository repository, Action<string>? writer = null, int? maxCommits = null) => GitExtensions.DumpGraph(repository.ToGitRepository().Path, writer, maxCommits);

public static VersionVariables GetVersion(this RepositoryFixtureBase fixture, Config? configuration = null, IRepository? repository = null, string? commitId = null, bool onlyTrackedBranches = true, string? branch = null)
public static VersionVariables GetVersion(
this RepositoryFixtureBase fixture,
Config? configuration = null,
IRepository? repository = null,
string? commitId = null,
bool onlyTrackedBranches = true,
string? branch = null,
Action<IServiceProvider>? configureServices = null)
{
configuration ??= new ConfigurationBuilder().Build();

repository ??= fixture.Repository;

var options = Options.Create(new GitVersionOptions
Expand All @@ -73,11 +79,11 @@ public static VersionVariables GetVersion(this RepositoryFixtureBase fixture, Co
});

var sp = ConfigureServices(services => services.AddSingleton(options));
configureServices?.Invoke(sp);

var variableProvider = sp.GetRequiredService<IVariableProvider>();
var nextVersionCalculator = sp.GetRequiredService<INextVersionCalculator>();
var contextOptions = sp.GetRequiredService<Lazy<GitVersionContext>>();

var context = contextOptions.Value;

try
Expand All @@ -104,15 +110,23 @@ public static void WriteVersionVariables(this RepositoryFixtureBase fixture, str
writer.Write(versionInfo.ToString());
}

public static void AssertFullSemver(this RepositoryFixtureBase fixture, string fullSemver, Config? configuration = null, IRepository? repository = null, string? commitId = null, bool onlyTrackedBranches = true, string? targetBranch = null)
public static void AssertFullSemver(
this RepositoryFixtureBase fixture,
string fullSemver,
Config? configuration = null,
IRepository? repository = null,
string? commitId = null,
bool onlyTrackedBranches = true,
string? targetBranch = null,
Action<IServiceProvider>? configureServices = null)
{
configuration ??= new Config();
configuration = new ConfigurationBuilder().Add(configuration).Build();
Console.WriteLine("---------");

try
{
var variables = fixture.GetVersion(configuration, repository, commitId, onlyTrackedBranches, targetBranch);
var variables = fixture.GetVersion(configuration, repository, commitId, onlyTrackedBranches, targetBranch, configureServices);
variables.FullSemVer.ShouldBe(fullSemver);
}
catch (Exception)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,23 @@ public void GivenARemoteGitRepositoryWhenCheckingOutDetachedHeadUsingExistingImp
$"It looks like the branch being examined is a detached Head pointing to commit '{fixture.LocalRepositoryFixture.Repository.Head.Tip.Id.ToString(7)}'. Without a proper branch name GitVersion cannot determine the build version.");
}

[Test]
public void GivenARemoteGitRepositoryWhenCheckingOutDetachedHeadWithEnvironmentVariableSucceeds()
{
using var fixture = new RemoteRepositoryFixture();
var local = fixture.LocalRepositoryFixture;
Commands.Checkout(local.Repository, local.Repository.Head.Tip);

fixture.AssertFullSemver("0.1.0+4",
repository: local.Repository,
configureServices: sp =>
{
sp.GetRequiredService<IEnvironment>().SetEnvironmentVariable("GIT_BRANCH", "main");
sp.GetRequiredService<IGitPreparer>().Prepare();
});
}


[Test]
[Ignore("Needs more investigations.")]
public void GivenARemoteGitRepositoryWhenCheckingOutDetachedHeadUsingTrackingBranchOnlyBehaviourShouldReturnVersion014Plus5()
Expand Down
5 changes: 4 additions & 1 deletion src/GitVersion.Core/BuildAgents/LocalBuild.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ namespace GitVersion.BuildAgents;

public class LocalBuild : BuildAgentBase
{
public LocalBuild(IEnvironment environment, ILog log) : base(environment, log)
public LocalBuild(IEnvironment environment, ILog log)
: base(environment, log)
{
}

protected override string EnvironmentVariable => string.Empty;
public override string? GetCurrentBranch(bool usingDynamicRepos) => Environment.GetEnvironmentVariable("GIT_BRANCH");
public override bool CanApplyToCurrentContext() => true;
public override string? GenerateSetVersionMessage(VersionVariables variables) => null;
public override string[] GenerateSetParameterMessage(string name, string value) => Array.Empty<string>();
Expand Down
15 changes: 1 addition & 14 deletions src/GitVersion.Core/Core/GitPreparer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ public void Prepare()
// Normalize if we are running on build server
var normalizeGitDirectory = !gitVersionOptions.Settings.NoNormalize && this.buildAgent is not LocalBuild;
var shouldCleanUpRemotes = this.buildAgent.ShouldCleanUpRemotes();
var currentBranch = ResolveCurrentBranch();

var currentBranch = this.context.CurrentBranch?.Name.WithoutRemote;
var dotGitDirectory = this.repositoryInfo.DotGitDirectory;
var projectRoot = this.repositoryInfo.ProjectRootDirectory;

Expand Down Expand Up @@ -79,18 +78,6 @@ private void PrepareInternal(bool normalizeGitDirectory, string? currentBranch,
}
}

private string? ResolveCurrentBranch()
{
var gitVersionOptions = this.options.Value;
var targetBranch = gitVersionOptions.RepositoryInfo.TargetBranch;

var isDynamicRepository = !gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath.IsNullOrWhiteSpace();
var currentBranch = this.buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch;
this.log.Info("Branch from build environment: " + currentBranch);

return currentBranch;
}

private void CleanupDuplicateOrigin()
{
var remoteToKeep = DefaultRemoteName;
Expand Down
71 changes: 59 additions & 12 deletions src/GitVersion.Core/Core/GitVersionContextFactory.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using GitVersion.BuildAgents;
using GitVersion.Common;
using GitVersion.Configuration;
using GitVersion.Extensions;
using GitVersion.Logging;
using Microsoft.Extensions.Options;

namespace GitVersion;
Expand All @@ -10,36 +12,81 @@ public class GitVersionContextFactory : IGitVersionContextFactory
private readonly IConfigProvider configProvider;
private readonly IRepositoryStore repositoryStore;
private readonly IBranchConfigurationCalculator branchConfigurationCalculator;
private readonly IBuildAgent buildAgent;
private readonly ILog log;
private readonly IOptions<GitVersionOptions> options;

public GitVersionContextFactory(IConfigProvider configProvider, IRepositoryStore repositoryStore, IBranchConfigurationCalculator branchConfigurationCalculator, IOptions<GitVersionOptions> options)
public GitVersionContextFactory(IConfigProvider configProvider, IRepositoryStore repositoryStore, IBranchConfigurationCalculator branchConfigurationCalculator, IBuildAgentResolver buildAgentResolver, ILog log, IOptions<GitVersionOptions> options)
{
this.configProvider = configProvider.NotNull();
this.repositoryStore = repositoryStore.NotNull();
this.branchConfigurationCalculator = branchConfigurationCalculator.NotNull();
this.buildAgent = buildAgentResolver.NotNull().Resolve();
this.log = log.NotNull();
this.options = options.NotNull();
}

public GitVersionContext Create(GitVersionOptions gitVersionOptions)
{
var currentBranch = this.repositoryStore.GetTargetBranch(gitVersionOptions.RepositoryInfo.TargetBranch);
if (currentBranch == null)
throw new InvalidOperationException("Need a branch to operate on");
var branchCommit = ResolveCurrentBranchCommit(gitVersionOptions);
var currentBranch = branchCommit.Branch;
var currentCommit = branchCommit.Commit;
var configuration = this.configProvider.Provide(this.options.Value.ConfigInfo.OverrideConfig);
var currentBranchConfig = this.branchConfigurationCalculator.GetBranchConfiguration(currentBranch, currentCommit, configuration);
var effectiveConfiguration = configuration.CalculateEffectiveConfiguration(currentBranchConfig);
var currentCommitTaggedVersion = this.repositoryStore.GetCurrentCommitTaggedVersion(currentCommit, effectiveConfiguration);
var numberOfUncommittedChanges = this.repositoryStore.GetNumberOfUncommittedChanges();

return new GitVersionContext(currentBranch, currentCommit, configuration, effectiveConfiguration, currentCommitTaggedVersion, numberOfUncommittedChanges);
}

private BranchCommit ResolveCurrentBranchCommit(GitVersionOptions gitVersionOptions)
{
var currentBranch = ResolveCurrentBranch();
var currentCommit = this.repositoryStore.GetCurrentCommit(currentBranch, gitVersionOptions.RepositoryInfo.CommitId);

var configuration = this.configProvider.Provide(this.options.Value.ConfigInfo.OverrideConfig);
if (currentBranch.IsDetachedHead)
{
var branchForCommit = this.repositoryStore.GetBranchesContainingCommit(currentCommit, onlyTrackedBranches: gitVersionOptions.Settings.OnlyTrackedBranches).OnlyOrDefault();
currentBranch = branchForCommit ?? currentBranch;
currentBranch = this.repositoryStore.GetBranchesContainingCommit(currentCommit,
onlyTrackedBranches: gitVersionOptions.Settings.OnlyTrackedBranches).OnlyOrDefault()
?? currentBranch;
}

var currentBranchConfig = this.branchConfigurationCalculator.GetBranchConfiguration(currentBranch, currentCommit, configuration);
var effectiveConfiguration = configuration.CalculateEffectiveConfiguration(currentBranchConfig);
var currentCommitTaggedVersion = this.repositoryStore.GetCurrentCommitTaggedVersion(currentCommit, effectiveConfiguration);
var numberOfUncommittedChanges = this.repositoryStore.GetNumberOfUncommittedChanges();
return new BranchCommit(currentCommit, currentBranch);
}

return new GitVersionContext(currentBranch, currentCommit, configuration, effectiveConfiguration, currentCommitTaggedVersion, numberOfUncommittedChanges);
private IBranch ResolveCurrentBranch()
{
var currentBranchName = ResolveCurrentBranchName();
var currentBranch = this.repositoryStore.GetTargetBranch(currentBranchName);

if (currentBranch == null)
throw new InvalidOperationException("Need a branch to operate on");

return currentBranch;
}

private string? ResolveCurrentBranchName()
{
var gitVersionOptions = this.options.Value;
var isDynamicRepository = !gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath.IsNullOrWhiteSpace();
var currentBranch = this.buildAgent.GetCurrentBranch(isDynamicRepository);

if (!currentBranch.IsNullOrWhiteSpace())
{
this.log.Info($"Branch from build environment: {currentBranch}");
return currentBranch;
}

var targetBranch = gitVersionOptions.RepositoryInfo.TargetBranch;

if (!targetBranch.IsNullOrWhiteSpace())
{
this.log.Info($"Branch from Git repository: {targetBranch}");
return targetBranch;
}

this.log.Info($"No branch found in environment or repository; this is probably a detached HEAD.");
return null;
}
}
35 changes: 18 additions & 17 deletions src/GitVersion.Core/Model/GitVersionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,28 @@
namespace GitVersion;

/// <summary>
/// Contextual information about where GitVersion is being run
/// Contextual information about where GitVersion is being run
/// </summary>
public class GitVersionContext
{
public GitVersionContext(
IBranch currentBranch,
ICommit? currentCommit,
Config configuration,
EffectiveConfiguration effectiveConfiguration,
SemanticVersion currentCommitTaggedVersion,
int numberOfUncommittedChanges)
{
CurrentBranch = currentBranch;
CurrentCommit = currentCommit;
FullConfiguration = configuration;
Configuration = effectiveConfiguration;
CurrentCommitTaggedVersion = currentCommitTaggedVersion;
NumberOfUncommittedChanges = numberOfUncommittedChanges;
}

/// <summary>
/// Contains the raw configuration, use Configuration for specific config based on the current GitVersion context.
/// Contains the raw configuration, use Configuration for specific config based on the current GitVersion context.
/// </summary>
public Config FullConfiguration { get; }

Expand All @@ -17,20 +33,5 @@ public class GitVersionContext
public IBranch CurrentBranch { get; }
public ICommit? CurrentCommit { get; }
public bool IsCurrentCommitTagged => CurrentCommitTaggedVersion != null;

public int NumberOfUncommittedChanges { get; }

public GitVersionContext(IBranch currentBranch, ICommit? currentCommit,
Config configuration, EffectiveConfiguration effectiveConfiguration,
SemanticVersion currentCommitTaggedVersion, int numberOfUncommittedChanges)
{
CurrentBranch = currentBranch;
CurrentCommit = currentCommit;

FullConfiguration = configuration;
Configuration = effectiveConfiguration;

CurrentCommitTaggedVersion = currentCommitTaggedVersion;
NumberOfUncommittedChanges = numberOfUncommittedChanges;
}
}