Sub topic 13
Loose Objects and Packfiles
This chapter assumes you have followed the earlier chapters. You should know what a blob, tree and commit are, and you should be comfortable with git hash-object and git cat-file. You also need a Unix-style shell and Python 3 for one small script. Here you will learn the two ways Git stores objects on disk, how to inspect both, and what git gc changes.
Two storage formats, one object model
Every object you have created so far began as a loose object. A loose object is one file in .git/objects, holding one object. Git can also store thousands of objects together in a packfile, which is a single archive with a separate index file.
The two formats are invisible to most commands. git cat-file -p <id> returns the same output whether the object is loose or packed. The object ID is the hash of the object's content, so it does not depend on where the bytes are stored. Moving an object into a pack never changes its name.
Loose objects
A loose object lives at .git/objects/<first two hex digits>/<remaining 38 digits>. The blob for hello followed by a newline has ID ce013625030ba8dba906f756967f9e9ca394464a, so its file is .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a.
The file is not plain text. It is the zlib compression of a header, a NUL byte, and the content:
<type> <size>\0<content>The header holds the type (blob, tree, commit or tag) and the content length in bytes. The object ID is the SHA-1 hash of this uncompressed header plus content, not of the content alone. That is why two objects of different types never share an ID, even if their bytes are the same.
This script decompresses a loose object and prints the header and body:
import sys
import zlib
path = sys.argv[1]
with open(path, "rb") as f:
data = zlib.decompress(f.read())
header, _, body = data.partition(b"\0")
print("header:", header.decode())
print("body:", body)Save it as show_loose.py and run python3 show_loose.py .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a. You should see header: blob 6 and body: b'hello\n'. For trees, the body is binary, because each entry stores the child's hash as 20 raw bytes instead of 40 hex characters.
Loose storage has two weaknesses:
- Each object is compressed on its own, so Git cannot take advantage of similarity between two versions of the same file.
- Each object takes a whole filesystem block, so thousands of tiny objects waste disk space and make directory scans slow.
Packfiles
A packfile stores many objects in one file, and most of them are compressed against each other. Packs live in .git/objects/pack/ as a pair:
| File | Contents |
|---|---|
| `pack-<name>.pack` | A `PACK` header with a version and object count, the object entries, and a trailing checksum |
| `pack-<name>.idx` | A sorted table of object IDs with a CRC32 and an offset into the `.pack` file for each |
The index lets Git find an object by binary search without reading the whole pack. Each entry in the .pack file records the object type and size, followed by zlib-compressed data.
Deltas
A packed entry can be a full object, or it can be a delta. A delta is a set of instructions that rebuilds the object from a base object, such as "copy bytes 0 to 8800 from the base, then insert these new bytes". Two versions of a large file that differ by one line become one full copy plus a tiny delta.
Delta chains are possible. Object C can be a delta against B, which is a delta against A. The chain length is called the depth, and Git limits it (50 by default for git repack) so that reading an object does not require applying too many deltas. Deltas apply across object types in principle, but in practice Git mostly deltifies blobs and trees.
Git does not always store the older version as the base. It tends to keep the most recent version in full, because recent versions are read most often, and stores older versions as deltas against it.
Watching git gc pack objects
Run this in the demo repository from the earlier chapters:
git count-objects -v
git gc
git count-objects -v
git verify-pack -v .git/objects/pack/pack-*.idx
git fsck --unreachableThe count-objects -v fields to watch are:
count: the number of loose objects.in-pack: the number of objects stored in packs.packs: the number of packfiles.sizeandsize-pack: the disk use of each, in KiB.
Before gc you should see a nonzero count and in-pack: 0. After gc, count should be 0 and in-pack should equal the number of reachable objects. That is seven if you followed this tutorial exactly: two commits, two trees, two blobs and the annotated tag.
git verify-pack -v prints one line for each packed object, in the form <id> <type> <size> <size-in-pack> <offset>. Deltified entries add a depth and a base ID. It ends with a statistics block and pack-....pack: ok. In a seven-object repository the objects are too small and unrelated for deltas, so every entry is a full object.
git gc also runs git pack-refs. After it, .git/refs/heads/main may no longer exist as a file. The ref moves into .git/packed-refs, and Git consults both places when resolving a name.
Seeing a delta
To see a delta, you need two similar versions of a larger file. This sequence builds that case with porcelain commands. It needs user.name and user.email set.
git init delta-demo
cd delta-demo
seq 1 2000 > numbers.txt
git add numbers.txt
git commit -m "numbers"
echo 2001 >> numbers.txt
git commit -am "append one line"
git gc
git verify-pack -v .git/objects/pack/pack-*.idx | grep blobYou should see two blob lines. One has a size near 8,900 bytes and a similar size in the pack. The other has the same original size but a size-in-pack of only a few bytes, followed by a depth of 1 and the ID of the base blob. The second entry is the delta. git cat-file -p still returns the full text of both versions, because Git resolves the delta for you.
Useful commands for either format
These commands treat loose and packed objects the same way:
git count-objects -vH
git cat-file --batch-all-objects \
--batch-check='%(objectname) %(objecttype) %(objectsize) %(objectsize:disk)'The %(objectsize:disk) field is the on-disk size, so a deltified blob shows a far smaller value than its %(objectsize).
Other commands that change the layout:
git repack -a -dcombines everything into one new pack and deletes the old packs.git prune-packeddeletes loose objects whose copy already exists in a pack.git gcrunsrepack,prune-packed,pack-refs, and pruning of old unreachable objects.
When packing happens
You rarely run git gc yourself, because porcelain commands start it automatically when thresholds are crossed:
gc.auto: when there are more than about 6,700 loose objects, a backgroundgcstarts.gc.autoPackLimit: when there are more than 50 packs, they are consolidated.receive.unpackLimitandtransfer.unpackLimit: a fetch or push with fewer than 100 objects is exploded into loose objects. A larger transfer is kept as a pack.
So a repository you only commit into can hold many loose objects for a long time, while a fresh clone starts almost entirely packed.
Edge cases
- An object that is both loose and in a pack is harmless. It just wastes space until
prune-packedruns. - Packs are never modified in place. Git writes a new pack and deletes the old one afterward, so a crash during
gcleaves a valid repository. git verify-packchecks the pack against its index. It does not check that the objects are reachable. For that, usegit fsck, which the next chapter covers.- Unreachable objects in a pack are only dropped when you repack.
git repack -a -dleaves them in a new pack if they are younger than the expiry. - Because the ID is the hash of the content, a pack can be copied between repositories and every object keeps its name.
Exercise
You run git gc in a repository with 500 loose objects, and git count-objects -v afterward still shows count: 3. You then run git hash-object -w --stdin on new text and count goes up by one. What are two likely reasons for the leftover 3, and which command lists unreachable objects?
Show answer
The leftover loose objects are probably unreachable objects younger than the two-week gc.pruneExpire grace period. gc leaves them alone, because deleting them could break a process that is still writing. They can also be objects created by commands that ran while gc was working. git fsck --unreachable lists objects that no ref reaches. git gc --prune=now would delete the unreachable ones.
Exercise
In the delta demo, git cat-file -p on the blob that is stored as a delta prints the full file. Which part of Git makes that work, and does the blob's ID change when it becomes a delta?
Show answer
Git's object-reading code looks up the ID in the pack index, reads the entry, finds its base object, and applies the delta instructions to rebuild the full content. The ID does not change. It is the hash of the header and the full content, so it stays the same regardless of how the bytes are stored.