How to get `git grep` to show `git blame`-like information

290 views Asked by At

I'd like to git grep in the usual way, but with something like the additional insight of git blame in the displayed results.

In some instances I probably would benefit from including the metadata in the search query (show only results written by Bob), and in others I'd rather just use my own human judgement. I guess I'm flexible with which way that goes.

1

There are 1 answers

1
Vser On

I added the following to my git aliases:

grame = "!r() { git grep -n $1 $2 | while IFS=: read i j k; do git blame -f -L $j,$j $i; done }; r"

Which I shamelessly stole and adapted from: https://gist.github.com/lonnen/3101795

I added the pathspec argument so it’s used as:

git grame <pattern> [<pathspec>...]

Note that git blame is called for each match. Since git blame can be quite long, if a file has several match, the repeated call can be quite costly. Better try something like:

grame1 = "!r() { git grep -noh $1 $2 | while IFS=: read line _; do echo -n \"-L ${line},${line} \"; done }; r"
grame2 = "!r() { git grep -l $1 $2 | while IFS=EOL read src; do git blame -f $(git grame1 $1 $src) $src; done }; r

but which still does 2 git grep call instead of one. Some awk/sed/perl invocation could format the first invocation of git grep as:

-L line,line -L line,line [as many -L as matches] file