Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find file revision or commit from git repository by a file hash?

Tags:

git

hash

I have a git diff output that contains lines like this: index 0056c73..92c6cbd 100644 for each file. I know which repository it comes from, but unfortunately have no idea which revision of the repository it is diffing against.

How do I find the commit of the repository that the diff is against?

Alternately, how do I find the exact commit of each file that the pre-image hashes in the diff correspond to? (i.e. which version of a file has the 0056c73 hash in the example above)

like image 790
Alex I Avatar asked Jul 30 '16 19:07

Alex I


2 Answers

If you know the path of the file, you can start displaying all the commits for said path:

git log --all --pretty=format:%H <path>

If 0056c73 is a blob SHA1 for that file, a git ls-tree will print all entries SHA1, and you can grep the one you are after.

"Which commit has this blob?" proposes this one-liner from aragaer:

git log --all --pretty=format:%H <path> | xargs -n1 -I% sh -c "git ls-tree % <path> | grep -q <hash> && echo %"

(replace <hash> with 0056c73)

As I mentioned in "Which commit has this blob?", with Git 2.16+ (Dec. 2017), you can use:

  • git describe
  • git log --oneline --find-object(=...)
like image 136
VonC Avatar answered Oct 30 '22 00:10

VonC


As elaborated in https://stackoverflow.com/a/48027778/239657, since Git 2.16 (Q1 2018), you can simply run git describe 0056c73. Example on another repo:

$ git show d69fe27cf937398fa2bf6813674a3975bfe56e89 | grep e1cfe5
index 6e180f8221..e1cfe56bf6 100755
$ git describe e1cfe56bf6
1.1.0.Beta2-7645-gd69fe27cf9:adapters/oidc/js/src/main/resources/keycloak.js
$ git describe e1cfe56bf6 --abbrev=40
1.1.0.Beta2-7645-gd69fe27cf937398fa2bf6813674a3975bfe56e89:adapters/oidc/js/src/main/resources/keycloak.js

You can play with git describe flags to tweak the friendly lookup of close tags vs just showing the commit hash...

like image 33
Beni Cherniavsky-Paskin Avatar answered Oct 29 '22 23:10

Beni Cherniavsky-Paskin