Skip to content

Commit e7894ab

Browse files
committed
Move the logic to select the desired branch to its own static method.
1 parent 946ebbf commit e7894ab

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

src/GitVersionCore/GitVersionContext.cs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,7 @@
1010
public class GitVersionContext
1111
{
1212
public GitVersionContext(IRepository repository, string targetBranch, Config configuration, bool onlyEvaluateTrackedBranches = true, string commitId = null)
13-
: this(repository,
14-
repository.Branches.SingleOrDefault(b => b.CanonicalName == targetBranch || b.FriendlyName == targetBranch) ?? repository.Head,
15-
configuration, onlyEvaluateTrackedBranches, commitId)
13+
: this(repository, GitVersionContext.GetTargetBranch(repository, targetBranch), configuration, onlyEvaluateTrackedBranches, commitId)
1614
{
1715
}
1816

@@ -148,5 +146,31 @@ void CalculateEffectiveConfiguration()
148146
currentBranchConfig.TracksReleaseBranches.Value,
149147
currentBranchConfig.IsReleaseBranch.Value);
150148
}
149+
150+
private static Branch GetTargetBranch(IRepository repository, string targetBranch)
151+
{
152+
// By default, we assume HEAD is pointing to the desired branch
153+
var desiredBranch = repository.Head;
154+
155+
// Make sure the desired branch has been specified
156+
if (!string.IsNullOrEmpty(targetBranch))
157+
{
158+
// There are some edge cases where HEAD is not pointing to the desired branch.
159+
// Therefore it's important to verify if 'currentBranch' is indeed the desired branch.
160+
if (desiredBranch.CanonicalName != targetBranch)
161+
{
162+
// In the case where HEAD is not the desired branch, try to find the branch with matching name
163+
desiredBranch = repository?.Branches?
164+
.SingleOrDefault(b =>
165+
b.CanonicalName == targetBranch ||
166+
b.FriendlyName == targetBranch);
167+
168+
// Failsafe in case the specified branch is invalid
169+
desiredBranch = desiredBranch ?? repository.Head;
170+
}
171+
}
172+
173+
return desiredBranch;
174+
}
151175
}
152176
}

0 commit comments

Comments
 (0)