|
10 | 10 | public class GitVersionContext
|
11 | 11 | {
|
12 | 12 | 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) |
16 | 14 | {
|
17 | 15 | }
|
18 | 16 |
|
@@ -148,5 +146,31 @@ void CalculateEffectiveConfiguration()
|
148 | 146 | currentBranchConfig.TracksReleaseBranches.Value,
|
149 | 147 | currentBranchConfig.IsReleaseBranch.Value);
|
150 | 148 | }
|
| 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 | + } |
151 | 175 | }
|
152 | 176 | }
|
0 commit comments