Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find git commits related to a certain part of a file

Tags:

git

Case
Quite often I find myself staring at some old code that doesn't look right. It looks like something has been removed (e.g. it has a loop that does nothing of value, or it creates a variable but doesn't use it), or something is just hard to understand the point of. In these cases I would really need to see the history of that section of the file. Not all of the file though, just that section, or function.

Ideal solution
A simple command like

git log books.cpp:10

to find history of line 10 (possibly with surroundings) of file books.cpp is probably too much magic to ask for, but do you have ideas of how to work out that history?

What I have tried
I have tried using blame, and then checking out the commit before the given commit of that line - repeating it until I've seen enough. But that is very tedious work.

Have you felt the need for this feature? Do you have a way of achieving it? Share your experience!

like image 663
Joel Avatar asked Mar 03 '11 08:03

Joel


People also ask

How do I see commits in a specific file?

Use git log --all <filename> to view the commits influencing <filename> in all branches.

How can we locate a particular git commit?

Finding a Git commit when given a file size So we use git rev-list to generate a list of all the commits (by default, these are output from newest to oldest). Then we pass each commit to the ls-tree command, and use grep to see if that number appears anywhere in the output.

How do I blame a specific line in git?

Blaming only a limited line range Sometimes, You don't need to blame the entire file, you just need to blame in a limited line range. Git blame provides the option for that. -L will take the option for the start line and for the end line. The above command will blame from line 80 through line 100.


1 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 call it like this:

git linehistory books.cpp 5,15

It will show you what lines 5 to 15 look like at each commit for that file.

like image 129
Peter Farmer Avatar answered Nov 09 '22 21:11

Peter Farmer