There's a libgit2 function for this.