Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git - finding a filename from a SHA1

Tags:

git

sha1

I added a file to the index with:

git add somefile.txt 

I then got the SHA1 for this file with:

git hash-object somefile.txt 

I now have a SHA1 and I would like to retrieve the filename of the object in the index using the SHA1.

git show 5a5bf28dcd7944991944cc5076c7525439830122 

This command returns the file contents but not the name of the file.

How do I get the full filename and path back from the SHA1?

like image 523
git-noob Avatar asked Jan 20 '09 07:01

git-noob


People also ask

How do I get the path of a file in Git?

While browsing your Git repository, start typing in the path control box to search for the file or folder you are looking for. The interface lists the results starting from your current folder followed by matching items from across the repo.

Which objects in Git have a SHA1 hash?

Since trees and blobs, like all other objects, are named by the SHA1 hash of their contents, two trees have the same SHA1 name if and only if their contents (including, recursively, the contents of all subdirectories) are identical.

What is SHA1 in git?

The SHA-1 name of an object is the SHA-1 of the concatenation of its type, length, a nul byte, and the object's SHA-1 content. This is the traditional <sha1> used in Git to name objects. The SHA-256 name of an object is the SHA-256 of the concatenation of its type, length, a nul byte, and the object's SHA-256 content.

How do I see the contents of a file in Git?

The Git Show command allows us to view files as they existed in a previous state. The version can be a commit ID, tag, or even a branch name. The file must be the path to a file. For example, the following would output a contents of a file named internal/example/module.go file from a tagged commit called “release-23”.


2 Answers

There's no such direct mapping in git as the name of the file is part of the tree object that contains the file, not of the blob object that is the file's contents.

It's not a usual operation to want to retrieve a file name from a SHA1 hash so perhaps you could expand on a real world use case for it?

If you're looking at current files (i.e. the HEAD commit) you can try the following.

git ls-tree -r HEAD | grep <SHA1> 

If you want to find the contents in previous commits you'll need to do something more like this.

git rev-list <commit-list> | \ xargs -n1 -iX sh -c "git ls-tree -r X | grep <SHA1> && echo X" 
like image 109
CB Bailey Avatar answered Oct 04 '22 11:10

CB Bailey


Great one-liner to do this:

git rev-list --objects --all | grep <blob sha1> 
like image 28
brandonscript Avatar answered Oct 04 '22 11:10

brandonscript