Home > database >  Is there a way to tell git to give me the commit which moved a line in a file?
Is there a way to tell git to give me the commit which moved a line in a file?

Time:05-18

I have a log that shows a stack trace. Each line in the stack trace shows the function called, filename and line number.

Thing is, is that these don't align with the build that it's supposed to be. So, I need to know when the function was moved from the current location to the location in the past.

E.g.

System.NullReferenceException: Object reference not set to an instance of an object.
at ns1.ns2.cn.fn2(t1 p1, t2 p2) in c:\path\file2.cs:line 456
at ns1.ns2.cn.fn1(t1 p1, t2 p2) in c:\path\file1.cs:line 123
...

In this case, in the past, ns1.ns2.cn.fn1(t1 p1, t2 p2) was called which called another function ns1.ns2.cn.fn2(t1 p1, t2 p2) in file c:\path\file1.cs on line 123.

However, currently, that line is on line 223, which is 100 lines lower.

Is there a way to tell git to tell me when lines were added prior to 223 which moved it down 100 lines?

CodePudding user response:

The fastest way I figured out was to make a script to look at all of the different versions of the file:

$  export file="path_from_repo_root/file1.cs";\
git log --pretty=short -u -L 1,99999999:"$file"|perl -e '
use warnings;
use strict;
my ($linesAdded, $linesDeleted) = (0, 0);
while (<>) {
 if (/^commit ([a-f0-9] )/ and !eof()) {
   my $linesDiff = ($linesAdded - $linesDeleted);
   print;  # prints commit hash
   if ($linesDiff) {
     system("git show $1:$ENV{file} | grep -n --color=always fn2");
   }
   ($linesAdded, $linesDeleted) = (0, 0);
 } elsif (/^-/ ) {
     $linesDeleted;
 } elsif (/^\ /) {
     $linesAdded;
 }
}' | less -R

Which will spit out all of the commit hashes to the file and the location of the function in the file if the number of lines in the file have changed.

Note that this isn't a perfect solution, but it was good enough to find what I needed. Also, 99999999 could have been changed to a the line where the function currently resides (I think), but I wasn't sure, so I just basically said to look at the entire file.

  •  Tags:  
  • git
  • Related