Search code examples
libgit2

How do I get the name of the current branch in libgit2?


I am trying to use libgit2 to read the name of the current branch. Do I have to do some sort of resolve?

I tried using

git_branch_lookup

to look up the git_reference for HEAD, but it results in

Unable to find local branch 'HEAD'

Thanks!


Solution

  • Running git branch -a doesn't list HEAD. In libgit2, HEAD isn't considered a valid branch either. It's only a reference.

    If you want to discover which reference is the current branch, then you should

    • Load the current HEAD reference (try the git_repository_head() convenience method)
    • Determine its type (using git_reference_type())
    • Depending on its type (GIT_REFERENCE_SYMBOLIC or GIT_REFERENCE_DIRECT) retrieve one of the following
      • The name of the branch (using git_reference_symbolic_target())
      • The commit being pointed at (using git_reference_target())