Skip to content

Commit 6b9afb2

Browse files
jamillnulltoken
authored andcommitted
Teach BranchCollection to disambiguate local and remote branch names
1 parent 745da08 commit 6b9afb2

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

LibGit2Sharp.Tests/BranchFixture.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,27 @@ public void CanListAllBranches()
189189
}
190190
}
191191

192+
[Fact]
193+
public void CanListBranchesWithRemoteAndLocalBranchWithSameShortName()
194+
{
195+
TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath);
196+
197+
using (var repo = new Repository(path.RepositoryPath))
198+
{
199+
// Create a local branch with the same short name as a remote branch.
200+
repo.Branches.Add("origin/master", repo.Branches["origin/test"].Tip);
201+
202+
var expectedWdBranches = new[]
203+
{
204+
"diff-test-cases", "i-do-numbers", "logo", "master", "origin/master", "track-local",
205+
};
206+
207+
Assert.Equal(expectedWdBranches, repo.Branches
208+
.Where(b => !b.IsRemote)
209+
.Select(b => b.Name).ToArray());
210+
}
211+
}
212+
192213
[Fact]
193214
public void CanListAllBranchesWhenGivenWorkingDir()
194215
{

LibGit2Sharp/BranchCollection.cs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ private Branch BuildFromReferenceName(string canonicalName)
9191
/// <returns>An <see cref = "IEnumerator{T}" /> object that can be used to iterate through the collection.</returns>
9292
public virtual IEnumerator<Branch> GetEnumerator()
9393
{
94-
return Proxy.git_branch_foreach(repo.Handle, GitBranchType.GIT_BRANCH_LOCAL | GitBranchType.GIT_BRANCH_REMOTE, (b, t) => Utf8Marshaler.FromNative(b))
94+
return Proxy.git_branch_foreach(repo.Handle, GitBranchType.GIT_BRANCH_LOCAL | GitBranchType.GIT_BRANCH_REMOTE, branchToCanoncialName)
9595
.Select(n => this[n])
9696
.OrderBy(b => b.CanonicalName, StringComparer.Ordinal)
9797
.GetEnumerator();
@@ -197,6 +197,21 @@ private static bool LooksLikeABranchName(string referenceName)
197197
referenceName.StartsWith("refs/remotes/", StringComparison.Ordinal);
198198
}
199199

200+
private static string branchToCanoncialName(IntPtr namePtr, GitBranchType branchType)
201+
{
202+
string shortName = Utf8Marshaler.FromNative(namePtr);
203+
204+
switch (branchType)
205+
{
206+
case GitBranchType.GIT_BRANCH_LOCAL:
207+
return ShortToLocalName(shortName);
208+
case GitBranchType.GIT_BRANCH_REMOTE:
209+
return ShortToRemoteName(shortName);
210+
default:
211+
return shortName;
212+
}
213+
}
214+
200215
private string DebuggerDisplay
201216
{
202217
get

0 commit comments

Comments
 (0)