gitgit-log

How to search specified string which introduced by merge commit?


Is there a way to search for a specific string introduced from a merge commit?

git log -S won't work and git log -m -p | less is too slow.

To reproduce the the problem, given the setup:

git init -b a
touch init
git add init
git commit -m init
echo a > init
git commit -am a
git switch -c b HEAD~
echo b > init
git commit -am b
git merge a # this would fail due to conflict
echo ab > init
git commit -a --no-edit

The log would be like:

λ git log --graph --oneline
*   c65b4ce (HEAD -> b) Merge branch 'a' into b
|\  
| * 59d5818 (a) a
* | 0967c4b b
|/  
* 40fac69 init

As you can see, git log -S can find the corresponding commits with the search term a or b:

λ git log --oneline -S a
59d5818 a

λ git log --oneline -S b
0967c4b b

Expected

I expect git log -S can find the merge commit c65b4ce by the term ab:

λ git log --oneline -S ab
c65b4ce Merge branch 'a' into b

Actual

However, it prints nothing:

λ git log --oneline -S ab
# prints nothing

Solution

  • For merge commits, you need to specify --diff-merges=<format>.

    git log --oneline -S ab --diff-merges=on  # -m for short
    git log --oneline -S ab --diff-merges=c  # -c for short
    git log --oneline -S ab --diff-merges=cc  # --cc for short
    

    As to the differences between these formats, refer to the manual. Some of them also display the diff of merge commits in git log.