Sub topic 1
How Git stores history: commits, parents, and branches
Prerequisites
This chapter assumes you can already do the following:
- Run commands in a terminal.
- Create a repository with
git initorgit clone. - Stage files with
git addand save them withgit commit. - Create and switch branches.
You do not need to know git log or git diff yet. Later chapters cover them.
Commits are snapshots with a parent link
A commit is a saved snapshot of your project. It also records an author, a date, a message, and a pointer to its parent. The parent is the commit that came directly before it.
Git identifies each commit by a hash, a 40-character ID computed from the commit's contents. Because the parent's hash is part of the child's contents, a commit cannot change without changing every hash after it. Tools usually show only the first 7 or so characters, called the abbreviated hash.
A commit stores a snapshot, not a diff. When you later see a diff, Git computed it by comparing two snapshots.
Most commits have one parent. A commit made by merging two branches has two parents. The first commit in a repository has none and is called the root commit.
History is a graph
Because each commit points back to its parents, the history forms a directed acyclic graph. Arrows run from child to parent, and they never form a loop. Commands like git log start at a commit and follow parent links backward, visiting each reachable commit.
Commit E is a merge, so it has two parents. Walking back from E reaches D, C, B, and A.
Branches are movable labels
A branch is a name that points to one commit. It is not a copy of your files, and it does not hold a list of commits. Creating a branch only creates a new label.
When you commit on a branch, Git creates the new commit with the current commit as its parent. Then it moves the branch label to the new commit. HEAD is a special pointer that says which branch (or commit) you currently have checked out.
Tags are labels too, but they normally stay fixed on one commit.
Here main is two commits ahead of feature. History for main includes C, B, and A. History for feature includes only B and A.
Seeing the structure yourself
You can print the parents of any commit with git rev-list:
git rev-list --parents -n 1 HEADThe output is the commit's hash followed by the hashes of its parents. One parent hash means an ordinary commit. Two means a merge. None means the root commit.
This is why a later chapter on revision ranges matters. Selecting commits means choosing starting points and excluding what is reachable from others.
Exercise
A repository has commits A, B, and C in a straight line, with main pointing at C. You run git branch hotfix B. How many commits does that command create, and what are the commits in the history of hotfix?
Show answer
It creates no commits, only a new label pointing at B. The history of hotfix is B and A, because those are the commits reachable from B by following parent links.