Alex I
Alex I

Reputation: 20317

How to find file revision or commit from git repository by a file 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)

Upvotes: 8

Views: 1030

Answers (2)

VonC
VonC

Reputation: 1328712

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:

Upvotes: 3

Beni Cherniavsky-Paskin
Beni Cherniavsky-Paskin

Reputation: 10039

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...

Upvotes: 1

Related Questions