4

I added some lines of code to a repo and commited it. Then number of commits later those lines have been removed.

I have the commit hash when the lines where added and the hash of a subsequent commit that has them removed. How can I find the exact commit where they were removed?

nickponline
  • 25,354
  • 32
  • 99
  • 167
  • Possible duplicate of [How to grep git commits for a certain word](http://stackoverflow.com/questions/1337320/how-to-grep-git-commits-for-a-certain-word) –  Jun 12 '14 at 21:11
  • Related: [git: finding a commit that introduced a string](http://stackoverflow.com/q/5816134/456814). –  Jun 12 '14 at 21:12

2 Answers2

5

You can use the -S or -G options to git log. The difference between them is that -S takes a fixed string (representing the line of code that you want to match), while -G does the same thing, but takes a regex:

git log --oneline -S 'fixed string'
git log --oneline -G '^foobar$'

The -S and -G option will return commits that either first introduce or remove the string/regex pattern. You can even add the --patch or -p option if you want to see the diffs with the commit matches.

Documentation

From the official Linux Kernel git log documentation:

-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.

-G <regex>

Look for differences whose added or removed line matches the given <regex>.

  • Difference between -G and -S is more subtle than this: -S won't find the commit with the number of occurrences of 'pattern' unchanged. In other words if e.g. 'pattern' was moved from one function call to another - it won't find it. Considering -G also does regexp by default I'm choosing it as my favorite. – Ev Dolzhenko May 18 '23 at 15:12
2

You may want to take a look at git-blameall. It shows every line that ever existed in a file and includes the commit that deleted a line. It's been useful for this sort of forensics.

John Szakmeister
  • 44,691
  • 9
  • 89
  • 79
  • Let's start over. How is `blameall` advantageous over http://stackoverflow.com/a/24193859/832230 ? – Asclepius Aug 12 '14 at 23:42
  • @A-B-B I'm not trying to advocate my answer. I genuinely want to know whether or not it deals with false positive any better. I suspect it doesn't, which is why I asked. And it appears that you deleted your comments regarding it, which is unfortunate--it's a helpful conversation to have. FWIW, I like blameall, because it puts what I want center screen, and where I can see what happened to the line over time. Yes, you have to deal with code motion and what not, but in general it shows the changes pretty well. It's organization could be improved, but it's handy. – John Szakmeister Aug 12 '14 at 23:47