How to search through the history code (Git)

Sometimes, You may want to know which commits touched a specific method or variable. This is also possible using git log. You can perform a search for a string, for example, or a variable or method, and git log will give you the commits, adding or deleting the string from the history. In this way, you can easily get the full commit context for the piece of code.

Again, we will use the JGit repository with the master branch pointing to d35f0ff:

Step 1 : We would like to find all the commits that have had changes made to the lines that contain the "isOutdated" method.

Step 2 : The -G option used with git log will look for differences in the patches that contain added or deleted lines that match the given string. However, these lines could also have been added or removed because of some other refactoring/renaming of a variable or method. There is another option that can be used with git log, namely -S, which will look through the difference in the patch text in a similar way to the -G option, but will only match commits where there is a change in the number of occurrences of the specified string—that is, a line added or removed, but not added and removed.

Step 3 : The search matches 8 commits, whereas the search with the -G option matches 11 commits. The difference is that the commit with the ID c9c57d34d is only found with the -G option in the first list. A closer look at this commit shows that the isOutdated string is only touched because of the renaming of another object, and this is why it is filtered away from the list of matching commits in the last list when using the -S option. We can see the content of the commit with the git show command, and use grep -C4 to limit the output to just the four lines before and after the search string: