How to find out in which commit a particular code was added?

GitGit Commit

Git Problem Overview


I want to find out in which commit did I add the code given below:

if (getListView().getChildCount() == 0)
    			getActivity().findViewById(android.R.id.empty).setVisibility(View.VISIBLE);

How do I achieve this?

Git Solutions


Solution 1 - Git

git log -S searchTerm

gives you the commits in which the search term was introduced.

Solution 2 - Git

Run git blame on the file. It'll show you the commit ID, the date and time, and who committed it- for each line. Then just copy out the commit identifier and you can use it in git log <commit> or git show <commit>.

For example, I've got a file, called test.txt, with lines added on different commits:

$ cat test.txt
First line.
Second line.

Running the git blame:

$ git blame test.txt
^410c3dd (Leigh 2013-11-09 12:00:00 1) First line.
2365eb7d (Leigh 2013-11-09 12:00:10 2) Second line.

The first bit is the commit ID, then name, then date, time, time zone, and finally the line number and line contents.

Solution 3 - Git

There is something quicker than issuing a blame on the full file. If the line is ${lineno} and the file is ${filename} you can:

git blame -L ${lineno},${lineno} ${filename}

Example:

git blame -L 2,2 test.txt

Solution 4 - Git

git log -S "mention here line of code" [file-path]    

For example:

git log -S "First line" test.txt         

Providing the file name with its path is obvious because, most of the time, we want to know who introduced a particular code segment in a particular file.

Solution 5 - Git

If code is being maintained in Git repository and intellij IDE along with Git plugin is being used to browse the code then i have found the following way very intuitive:

  1. Open the file in intellij
  2. Go to context menu -> Git -> Annotate.
  3. New window will appear where each line in new window tells who made that line commit.

Following screenshots are for the references:

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarshal KshatriyaView Question on Stackoverflow
Solution 1 - GitRahil AhmadView Answer on Stackoverflow
Solution 2 - GitLeighView Answer on Stackoverflow
Solution 3 - GitcforbishView Answer on Stackoverflow
Solution 4 - GitAnshul SinghalView Answer on Stackoverflow
Solution 5 - GitAnshul SinghalView Answer on Stackoverflow