Git Log as JSON in Go
Published in
1 min readJul 23, 2019
For reasons I wanted git log
to be parsed in Go and it looks like the easiest way to do that is to output it as JSON and parse into Go structs.
First we need to define the format for the JSON (borrowed from here):
var GITFORMAT string = `--pretty=format:{
"commit": "%H",
"parent": "%P",
"refs": "%D",
"subject": "%s",
"author": { "name": "%aN", "email": "%aE", "date": "%ad" },
"commiter": { "name": "%cN", "email": "%cE", "date": "%cd" }
},`
Then define the structs:
type GitPerson struct {
Name string `json:"name"`
Email string `json:"email"`
Date *time.Time `json:"date"`
}type GitCommit struct {
Commit string `json:"commit"`
Parent string `json:"parent"`
Refs string `json:"refs"`
Subject string `json:"subject"` Author GitPerson `json:"author"`
Commiter GitPerson `json:"commiter"`
}
The function will then run git log
and Unmarshal
the result:
func gitLog() ([]GitCommit, error) {
args := []string{
"log",
"--date=iso-strict",
"--first-parent",
GITFORMAT,
} cmd := exec.Command("git", args...)
out, _ := cmd.Output()
logOut := string(out)
logOut = logOut[:len(logOut)-1] // Remove the last ","
logOut = fmt.Sprintf("[%s]", logOut) // Add []
gitCommitList := []GitCommit{}
json.Unmarshal([]byte(logOut), &gitCommitList)
return gitCommitList, nil
}
--date=iso-strict
makes sure that the dates that are outputted are parsable by Go.
Hopefully if you find a reason to need git log
in Go this might help :)