Search code examples
gitdvcs

Show all commits whose diff contain specific string


As the title says, I want to find every commit whose diff contains specific string.

At the moment, I use

git log -p 'filename'

Which shows less like interface of every diff, where I search for the string. Then I backtrace to find the actual commit msg.

Simple alternative might be to pipe git log -p into grep, but I can not find the commit id or message that way.


Solution

  • Here's a one-liner shell script (split into more than one line for formatting purposes) that extracts the rev-numbers of current-branch-reachable commits affecting path where git show -p contains the given pattern. It's not perfect (it will match commit messages as well as diffs) but it should be easy to tweak however you like, from here.

    git rev-list HEAD -- path |
    while read rev; do
        if git show -p $rev | grep pattern >/dev/null; then
            echo $rev
        fi
    done
    

    Note that you can replace git show with, e.g., git diff $rev^ $rev (note that this only compares against first-parent if it's a merge), or git whatchanged $rev, or whatever you like. The main trick is to start with git rev-list to extract all the candidates (commits affecting the given path; omit the -- path part to get all commits starting from HEAD). See git-rev-list(1) for lots of other things you can do with git rev-list.