How Git stores data
Objects, hashes and references: the model that explains every command.
Git is a content-addressable store. Everything is an object named by the hash of its content, kept in .git/objects.
| Object | What it holds |
|---|---|
| blob | The contents of one file |
| tree | A directory: names pointing to blobs and other trees |
| commit | A pointer to a tree, the parent commit(s), author, date and message |
| tag (annotated) | A named pointer to a commit with a message |
git cat-file -t HEAD # commit
git cat-file -p HEAD # shows the tree, parent, author, message
git ls-tree HEAD # the files of that commitBranches are just pointers
A branch is a file in .git/refs/heads/ that contains one commit hash. Creating a branch is nearly free. HEAD points to the current branch. A commit stores its parent, so the history is a chain of commits linked by hashes.
cat .git/HEAD # ref: refs/heads/main
cat .git/refs/heads/main # a commit hashConsequences
- Changing a commit changes its hash and the hash of every descendant. That is why rewriting history needs a force push.
- Identical file contents are stored once, whatever their name or branch.
- Git stores snapshots, and shows diffs by comparing them. It does not store changes.
- Objects are only removed by garbage collection, long after they become unreachable.
NoteGit has used SHA-1 for object names since its beginning and supports a SHA-256 object format for new repositories. Hosting support for it is still limited.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.