Find git commits associated with a specific part of a file

Case
Quite often, I look at old code that doesn't look right. It seems that something has been deleted (for example, it has a loop that does nothing for the value, or creates a variable but does not use it), or something is simply hard to understand. In these cases, I really would need to look at the history of this section of the file. Not all files, though, only this section or function.

The perfect solution
A simple command like

git log books.cpp:10 

to find the history of line 10 (possibly with the surroundings) of the books.cpp file, maybe too much magic to ask, but do you have any ideas on how to work out this story?

What i tried
I tried using fault, and then I check the commit before the given commit of this line - repeating it until I see enough. But this is a very tiring job.

Did you feel the need for this feature? Do you have a way to achieve this? Share your experience!

+8
git
source share
2 answers

Git is very easy to extend. Does something like this achieve what you want?

 #!/bin/bash FILENAME=$1 LINENUMBERS=$2 for hash in `git log --pretty=format:%h ${FILENAME}` do echo "***************** Showing ${FILENAME} at ${hash}" git blame -L ${LINENUMBERS} ${hash} ${FILENAME} done 

Put this little script in your path as something like git-linehistory and name it like this:

 git linehistory books.cpp 5,15 

It will show you which lines 5 through 15 look like with each commit for this file.

+4
source share
  • Option
  • git blame -L allows you to specify a range of the output string or even a regular expression to match the required function.
  • You can also indicate blame for a specific commit, then you do not need to check the revision to blame.

In short, you can make sequential calls to git blame -L range <commit> <file-name> to view the history of line-by-line changes.

+2
source share

All Articles