If you need to read Git repositories from Go, instead of calling git
command-line tool, consider using gogit.
Gogit is Git repository reader written in pure Go. You can access any object stored in git object store: blobs, commits, trees, tags.
How to use gogit
First you need to open a repository by calling OpenRepository
function with a path to the repo. Then you can use Lookup...
methods to find objects:
LookupBlob
— finds the blob by its SHA1,LookupCommit
— finds a commit by its SHA1,LookupReference
— finds a reference, such as HEAD, a branch, a tag, by its name,LookupTag
— finds a tag object by its SHA1,LookupTree
— finds a tree object by its SHA1.
You can also query repository for the size of object using ObjectSize
method, and its type by calling Type
and passing them an object hash.
SHA1 hashes for those functions are represented with pointers to struct of Oid
type:
type Oid struct {
Bytes SHA1
}
which you can create from bytes or hex string.
Here’s an example from README of how to open repository, find its HEAD, get the tree for the latest commit, and walk it, printing file names:
package main
import (
"github.com/speedata/gogit"
"log"
"os"
"path"
"path/filepath"
)
func walk(dirname string, te *gogit.TreeEntry) int {
log.Println(path.Join(dirname, te.Name))
return 0
}
func main() {
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
repository, err := gogit.OpenRepository(filepath.Join(wd, "src/github.com/speedata/gogit/_testdata/testrepo.git"))
if err != nil {
log.Fatal(err)
}
ref, err := repository.LookupReference("HEAD")
if err != nil {
log.Fatal(err)
}
ci, err := repository.LookupCommit(ref.Oid)
if err != nil {
log.Fatal(err)
}
ci.tree.Walk(walk)
}
Looks pretty easy!
How to get gogit
You can install gogit with go get
:
go get github.com/speedata/gogit
Source code and license
GitHub: https://github.com/speedata/gogit
Documentation: http://godoc.org/github.com/speedata/gogit
Author: Patrick Gundlach (@patrickgundlach)
License: MIT