git blame of particular lines inside all files filtered with grep command
Asked Answered
D

3

11

I know how to run gblame inside a file.

I know how to grep a content inside all files in a directory.

I'd like to see gblame of particular lines around that one that contains a content. Example:

$ blame -R "content" ./

I see a list of files. I want to gblame all of theme, and understand who has touched those lines of code.

Domicile answered 25/2, 2015 at 16:17 Comment(0)
K
23

You can do it with Perl:

git grep -n 'content' | perl -F':' -anpe '$_=`git blame -L$F[1],+1 $F[0]`'

and if you want to create a custom command you can add something like this to your gitconfig in the alias section:

gb = "!f() { git grep -n $1 | perl -F':' -anpe '$_=`git blame -L$F[1],+1 $F[0]`'; }; f"
Kautz answered 28/12, 2016 at 9:47 Comment(3)
For me, the first command did not display the file name. How can the command be extended to display the filename?Interact
@Interact You can use the -f / --show-name option for blame, which will show you file names, so the command would be: git blame -fL$F[1],+1 $F[0]Kautz
I ended up using git blame -lf $F[1],+1 $F[0] | | git name-rev --stdin --tags --always in order to see the closest release tag.Stoush
L
0

find files with needle, for each file blame, and for each blame output search needle

for file in `grep -lr needle *`; do  git blame $file |grep needle ; done

You can add context with -C

for file in `grep -lr needle *`; do  git blame $file |grep -C5 needle ; done
Lastditch answered 25/2, 2015 at 16:31 Comment(1)
In this context, git grep would be preferable.Transmigrate
H
0

I wrote this little script to accomplish git grep + blame:

#!/bin/bash

if [ "$1" = "" ] ; then
    echo "usage: $0 <term>" 1>&2
    exit 1
fi

for file in $(git grep $1 | cut -d ':' -f 1 | uniq) ; do
    echo $file ::
    git blame $file | grep $1
done 
Harmonics answered 27/4, 2017 at 17:52 Comment(1)
I modified this to be .bash_profile addable by kicking out the #!/bin/bash and just writing function ggb { your content } . works like a charm. nice! Thanks for sharing this.Cling

© 2022 - 2024 — McMap. All rights reserved.