There's a function in libgit2 to do this.