Search code examples
libgit2sharp

How to get the current branch with LibGit2Sharp?


How do I get the branch for a specific directory even if this directory is not the root of the repo ? iow the equivalent of

git branch --show-current

(which works fine even in a subdirectory).

Following the answer to this similar question, I did as follows, which works only in the root dir of the repo:

using (var git = new Repository("repo_root\subdir")) // throws if subdir
{
  return git.Head.FriendlyName;
}

Solution

  • Oops, found it:

    using (var git = new Repository(
      LibGit2Sharp.Repository.Discover(@"repo_root\subdir")))
    {
      return git.Head.FriendlyName;
    }