Search code examples
gitgit-loggit-blame

Find who & when deleted a line in a function using GIT


I have some ruby code in a huge repo like this

def my_func params
  {
    :k1 => 1,
    :k2 => 2,
    :k3 => 3,
    :k4 => 4,
    :k5 => 5,
    :k6 => 6
  }
end

Somehow, few key-value pairs got deleted over time. I want to git blame who did this, But the key-value pair is so common that a grep would cause too many false-positives. So is there a way to view a function's change over all commits?

I tried something like git log -L /^\s+def my_func/,/^\s+def/ src/to/file.rb, didn't work. GUI tools like SourceTree has "Log this file", it only shows the diff, so I can not tell which function the change belongs to. I also searched stackoverflow and googled a bit, didn't find a universal way.


Solution

  • In that case you can perform a "reverse blame". You simply ask the "difference" from the "new" to the old file, so deletions become addtions and vice versa.

    git blame --reverse start..end file.ext
    

    Where start and end should be commit signatures.

    For each line, it will show the latest commit in which the line appeared. You can then derive the next commit to find out what happened.