Get Current Branch Name using libgit2

Get Current Branch Name using libgit2

When interacting with Git repositories at a low level, accessing metadata programmatically can be highly valuable. A common requirement is determining the branch that is currently checked out. Using the libgit2 library in C, this information can be retrieved directly from the repository state.

The branch name can be obtained by inspecting the HEAD reference. In Git, HEAD represents the current position of the repository. In typical scenarios, it points to a branch reference. However, when a specific commit is checked out, HEAD enters a detached state and no longer refers to any branch. This distinction must be handled correctly.

The example below queries the repository for its HEAD, verifies whether it corresponds to a branch, and then extracts the short branch name. If the repository is in a detached state, an empty string is returned instead.

#include <stdio.h>
#include <git2.h>

int get_current_branch_name(git_repository *repo, char *branch_name, const int len) {
    git_reference *head = NULL;
    const int error = git_repository_head(&head, repo);
    if (error != 0) {
        return error;
    }

    if (git_reference_is_branch(head)) {
        snprintf(branch_name, len, "%s", git_reference_shorthand(head));
    } else {
        branch_name[0] = '\0';
    }
    git_reference_free(head);

    return 0;
}

int main() {
    const char *repo_path = "/var/www/myproject";
    git_libgit2_init();

    git_repository *repo = NULL;
    if (git_repository_open(&repo, repo_path) != 0) {
        printf("Failed to open repository\n");
        return 1;
    }

    char branch_name[255];
    if (get_current_branch_name(repo, branch_name, 255)) {
        printf("Failed to get branch name\n");
    } else {
        printf("%s\n", branch_name);
    }

    git_repository_free(repo);
    git_libgit2_shutdown();

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.