I want to write a script which is similar to git log -G
with go-git
This code prints all commits of the repos, but how to get the added/removed lines of each commit?
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("too few arguments. Please specify a directory containing git repos.")
os.Exit(1)
}
err := SearchLog(os.Args[1])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func SearchLog(dir string) error {
files, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, f := range files {
if f.IsDir() {
path := filepath.Join(dir, f.Name())
r, err := git.PlainOpen(path)
if err != nil {
fmt.Printf("%s %v", f.Name(), err)
continue
}
err = searchLogInRepo(r)
if err != nil {
return err
}
}
}
return nil
}
func searchLogInRepo(r *git.Repository) error {
options := git.LogOptions{}
cIter, err := r.Log(&options)
if err != nil {
return err
}
err = cIter.ForEach(func(c *object.Commit) error {
fmt.Println(c)
return nil
})
return err
}
how to get the added/removed lines of each commit?
A git log -G <regex>
alone would not show the commit content .
Only a, for instance, git log -p -G would.
And you would need to grep for your searched expression, in order to isolate the differences whose patch text contains added/removed lines that match <regex>
.
For each commit, you would need to get the patch from its parent commit (as in plumbing/object/commit_test.go
, and look for your regex.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.