Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

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.

like image 868
Pumpkin Avatar asked Aug 17 '12 11:08

Pumpkin


People also ask

How can we locate a particular git commit?

Finding a Git commit when given a file size So we use git rev-list to generate a list of all the commits (by default, these are output from newest to oldest). Then we pass each commit to the ls-tree command, and use grep to see if that number appears anywhere in the output.

What git command do you need to use to know who changed certain lines in a specific file?

The git blame command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.

Does git blame identify a particular commit?

The git blame command is used to know who/which commit is responsible for the latest changes made to a file. The author/commit of each line can also been seen. There are many other options for blame, but generally these could help.

How do you view the commit history of a cloned repository?

After you have created several commits, or if you have cloned a repository with an existing commit history, you'll probably want to look back to see what has happened. The most basic and powerful tool to do this is the git log command.


2 Answers

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>]
like image 147
Christopher Avatar answered Nov 15 '22 09:11

Christopher


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.

like image 22
Willem Mulder Avatar answered Nov 15 '22 08:11

Willem Mulder