git tip of the day
August 2, 2012
So I just wanted to give a quick git tip, since I see people give them occasionally and I find those posts useful for me.
It’s often important to try find a commit where something was introduced originally. This is good for figuring out what commit to squash to fix up to, or for doing code archaeology to figure out context beside why a certain piece of code exists. I see a lot of people use git log –grep or git log -S. Those commands are nice and there is nothing wrong with them. I don’t usually like using them, though. I prefer:
git log -p
This will show you every commit message and patch in reverse chronological order paged through less. less has powerful search features built in. So you can for instance type:
/^\+.*my_function
to search for the last instance of when my_function was added in the code. If you hit "n"
it will jump to the next to last instance, and so on. If you decide you want to seek backward over an entry you already went past you can do "?"
and then "n"
repeatedly. "/"
to seek forward again.
Why do I like this better?
- Because it’s interactive and more flexible. You can switch search terms mid-stream (tell me when
bar()
was called, but only beforefoo()
was implemented in history) - Because it lets you see the surrounding commits. Seeing a commit in isolation is useful, but being able to see the commits that went in along side it is often invaluable for gleaning context into the motivation behind the commit.
Okay one more quickie: Another option that’s useful to throw before the "-p"
in "git log -p"
is "-U30"
. This amps up the amount of diff context surrounding the changes introduced in a patch, often making those changes imminently more clear. It’s no fun to see a patch that modifies the middle part of a function, and not being able to see what the function does.
So that’s my git tip.
August 2, 2012 at 11:19 am
I like more
git log -p -Sstring
or
git log -p -Gregex
because it only search on added or removed lines, so you can skip changes that are around what you are looking for. But it is true that sometimes searching with less is easier, I do it when I expect to try many searches
August 9, 2012 at 6:03 pm
You can limit your search queries to only show added and removed lines with less as well by prepending your search with
/^[+-].*search query here
This line noise is a regex that requires the matches in the diff output start with – or +
August 3, 2012 at 11:27 am
Instead of -U30 there is also –function-context (-W in short).
August 3, 2012 at 1:09 pm
Nice!
August 9, 2012 at 11:58 am
Is there an easy way to make it ignore matches in translations? I find that makes it much less useful to me than it could be.
August 9, 2012 at 5:58 pm
if you have a tree like:
configure.ac
Makefile.am
src/
po/
then you can do
git log –relative=src/ -p
to only show diffs under src