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 before foo() 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.

6 Responses to “git tip of the day”

  1. Robert Says:

    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

    • halfline Says:

      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 +

  2. swilmet Says:

    Instead of -U30 there is also –function-context (-W in short).

  3. Jon McCann Says:

    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.


Comments are closed.