8

Similar to How to link to specific line number on github I'd like to link to a line of code on github. The difference is that I want to link to a line in the diff viewer. See for example this link:

https://github.com/git/git/commit/5bdb7a78adf2a2656a1915e6fa656aecb45c1fc3/#diff-fea9abc098557219301972e6c6782b8fL9

In addition to the commit hash (5bdb7a78...) there is a second hex string in the url anchor (#diff-fea9abc0...) that seems to specify the file being changed.

I'd like to be able to generate these links without first visiting github and clicking on the line. How is the second hex string (#diff-fea9abc0...) generated?

Community
  • 1
  • 1
user12341234
  • 6,573
  • 6
  • 23
  • 48

1 Answers1

9

The anchor hash is reference to the filename being linked to. In the question above, the linked line is pointing to line 9 (on the left hand side) of the file contrib/hooks/multimail/README.Git. To generate the hash for that file, simply MD5 hash it:

% md5 -s contrib/hooks/multimail/README.Git
MD5 ("contrib/hooks/multimail/README.Git") = fea9abc098557219301972e6c6782b8f

Then append L or R depending whether you’d like to reference the left (original) or right (changed) side in the patch, and append the line number:

               MD5 (filename)          Line number
      /------------------------------\ v
#diff-fea9abc098557219301972e6c6782b8fL9
                                      ^
                                    L or R
user12341234
  • 6,573
  • 6
  • 23
  • 48
  • 2
    Note that this does not seem to work for large diffs that are collapsed, even if you put the line number at the end of it, Github will not "jump" to the line you specified when you click the link, it will just take you to the top of the commit diff. Bitbucket supports this functionality but it doesn't seem like Github does. – jrh Nov 25 '20 at 14:19
  • 2
    Note: It seems like Github has updated the hash algorithm from MD5 to SHA256. – Parker May 02 '21 at 16:54
  • @Parker did you manage to get a working anchor link using SHA256? I tried here but got a different one: https://github.com/apache/zookeeper/compare/0287c9572...4d8caf985#diff-b810ebe4ffda4293c79d292059b45b59de7e649e86314ffd5a1ee4eb4b1e08c8 `echo 'NOTICE.txt' | sha256sum` -> `aef6d783bb8a08be73f134b53752e8ea2fc797e964262c30315d980ea0b3dbb9` – Juraj Martinka Aug 10 '21 at 07:16
  • 2
    @JurajMartinka Yes! The issue you're running into is that `echo` includes a trailing newline by default, so you're actually getting the hash of "NOTICE.txt\n". You can use the `-n` option to avoid that: `echo -n 'NOTICE.txt' | sha256sum` -> `b810ebe4ffda4293c79d292059b45b59de7e649e86314ffd5a1ee4eb4b1e08c8 -` – Parker Aug 11 '21 at 13:20