calvin
calvin

Reputation: 2955

Get the history of a line which could be moved across different files with git?

I find a line Footer is saved at the end of the file, with fixed length in fileA, and I want to know at which commit this line was added. Then I use

git log -L 51,51:.../FileFormat.h

And it turns out the FileFormat.h was recently created, and then the line was moved to this file in commitA.

So I have to checkout to the commitA, re-locate the line which is in fileB, and find the line again with git log.

I wonder if there is a super git log -L that once specify the line, it could find its history even if it has been moved from file to file.

Upvotes: 0

Views: 50

Answers (2)

dani-vta
dani-vta

Reputation: 7180

You could use git log with the -G option to look for differences whose patch text contains added/removed lines that match the given regex. In your case, the regex would simply be the line you're looking for. If you also add the -p option, the command outputs the commit's changes, showing if the line was added or removed from a file.

git log -p -G "Footer is saved at the end of the file, with fixed length"

Upvotes: 2

hlovdal
hlovdal

Reputation: 28258

Gitk is awsome for many other reasons as well, but this use case is one where it really shines with its "Show origin of this line" support.

For this example I created a file with ten lines and then renamed the file a couple of times.

Screenshot 1

Exercise goal is to find the origin of the fifth line from the latest commit on main. Since the fifth line is not shown in the default diff view ("Patch") we need to change to "Tree" and then click on the relevant file to show its content in the lower left pane. Inside this view right click on the line you are interested in and select the "Show origin of this line" menu option.

Screenshot 2

Whith that gitk jumps back to the commit where the line was last changed/added (even across an additional rename in this example):

Screenshot 3

Upvotes: 2

Related Questions