Advent Day 22: libgit2 and Friends

December 22, 2018

This is day 22 of my Git Tips and Tricks Advent Calendar. If you want to see the whole list of tips as they're published, see the index.

I love scripting against my git repository. Often I'll have an idea for a quick and dirty tool that will help me get my work done - for example, git recover, which helps you locate files that were accidentally deleted from your working tree that never got checked in.

But scripting against git generally means writing Bourne shell scripts and parsing text output. That's fine for simple jobs, but it gets frustrating quickly if you're trying to do something more complicated.

That's when I reach for libgit2.

libgit2 is a pure C library that helps you manage your Git repository. We've taken some of the guts of git itself, and rewritten other parts, to provide you with a library that has a sensible API, is re-entrant, and has a proper object model. This lets you code against your Git repository very efficiently, without trying to parse text output.

For example, to list the paths in the index:

git_repository *repo;
git_index *index;
git_index_entry *entry;
size_t i;

git_repository_open(&repo, "/tmp/myrepo");
git_repository_index(&index, repo);

for (i = 0; i < git_index_entrycount(index); i++) {
    entry = git_index_get_byindex(index, i);
    puts(entry->path);
}

git_index_free(index);
git_repository_free(repo);

Of course, it only lets you code efficiently if you happen to like C. And I do - at least most of the time - but you may not. Thankfully, there are a number of "language binding" projects that wrap libgit2 in other languages. There's LibGit2Sharp for .NET, Rugged for Ruby, and NodeGit for Node.JS. Plus a bunch of others.

libgit2 powers parts of all the major Git hosting providers, including GitHub, GitLab, Bitbucket and Azure Repos. Plus several GUI clients, including GitKraken and gmaster.

I'm happy with some of the contributions that were made to libgit2 this year, from bug fixes and security updates to work to stabilize the API to big new features like patch application support. And I'm excited about what we'll do in 2019.

But I'm more excited to know what you build with it!