Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 518
sh1 Avatar asked Oct 23 '25 07:10

sh1


1 Answers

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
like image 110
Vser Avatar answered Oct 25 '25 09:10

Vser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!