Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'git cat-file -p <sha1>': "fatal: Not a valid object name" on random objects from .git/objects

Tags:

git

I want to learn more about the inner workings of git so I ran these commands:

cd .git/objects/62

ls
00cb2f01089db22aca24675272a16712e89747
0ee798881329430bfef6c558be7b14c1f0676f
1087f408e2f2bd782d53a1211a7418fee4f6a7
a6a71f3bd5a3af882f3f0ec4fad4c672055746
f95e69f344b52c5038d922260189475626e69a

git cat-file -p 00cb2f01089db22aca24675272a16712e89747

and got the following error:

fatal: Not a valid object name 00cb2f01089db22aca24675272a16712e89747

Why did I get it?

I tried like 10 times (for different files from different directories inside .git/objects) and got the same error.

How can I view the actual content of the files (be it a blob, tree or commit)?

like image 218
Igor Popov Avatar asked Nov 16 '11 10:11

Igor Popov


4 Answers

You don't have to cd into the .git object store, but you have to provide enough of the full sha1 hash for Git to uniquely identify the object.

Usually the first 6 or 7 digits are sufficient. Git matches the object IDs starting from the front, so entering any substring, such as the last several digits, will fail (or match to a different object than you intended).

git cat-file -p 621087f408e2f2bd782d53a1211a7418fee4f6a7

Git stores its objects in .git/objects, distributed across 256 folders to keep the size of the directory down. The first two characters of each hash are used as directory name, the remaining 38 chars are used as filename.

like image 69
knittl Avatar answered Nov 17 '22 09:11

knittl


Thanks to @knittl for a great answer.

You can get build all of the objects with this bash script.

cd .git/objects; 
for d in * ; do (
  cd "$d"; 
  for p in * ; do ( echo "$d$p";); done 
); done

Or you can get a run cat -p on everything!

cd .git/objects; 
for d in * ; do (
  cd "$d"; 
  for p in * ; do ( 
    echo "$d$p";
    git cat-file -p $d$p
  ); done 
); done
like image 3
Michael Dimmitt Avatar answered Nov 17 '22 09:11

Michael Dimmitt


  1. SHA1's are 40 characters and 00cb2f01089db22aca24675272a16712e89747 is only 38 characters which leads me to number 2.
  2. I only know this because just like you, I spent the last 20 min banging my head on the wall doing the same thing you did which was drop the 2 character prefix at the start off the SHA. Check the photo for details. walkthrough

Also, as a caveat, brew install tree if you can to get a better look at the SHA.

like image 2
Dom Hallan Avatar answered Nov 17 '22 10:11

Dom Hallan


I would like to clarify a little the answer provided by @Knittl

Git store "hashed objects" into "objects" folder, but the way they store it is clever:

folder_name + file_name = hash_code

the command cat-file takes that hash code not the file_name stored into object folder, so is not necessary to be into that folder as well

like image 1
Adel Balbisi Avatar answered Nov 17 '22 10:11

Adel Balbisi