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!
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
HEAD
reference (try the git_repository_head()
convenience method)git_reference_type()
)GIT_REFERENCE_SYMBOLIC
or GIT_REFERENCE_DIRECT
) retrieve one of the following
git_reference_symbolic_target()
)git_reference_target()
)I did not find the existing answer/comments helpful, when having this exact problem. Instead I combined git_reference_lookup()
and git_reference_symbolic_target()
.
git_reference* head_ref;
git_reference_lookup(&head_ref, repo, "HEAD");
const char *symbolic_ref;
symbolic_ref = git_reference_symbolic_target(head_ref);
std::string result;
// Skip leading "refs/heads/" -- 11 chars.
if (symbolic_ref) result = &symbolic_ref[11];
git_reference_free(head_ref);
This feels like something of a dirty hack, but it's the best I've managed. The result
string either ends up empty (e.g. detached head, there is no checked out branch) or contains the name of the checked out branch. The symbolic target is owned by the ref, so copy that value into the string before freeing it!
There is an example for this at https://libgit2.org/libgit2/ex/HEAD/status.html . It is based around the method get_reference_shorthand
. This should give the branch name instead of the reference, so no string manipulation needed, and it should also work in the edge case where branch and remote have different names.
static void show_branch(git_repository *repo, int format)
{
int error = 0;
const char *branch = NULL;
git_reference *head = NULL;
error = git_repository_head(&head, repo);
if (error == GIT_EUNBORNBRANCH || error == GIT_ENOTFOUND)
branch = NULL;
else if (!error) {
branch = git_reference_shorthand(head);
} else
check_lg2(error, "failed to get current branch", NULL);
if (format == FORMAT_LONG)
printf("# On branch %s\n",
branch ? branch : "Not currently on any branch.");
else
printf("## %s\n", branch ? branch : "HEAD (no branch)");
git_reference_free(head);
}