Post

Git (Part 1): Commits, Branches and Merging from the Ground Up

Git explained from the very start with simple pictures: what a commit is, why a branch is only a pointer, how HEAD works, how work branches out, and how fast-forward, three-way merge, rebase, squash and reset really play out.

Git (Part 1): Commits, Branches and Merging from the Ground Up

Git series: Quick Summary · 1. Commits, Branches and Merging · 2. Remotes and Pointers · Cheat Sheet

Git looks big because of all the commands. The idea underneath is small, and once you can picture it, most commands explain themselves.

So we’ll start with pictures, with no commands at all, and bring the commands in once the picture is clear.

📑 Table of Contents

Commits: saved points in your project

You’re working on a project and you reach a point worth saving. You make a commit. Git takes a snapshot of all your files at that moment. Let’s call it A.

1
A

You work some more and commit again. That’s B. Git remembers that B came after A:

1
A ← B

One more:

1
A ← B ← C

That’s your history. Read each arrow as “came after”. Each commit points back to the one before it, called its parent.

Why backwards? Because when C is created, B already exists, so C can record it. B can’t record C, since C didn’t exist yet, and a commit can’t be changed afterwards.

That last part matters a lot, so remember these two things about commits:

  • A commit is a full snapshot of the project, not a list of changes.
  • A commit never changes. Once made, it stays exactly as it is.

Every commit gets its own unique ID, a long SHA such as 796e2c3…, worked out from its contents and its parent. So a new commit always means a new SHA. Nobody reads those, so this post sticks to letters.


Where the history actually lives

We’ve been drawing A ← B ← C and reading the arrows as history. But where do those arrows actually live? This is the piece that makes everything later click, so let’s be exact.

Each commit is an object, and it stores the ID of its parent inside itself. That parent link is the arrow. So commit C isn’t just a snapshot; it’s a small record that looks roughly like this:

1
2
3
4
5
C
├── tree:    (the snapshot of your files)
├── parent:  B          ← the arrow, stored right here
├── author:  you, with a date
└── message: "Add login"

And B holds the same shape, pointing at A. The very first commit is the one with no parent:

1
2
3
4
A                    B                    C
├── tree:  ...       ├── tree:  ...       ├── tree:  ...
├── parent: (none)   ├── parent: A        ├── parent: B
└── msg: "first"     └── msg: "Add API"   └── msg: "Add login"

Don’t take my word for it — this is a real commit, opened with git cat-file -p (the one time we’ll look at raw SHAs):

1
2
3
4
5
6
7
$ git cat-file -p HEAD
tree 5b372f88770ab124f5149bc6eae19714b16ee363
parent 4e9e88dead3cddecfb2e1fc02c143344018b5174    ← the previous commit
author  you <you@example.com> ...
committer you <you@example.com> ...

Add login

There it is: a parent line pointing at the commit before it. Open that parent and you’ll find its parent, and so on until the first commit, which has no parent line at all.

If that structure feels familiar, it’s because it’s a linked list — each node knowing only the one behind it:

1
2
3
class Commit:
    sha: str
    parent: Commit     # the one before it (None for the very first)

So Git rebuilds your whole history by starting at one commit and walking the parent links backwards: C → B → A → done. The history isn’t stored in a list somewhere; it’s distributed across the commits themselves, each holding one link in the chain.

Which raises the obvious question: if the history lives inside the commits, what does a branch actually hold? Just one thing, as it turns out.


Branches: just a pointer

If commits only have long IDs, how do you refer to the latest one? You give it a name. That name is a branch.

1
2
3
A ← B ← C
        ↑
       main

main isn’t a folder, and it isn’t a copy of your code. It’s a label that says “this commit”. On disk it’s a tiny text file with one commit ID inside it:

1
2
$ cat .git/refs/heads/main
796e2c3...        # the ID of C. That's the whole branch.

That’s a 41-byte file: forty characters of SHA and a newline. The branch knows only the latest commit; the commits know the rest. It doesn’t need to list the history — it points at C, and C’s parent links lead back through everything else.

When you make a new commit, the label moves forward by itself:

1
2
3
A ← B ← C ← D
            ↑
           main

Creating a new branch just adds a second label. Nothing gets copied, which is why it’s instant:

1
git branch feature
1
2
3
A ← B ← C ← D
            ↑
      main, feature

Two names, same commit. And you can see now why a branch can be pointed at any commit you want: it’s only a label. We’ll use that later.


Now there are two labels on D. When you commit, which one should move?

Git keeps one more pointer, called HEAD. It means “you are here”, and it normally sits on a branch:

1
2
3
A ← B ← C ← D
            ↑
      main (HEAD), feature

git checkout feature moves HEAD to the other branch, and updates your files to match that branch’s commit:

1
2
3
A ← B ← C ← D
            ↑
      main, feature (HEAD)

Now commit, and only the branch you’re on moves:

1
2
3
A ← B ← C ← D ← E
            ↑   ↑
         main   feature (HEAD)

main stayed where it was. That’s the whole trick behind branching.

To create a branch and move onto it in one go, use git checkout -b feature.

(Newer Git also has git switch feature and git switch -c feature, which do exactly the same. checkout does so many jobs that Git added switch for changing branches and restore for restoring files. The old commands still work everywhere, so use whichever you prefer. These posts use checkout, and the cheat sheet lists both.)


How work branches out

Go back to main and make a commit there too:

1
2
git checkout main
# edit something, then commit
1
2
3
A ← B ← C ← D ← F      main (HEAD)
             \
              E        feature

Now you have two lines of work that both started from D. Your files change as you switch between them, because each branch points at a different snapshot.

Sooner or later you’ll want them back together. There are two situations, and they work very differently.


Fast-forward: when only one side moved

Say you’re on main, you’ve done nothing on it since feature split off, and feature has two new commits:

1
2
3
4
5
     merge base
        ↓
A ← B ← C              main (HEAD)
         \
          D ← E        feature
1
git merge feature

C is the last commit the two branches share, called the merge base. You can ask Git for it directly with git merge-base main feature. Here the merge base is exactly where main already stands, so there’s nothing to combine: feature has everything main has, plus more. Git just slides the main label forward:

1
A ← B ← C ← D ← E      main (HEAD), feature

No new commit. A label moved. That’s a fast-forward.


Three-way merge: when both sides moved

Now say both sides have new commits:

1
2
3
4
5
     merge base
        ↓
A ← B ← C ← E ← F      main (HEAD)
         \
          D ← G        feature

Sliding a label can’t work any more, because whichever way it goes, some commits get left out. Git has to actually combine the work.

To do that it looks at three commits: the two ends, F and G, and the merge base C, where they split.

Why does it need C? Suppose one line of a file reads differently on each side. On its own that tells Git nothing about who changed it. But compare both sides with the original and it’s obvious:

1
2
3
in C (original)   in F (main)   in G (feature)   result
hello             hello         hi               hi        only feature changed it
bye               see ya        bye              see ya    only main changed it

Git puts the result in a new commit M, which has two parents:

1
2
3
A ← B ← C ← E ← F ← M      main (HEAD)
         \         /
          D ←──── G        feature

main moved to M. feature didn’t move at all. And those two arrows are a permanent record that these two lines of work met here.

That record pays off next time. If feature carries on and you merge it again, Git walks back and sees G is already part of main, so G is the new merge base. Only the new work gets merged.

Here’s that same merge for real. git log --graph draws the picture, newest at the top:

1
2
3
4
5
6
7
8
9
10
11
$ git log --oneline --graph --all
*   41cbb0a (HEAD -> main) M
|\
| * 624b720 (feature) G
| * 42b073b D
* | 44391be F
* | 624d19e E
|/
* 796e2c3 C
* 30b2545 B
* 39fce58 A

You can force a merge commit even when a fast-forward was possible, with git merge --no-ff feature. People do this so that a finished feature shows up as one clear event in the history.


Conflicts

Sometimes both sides change the same line in different ways, and Git can’t know which is right. It stops and marks the spot in the file:

1
2
3
4
5
<<<<<<< HEAD
see ya
=======
goodbye
>>>>>>> feature

The top half is yours, the bottom half is theirs. Edit the file to what it should be, delete the markers, and finish:

1
2
git add file.txt
git commit

Changed your mind? git merge --abort puts everything back as it was.

You can also decide in advance who wins, with git merge -X theirs feature. That only settles the conflicting lines. It doesn’t make your branch identical to theirs, and it’s still a real merge with two parents.


Rebase: the same goal, a different shape

A merge joins two lines with a knot, and that knot is the new merge commit M you just saw. Rebase does something else: it picks up your commits and replays them on top of the latest work, as if you’d started from there.

1
2
3
A ← B ← C ← E          main
         \
          D ← F        feature (HEAD)
1
git rebase main
1
2
3
A ← B ← C ← E              main
             \
              D' ← F'      feature (HEAD)

Notice it’s D' and F', not D and F. Commits can’t change, and a commit’s parent is part of what it is. So Git creates new commits, with the same changes and messages but new SHAs, and moves the feature label onto them. The old D and F are still there, just with no label pointing to them.

main can now fast-forward onto F', and the history is one straight line.

 MergeRebase
Shapeshows the fork and the joinone straight line
Existing commitsuntouchedreplaced by new copies
Safe on a shared branch?yesno

The rule to remember: don’t rebase commits other people already have. They’d still be holding the old D and F while you’ve replaced them with lookalikes.

Rebase can hit conflicts too, and since it replays one commit at a time it can stop more than once. Fix it the same way, git add, then git rebase --continue. Or git rebase --abort to go back to how things were.


Squash and cherry-pick: copying without connecting

A squash takes all the changes from a branch and puts them in one new commit:

1
2
git merge --squash feature
git commit -m "Add the feature"
1
2
3
A ← B ← C ← E ← S      main (HEAD)     S holds all the changes from D and F
         \
          D ← F        feature

It’s tidy, but look at what’s missing compared with a real merge: there’s no arrow from S to F. The code came across, but Git has no record of it. As far as Git knows, feature was never merged.

For a small branch you’re about to delete, that’s perfectly fine. For a long-running branch that you’ll merge again and again, it hurts, because Git has no idea what’s already been brought over and keeps comparing against the old C.

Cherry-pick is similar, for a single commit. It copies one commit onto where you are:

1
git cherry-pick G
1
2
3
A ← B ← C ← E ← G'     main (HEAD)
         \
          D ← G        feature

G' has the same changes and the same message as G, but cherry-pick always creates a new commit with its own new SHA. It doesn’t reuse G’s, and nothing links back to it.

It can hit conflicts as well, just like a merge or a rebase: fix the file, git add, then git cherry-pick --continue, or --abort to back out.


Same code doesn’t mean related

Here’s something that surprised me. Two branches can hold identical files, and Git will still refuse to merge them:

1
2
3
A ← B ← C      main

X ← Y ← Z      development
1
fatal: refusing to merge unrelated histories

Normally, walking the arrows back from two branches leads you to the commit where they diverged, and git merge-base main development prints it. Here the walks back from C and Z never meet, so it prints nothing: no merge base. Git only trusts the arrows. It never looks at whether the files happen to match. This happens when a repo gets re-created, or when code is copied into a fresh repo.

If you really do want to join them, you have to say so:

1
git merge --allow-unrelated-histories development

That creates a normal merge commit with two parents. From then on the two lines are connected and future merges work normally.

Now you can see how squash can catch you out. Merge development into an integration branch properly, then squash integration into main, and main gets all the code but none of the arrows. It’s still “unrelated”.


Moving a branch anywhere: reset

A branch is only a label, so you can move it. That’s what git reset does: it moves the branch you’re on to whichever commit you name, and HEAD goes with it.

1
A ← B ← C ← D      main (HEAD)
1
git reset --hard B
1
2
3
A ← B ← C ← D
    ↑
   main (HEAD)

C and D weren’t deleted. The label just isn’t on them any more.

I’m using a letter here, but B can be anything that leads to a commit: a SHA, another branch, a tag, or a remote branch like origin/main (more on that in Part 2). If you’re on a branch, you can point it anywhere at all.

Don’t confuse this with git checkout, because they move different things:

1
2
git checkout feature    HEAD moves to another branch. No branch moves.
git reset --hard B      The current branch moves. HEAD comes along with it.

The three kinds of reset differ in what happens to your files. Your work exists in three places: your actual files, the staging area (what git add prepares for the next commit), and the commit you’re on.

CommandMoves the branchClears the staging areaOverwrites your files
git reset --soft Byesnono
git reset Byesyesno
git reset --hard Byesyesyes

Use --soft to undo commits but keep everything staged, plain reset to keep the changes in your files, and --hard to throw them away.

--hard destroys any changes you haven’t committed. Those can’t be recovered.

If you just want to look at an old commit, you can git checkout B. HEAD then sits straight on a commit instead of on a branch. That’s the famous detached HEAD, and it’s harmless. Just remember that new commits made there have no branch moving along with them, so run git checkout -b some-name if you want to keep them.


Nothing committed is really lost

After that reset --hard, C and D seem to be gone. They aren’t. Git keeps a private log of everywhere HEAD has been:

1
2
git reflog                 # find the commit you want
git reset --hard <that-id> # put the branch back on it

So if a rebase or reset goes wrong, the commits are still there and the fix is to point the branch back at them. Before trying something risky, you can also just make a spare label for free: git branch backup.

The other undo worth knowing is git revert C, which adds a new commit that does the opposite of C. It doesn’t move anything backwards, so it’s the safe way to undo something other people already have.

And when you’re halfway through something and need to switch branches, git stash saves your unfinished changes to one side and git stash pop brings them back.


The whole picture so far

1
2
3
A ← B ← C ← E ← F ← M      main (HEAD)
         \         /
          D ←──── G        feature
  • Commits are snapshots that never change, and each one points to its parent.
  • A branch is a label on a commit. HEAD is where you are.
  • Committing moves the label forward.
  • Fast-forward slides a label. A three-way merge makes a commit with two parents.
  • Rebase and cherry-pick make new copies. Squash brings over the code without the arrow.
  • Reset moves a label anywhere you like.

All of this happened on one machine. So where does GitHub fit in, and what on earth is origin? That’s Part 2.

This post is licensed under CC BY 4.0 by the author.