# Branches: work on many things without breaking main

What a branch really is (a movable pointer to a commit), how to create, rename, switch and delete branches, carry uncommitted work safely, and merge a finished branch back into main.

Course: [Git & GitHub](https://devops.rajeev.pro/courses/git), lesson 3. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/git/03-branching

## What you will learn

- Explain a branch as a pointer to a commit, and HEAD as a pointer to your current branch
- Create, rename and list branches, and see the last commit on each
- Switch branches with git switch, and know what happens to uncommitted changes
- Delete merged branches, and understand why Git refuses to delete unmerged ones
- Merge a branch into main, and tell a fast-forward from a merge commit
- Name branches so a team can read them at a glance

## A branch is a pointer

**Why branches exist.** Imagine you're halfway through a new coupon feature: three files changed, tests
failing, nothing ready to ship. Then production breaks and you need a one-line fix out in ten minutes.
Without branches, your half-finished coupon work is mixed into the same files. You either ship it
broken along with the fix, or copy the project to another folder and fix it there, then copy the fix
back and hope you didn't miss anything.

With branches, each line of work lives separately. The coupon work stays on `feature/coupons`. You
switch to `main`, make the fix on a new `fix/checkout-crash` branch, merge and deploy it, then switch
back to your coupons exactly where you left them. Nothing leaks between the two.

**How it works.** Most people imagine a branch as a copy of the code. It isn't. A branch is a tiny file holding one
commit ID. Commits point back to their parents, and a branch just marks the newest one in a line of
work:

> **Figure.** Commits drawn as a chain of circles, each pointing back to its parent. Two labels point at commits: main points to C3, and feature/coupons points to C5, which branched off after C3. HEAD points to feature/coupons, meaning that is the branch you are on. When you commit, a new commit C6 is created after C5 and feature/coupons moves to it; main stays where it was. Below, the files on disk: .git/HEAD contains ref: refs/heads/feature/coupons, and .git/refs/heads/main contains a commit ID.
>
> Branches point at commits. HEAD points at your branch. Committing moves only the branch you're on.

```sh
$ cat .git/HEAD                   # where you are: a branch
ref: refs/heads/main
$ cat .git/refs/heads/main        # what main is: one commit ID
9c53c908c97e192de201aed90f9063ca0ba0ade9
```

That's the whole trick. Creating a branch writes 41 bytes, so it's instant even in a huge
repository. Make them freely: one per feature, fix or experiment.

## Create, list and rename

A branch always starts **from a commit**: by default the one you're on now. `git switch -c` creates
the branch and moves you onto it in one step, which is what you want 90% of the time. Plain
`git branch <name>` creates it without moving you, for when you want to mark a starting point and
carry on where you are.

```sh
$ git switch -c feature/coupons   # create a branch here, and switch to it
Switched to a new branch 'feature/coupons'
$ git branch                      # * marks the current branch
* feature/coupons
  main
$ git branch -m feature/coupon-codes   # rename the current branch
$ git branch -v                   # with each branch's last commit
* feature/coupon-codes 0438c28 Add an empty coupon table
  main                 dad9c23 Add the app entry point
$ git branch hotfix main          # create from another starting point, without switching
```

### Naming branches

Use a short type, a slash and a description in lowercase with hyphens. Teams and CI tools rely on
these prefixes (a pipeline may deploy every `release/*` branch, for example):

| Prefix                | For                   | Example                 |
| --------------------- | --------------------- | ----------------------- |
| `feature/`            | new functionality     | `feature/coupon-codes`  |
| `fix/`                | bug fixes             | `fix/empty-cart-crash`  |
| `chore/`              | tooling, dependencies | `chore/upgrade-node-22` |
| `docs/`               | documentation         | `docs/setup-guide`      |
| `release/`, `hotfix/` | release processes     | `hotfix/1.4.1`          |

Add the issue number when you have one: `fix/142-empty-cart`.

> **Video.** [Git Tutorial #5: How to Create a Git Branch | Learn Git with GitKraken](https://www.youtube.com/watch?v=snxybJkFeUo) (GitKraken)

## Switching branches

```sh
$ git switch main                 # go to an existing branch
$ git switch -                    # back to the previous branch
$ git checkout main               # the older command; does the same here
```

Switching changes the files in your working folder to match that branch. `coupons.py` exists on
`feature/coupon-codes` and disappears when you switch to `main`; it comes back when you switch
again. Nothing is lost: it's in the commit.

**Uncommitted changes** travel with you when they don't conflict with the other branch. If they would
be overwritten, Git refuses to switch:

```text
error: Your local changes to the following files would be overwritten by checkout:
	app.py
Please commit your changes or stash them before you switch branches.
```

Commit them, or put them aside with `git stash` (the _Undoing changes_ lesson). `git switch` is the
modern command for branches only. `git checkout` also restores files, which is why newer Git split
it into `switch` and `restore`.

## Merging a finished branch

> **Figure.** Animated. On main, commits C1 and C2 are made. git switch -c feature creates a branch label at C2. Two commits, F1 and F2, are added on feature while main stays at C2. git switch main and a commit C3 move main forward on its own line. git merge feature creates merge commit M with two parents, C3 and F2, and main moves to M.
>
> Watch the labels: each commit moves only the branch you're on. The merge commit M joins both lines into main.

When work on a branch is done, you merge it into `main`. There are two outcomes:

```sh
$ git switch main
$ git merge feature/coupon-codes
Updating dad9c23..0438c28
Fast-forward
 coupons.py | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 coupons.py
```

**Fast-forward:** main had no new commits since the branch started, so Git just moved `main` forward
to the branch's commit. No new commit is needed.

When both branches have new commits, Git combines them in a **merge commit**, which has two parents:

```sh
$ git merge fix/readme
Merge made by the 'ort' strategy.
 README.md | 1 +
 1 file changed, 1 insertion(+)
$ git log --oneline --graph
*   9c53c90 Merge branch 'fix/readme'
|\
| * 26df073 Document how to run the app
* | 032e8d2 Add VERSION file
|/
* 0438c28 Add an empty coupon table
* dad9c23 Add the app entry point
```

If both branches changed the same lines, Git stops and asks you to resolve a **conflict**. The
_Merge strategies_ lesson covers conflicts, rebasing and squashing in detail.

## Deleting branches

A merged branch has done its job. Delete it so `git branch` stays readable:

```sh
$ git branch -d feature/coupon-codes   # safe: only if merged
Deleted branch feature/coupon-codes (was 0438c28).
$ git branch -d spike
error: the branch 'spike' is not fully merged
$ git branch -D spike                  # force: you're sure the work isn't needed
Deleted branch spike (was 1bae2b4).
$ git branch --merged main             # branches already merged into main: safe to delete
```

Deleting a branch deletes the pointer, not the commits. For a while afterwards the commits can still
be recovered with `git reflog`, using the ID Git printed ("was 1bae2b4").

`-d` (lowercase) is the safe one: Git refuses if the branch has commits that aren't merged anywhere,
because deleting it would make that work hard to find. `-D` (uppercase) deletes anyway; use it only
for experiments you're sure you don't need.

Your local copy and the copy on GitHub are separate. After a pull request is merged, GitHub can delete
the remote branch for you; otherwise delete it with `git push origin --delete feature/coupon-codes`.

> **In a team.** `main` should always be deployable. Nobody commits to it directly: work happens on short-lived branches that are merged through pull requests (the *Collaboration* lesson). Branches that live for weeks drift from main and end in painful merges, so merge small pieces often.

## Choose a branching strategy deliberately

Every team needs a shared rule for how branches are used. There are three common ones, from simplest
to heaviest:

- **Trunk-based development.** Everyone branches off `main` (the "trunk"), keeps the branch for a day
  or two, and merges back through a pull request. Branches stay small, so merges stay easy, and `main`
  is always close to what's in production. It's the best fit when you deploy often, and the default
  most teams should start with.
- **Release branches.** Same as trunk-based, but when a version is ready you cut `release/2.4` from
  `main` and only bug fixes go into it, while new work continues on `main`. Useful when customers run
  several versions at once (mobile apps, installed software). The cost: every fix must be copied to
  both `main` and the release branch (with `cherry-pick`, in the _Merge strategies_ lesson).
- **GitFlow.** Adds a long-lived `develop` branch next to `main`, plus feature, release and hotfix
  branches. It was popular for software released every few months. For a web app deployed every day
  it's mostly overhead: more branches to keep in sync and more merges to resolve.

When unsure, choose trunk-based and add release branches only when you actually support more than one
version.

> **Figure.** Two branching strategies: trunk-based development with small branches merged into main frequently, and a release-branch model where longer-lived release branches take fixes and need more coordination.
>
> Trunk-based: small branches, frequent merges. Release branches: longer-lived fixes and more coordination.

```sh
$ git log --oneline --graph --decorate --all
$ git branch --merged main
$ git switch -c feature/short-lived-change
```

## Mission: Ship a feature and a fix in parallel

While building a coupon feature on its own branch, a README fix is needed urgently. Do the fix on a second branch, merge it first, then finish and merge the feature. End with a clean main, both branches deleted, and a history graph that shows what happened.

- You need: The shop repository from the Commits lesson (or any repository)
- You'll have: main with both changes; git log --graph showing the merge

```sh
$ git switch -c feature/coupons
$ echo 'COUPONS = {"WELCOME10": 10}' > coupons.py
$ git add coupons.py && git commit -m "Add the coupon table"
$ git switch main && git switch -c fix/readme        # urgent fix, from main
$ echo "Run: python app.py" >> README.md
$ git commit -am "Document how to run the app"
$ git switch main && git merge fix/readme            # fast-forward
$ git switch feature/coupons
$ echo 'def discount(code): return COUPONS.get(code, 0)' >> coupons.py
$ git commit -am "Look up coupon discounts"
$ git switch main && git merge --no-edit feature/coupons   # merge commit
$ git branch -d fix/readme feature/coupons
$ git log --oneline --graph
*   70b46cf Merge branch 'feature/coupons'
|\
| * ebe3728 Look up coupon discounts
| * 63892d4 Add the coupon table
* | f0952f8 Document how to run the app
|/
* dad9c23 Add the app entry point
```

`git commit -am` stages every tracked file that changed and commits it; it never adds new files. The
fix merged as a fast-forward because main hadn't moved; the feature needed a merge commit because
main had the fix by then.

## Try it

- Run `git branch` and `cat .git/HEAD` in a repository and explain both outputs.
- Create `feature/hello` with `git switch -c`, commit on it, then switch back to main and check the file is gone.
- Rename it with `git branch -m feature/greeting` and list branches with `git branch -v`.
- Merge it into main and read whether Git says "Fast-forward".
- Make a commit on a new branch, switch back, and try `git branch -d` on it without merging.
- Draw your history with `git log --oneline --graph --all`.

## Quiz

1. What is a Git branch, technically?
   - A full copy of the project's files
   - **A small file holding the ID of one commit; it moves forward when you commit on it** (answer)
   - A folder in .git with every changed file
   Why: .git/refs/heads/main contains a 40-character commit ID and nothing else. That's why creating a branch is instant and costs nothing.

2. What does HEAD point to normally?
   - The newest commit in the repository
   - **The branch you have checked out, such as refs/heads/main** (answer)
   - The remote server
   Why: HEAD says "you are here". Committing moves the branch HEAD points to. cat .git/HEAD shows ref: refs/heads/main.

3. You merge feature into main, and main has no new commits since feature started. What happens?
   - A merge commit is always created
   - **A fast-forward: main simply moves to feature's latest commit** (answer)
   - Git refuses
   Why: When main is an ancestor of feature, there is nothing to combine, so Git moves the pointer. If both have new commits, Git makes a merge commit with two parents.

4. git branch -d spike says "not fully merged". What does that mean?
   - The branch is broken
   - **spike has commits that no other branch contains; deleting it would lose easy access to them** (answer)
   - You need to push first
   Why: -d protects unmerged work. -D deletes anyway. Even then, the commits can be found with git reflog for a while (the Undoing changes lesson).

5. Which command creates a branch and switches to it in one step?
   - git branch new-thing
   - **git switch -c new-thing (or git checkout -b new-thing)** (answer)
   - git merge new-thing
   Why: git branch only creates it. switch -c creates and switches. git checkout -b is the older spelling of the same thing.

## Resources

- [Pro Git: branches in a nutshell](https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell) (Pro Git)
- [Pro Git: basic branching and merging](https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging) (Pro Git)
- [git-switch documentation](https://git-scm.com/docs/git-switch) (Git)
- [Learn Git Branching (interactive)](https://learngitbranching.js.org/) (Learn Git Branching)
