Ali
Ali

Reputation: 267049

How to get the hash of the commit in which a deleted line was added?

When doing git diff, the old line and now line are shown next to each other, e.g:

-    @principal.connections.joins(:contact_infos)
+    @principal.connections.joins(:node)

Is there any command, or parameter, which will cause git to print the hash of the commit in which the deleted line was added?

For example, if the line @principal.connections.joins(:contact_infos) was added in the commit foo1234 and changed to @principal.connections.joins(:node) in the commit bar1234, then is there a way to get:

- foo1234   @principal.connections.joins(:contact_infos)
+    @principal.connections.joins(:node)

When doing git diff, or another command which will give a list of deleted lines and the hash in which they were added?

Closest I came was git blame but that only gives hashes for lines which are currently in the file, not ones which were modified / deleted

Upvotes: 2

Views: 55

Answers (1)

CB Bailey
CB Bailey

Reputation: 791361

You can git blame the old version of a file, typically I use a parent commit reference. E.g.:

$ git blame git-mergetool.sh
f8750a0e (Junio C Hamano   2012-08-22 22:33:15 -0700 356)       if test "$merge_keep_backup" = "true"
f8750a0e (Junio C Hamano   2012-08-22 22:33:15 -0700 357)       then
f8750a0e (Junio C Hamano   2012-08-22 22:33:15 -0700 358)               mv -- "$BACKUP" "$MERGED.orig"
f8750a0e (Junio C Hamano   2012-08-22 22:33:15 -0700 359)       else
f8750a0e (Junio C Hamano   2012-08-22 22:33:15 -0700 360)               rm -- "$BACKUP"
f8750a0e (Junio C Hamano   2012-08-22 22:33:15 -0700 361)       fi

Then if you use git show and discover that f8750a0e was all style fixes you might want to blame the previous version with something like:

$ git blame f8750a0e^ git-mergetool.sh
44c36d1c (Charles Bailey   2008-02-21 23:30:02 +0000 276)     if test "$merge_keep_backup" = "true"; then
b3ea27e4 (Charles Bailey   2008-02-21 23:30:34 +0000 277)       mv -- "$BACKUP" "$MERGED.orig"
44c36d1c (Charles Bailey   2008-02-21 23:30:02 +0000 278)     else
44c36d1c (Charles Bailey   2008-02-21 23:30:02 +0000 279)       rm -- "$BACKUP"
44c36d1c (Charles Bailey   2008-02-21 23:30:02 +0000 280)     fi

So in your case you can use git blame bar1234^ file and the line you care about should be labelled with foo1234. Note that as in my example you may find the lines have moved around a lot between the current version, the version where the line was last changed and that commit's immediate parent.

Upvotes: 2

Related Questions