November 29, 2020
I recently read a post about a way to search Git commit history for code, and I thought I’d summarise the post here. It’s mainly for my own reference, but others may find it useful.
The point is: git blame
is very coarse-grained, searches for a single line in one file, and only reports the most recent commit.
If you need more detailed results, Git has a ‘search’ feature:
git log -S 'code'
: find all commits with a snippet of codegit log -G 'regex'
: find all commits with a regular expression (also shows if a string moved in one file, which -S
doesn’t do)git log --grep 'text'
: find all commits with text in the commit message-p, --patch
: show the actual diff in the log--reverse
: show the oldest commit first (the one that introduced the snippet)To round off with an example, this is how I’d find the commit that introduced ‘expandtab’ into my dotfiles, excluding Newsboat cache, and showing the actual code:
git log --reverse -S 'expandtab' -p ':!newsboat/cache.db'