Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the Git commit that introduced a string in any branch?

Tags:

git

search

I want to be able to find a certain string which was introduced in any commit in any branch, how can I do that? I found something (that I modified for Win32), but git whatchanged doesn't seem to be looking into the different branches (ignore the py3k chunk, it's just a msys/win line feed fix)

git whatchanged -- <file> | \ grep "^commit " | \ python -c "exec(\"import sys,msvcrt,os\nmsvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\nfor l in sys.stdin: print(l.split()[1])\")" | \ xargs -i% git show origin % -- <file> 

It doesn't really matter if your solution is slow.

like image 274
Jonas Byström Avatar asked Apr 28 '11 08:04

Jonas Byström


1 Answers

You can do:

git log -S <whatever> --source --all 

To find all commits that added or removed the fixed string whatever. The --all parameter means to start from every branch and --source means to show which of those branches led to finding that commit. It's often useful to add -p to show the patches that each of those commits would introduce as well.

Versions of git since 1.7.4 also have a similar -G option, which takes a regular expression. This actually has different (and rather more obvious) semantics, explained in this blog post from Junio Hamano.

As thameera points out in the comments, you need to put quotes around the search term if it contains spaces or other special characters, for example:

git log -S 'hello world' --source --all git log -S "dude, where's my car?" --source --all 

Here's an example using -G to find occurrences of function foo() {:

git log -G "^(\s)*function foo[(][)](\s)*{$" --source --all 
like image 181
Mark Longair Avatar answered Sep 19 '22 11:09

Mark Longair