How to get the current/active branch with LibGit2Sharp?
Asked Answered
C

2

20

So using LibGit2Sharp https://github.com/libgit2/libgit2sharp you can walk through the branches like this

using (var repo = new Repository(@"path to .git"))
{
    foreach (var branch in repo.Branches)
    {
        Debug.WriteLine(branch.Name);   
    }
}

But how do I get the current/active branch?

Cecum answered 11/10, 2012 at 10:18 Comment(0)
C
25

Branch.IsCurrentRepositoryHead should do the trick.

I think Repository.Head will also do the same thing if you don't want to iterate through the branches...

Clothe answered 11/10, 2012 at 10:37 Comment(2)
In case it catches anyone else, because of how exact this property is, it will return false if you have checked out Branch but you are either behind or ahead of that branch on a fetched remote.Telemeter
This function should not care at all about any remote repositories. It literally does a string compare against the branch names. If you think it does change depending on remote repositories, please file a bug report with a reproduction case.Tenterhook
M
2

I think that, instead of going through the branches and checking whether each branch is the current head, the simplest approach is to directly get the branch name from the repository Head:

using (var repo = new Repository(@"path to .git"))
{
    var currentBranchName = repo.Head.FriendlyName;
}

You can then obtain the branch itself via

repo.Branches[currentBranchName]
Moneyed answered 19/1, 2018 at 11:44 Comment(1)
You can just use the Head to get the branch: repo.Head.Reference.TargetIdentifier.Tenterhook

© 2022 - 2024 — McMap. All rights reserved.