Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current/active branch with LibGit2Sharp?

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?

like image 379
Simon Avatar asked Oct 11 '12 10:10

Simon


2 Answers

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...

like image 89
Brendan Forster Avatar answered Oct 28 '22 13:10

Brendan Forster


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]
like image 2
Rubms Avatar answered Oct 28 '22 12:10

Rubms