Pumpkin
Pumpkin

Reputation: 2043

How can I find which commit introduced a specific line in git? Or is there a better alternative?

Imagine a class within a git project that has undergone 1000's of commits, re-visited over and over. Is there any chance for me to examine when exactly (at which commit) a specific line of code was introduced to the class ?

If not, is there an alternative to going towards each commit to find the set of lines that I have a particular interest in ?

Ty.

Upvotes: 5

Views: 847

Answers (2)

Christopher
Christopher

Reputation: 44314

A specific line of code? Like you know what the line is in advance? Sure it's possible. In fact it's stupid easy. Just use the pickaxe search option on git log:

-S<string>
    Look for differences that introduce or remove an instance of <string>. Note that this is different than the string simply appearing in diff output;
    see the pickaxe entry in gitdiffcore(7) for more details.

Suppose the class is public class Foo {, you could find every commit that touched that string with:

git log -S"public class Foo"

If you wanted to limit it to a particular file, just use the standard -- syntax:

git log -S"public class Foo" -- Foo.java

In general, use this:

git log -S<string> [-- <file>]

Upvotes: 12

Willem Mulder
Willem Mulder

Reputation: 14014

You can use git bisect to backtrack when certain code was introduced (see http://git-scm.com/book/en/Git-Tools-Debugging-with-Git) and could use this technique to check out the code each time and then see if the line is yet present. This makes the search O(log n) instead of O(n), which saves you a lot of time...

If you want to know when a line is last edited, you can use git blame.

Upvotes: 3

Related Questions