Ran Wei/ Git & GitHub/Lesson 5
中文
Git and GitHub, Step by Step

Lesson 5Branches: try ideas safely

Try a new look for your page on a branch, switch between versions in a second, then bring the change into your main line.

⏱ 40 minYou need: Lesson 4 (the my-page repository with three commits)

In this lesson you will

  • Understand what a branch is, and what HEAD means
  • Create a branch and switch between branches
  • Bring a branch’s work into main with git merge
  • Recognise a fast-forward merge and a merge commit
  • Delete a branch you have finished with
1

Why branches?

Suppose you want to try a dark colour scheme for your page. You are not sure you will like it. You could edit style.css, and if you do not like the result, try to undo it all. Or you could work on a branch: a separate line of work where you can try anything, while main stays as it was.

A branch is a label on a commit1 git switch -c dark-theme2 git commit, on dark-themefirst pagea sentencecoloursmaindark-themeHEADfirst pagea sentencecoloursdark thememaindark-themeHEADmain stays where it was
Figure 5.1

A branch is a label that points at a commit. main points at your newest commit. A new branch, dark-theme, starts at the same commit. New commits move the label of the branch you are on, and HEAD shows which branch that is.

A branch is not a copy of your files. It is only a label on a commit, so making one is instant, and it costs nothing. You can have as many as you like.

2

See your branches

Open my-page in VS Code and open a terminal, as before. Then:

Terminal
$ git branch* main

You have one branch, main. The * marks the branch you are on.

Tip

VS Code shows the current branch in the bottom-left corner of the window, in the status bar. Glance at it whenever you are not sure which branch you are on.

3

Create a branch and switch to it

Terminal
$ git switch -c dark-themeSwitched to a new branch 'dark-theme'

git switch moves you to another branch; -c (“create”) makes it first. Branch names cannot have spaces, so use hyphens.

Terminal
$ git branch* dark-theme
  main

You are now on dark-theme. Nothing else has changed yet: both branches point at the same commit.

4

Try the dark theme

Change three colours in style.css, the highlighted lines (copy the box and paste it over the whole file, as in Lesson 4):

style.csshighlighted: the lines to add or change
body {  font-family: sans-serif;  max-width: 40em;  margin: 2em auto;  padding: 0 1em;  background: #1e1e2e;  color: #e6e6e6;} h1 {  color: #8ec5fc;}

Reload the page in your browser (if it is not open, open it as in Lesson 3): it is dark. Commit the change, on this branch:

Terminal
$ git add style.css$ git commit -m "Try a dark theme"[dark-theme 85f8f42] Try a dark theme
 1 file changed, 3 insertions(+), 3 deletions(-)

The first part of the answer, [dark-theme ...], confirms which branch the commit went to.

5

Switch back and forth

Now the interesting part. Switch back to main:

Terminal
$ git switch mainSwitched to branch 'main'

Look at style.css in VS Code, and reload the page in the browser: the light colours are back. Git changed your files to match the branch you switched to. Switch again:

Terminal
$ git switch dark-themeSwitched to branch 'dark-theme'

Dark again. Your work on each branch is safe in its commits, and git switch brings back whichever version you ask for.

To see both branches in your history, ask git log for all branches:

Terminal
$ git log --oneline --all85f8f42 (HEAD -> dark-theme) Try a dark theme
f952430 (main) Add colours with a style sheet
358630b Add a sentence about me
c50e3a0 Add my first web page

The labels in brackets show where each branch points. HEAD -> dark-theme means “you are here, on dark-theme”.

Key idea

HEAD means “where you are now”. It points at the branch you are on, and that branch points at a commit. When you commit, the branch you are on moves forward to the new commit, and HEAD moves with it.

If something went wrong

error: Your local changes to the following files would be overwritten by checkout. You changed a file and did not commit, and switching would overwrite your change. Commit it first (or, if you do not want it, throw it away with git restore), then switch.

fatal: a branch named 'dark-theme' already exists. You already made it. Switch to it without -c: git switch dark-theme.

git switch printed M and a file name before “Switched to branch”, and the page stayed dark. You had not committed your change to that file, so it came with you to the other branch. Switch back (git switch dark-theme), then git add and git commit the file there.

6

Bring the change into main: git merge

You like the dark theme. To bring it into main, go to main and merge the branch into it:

Terminal
$ git switch mainSwitched to branch 'main'$ git merge dark-themeUpdating f952430..85f8f42
Fast-forward
 style.css | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

git merge dark-theme means “bring the work of dark-theme into the branch I am on”.

“Fast-forward” is the simplest kind of merge. Nothing had happened on main since dark-theme began, so Git only had to move the main label forward to the branch’s newest commit.

Terminal
$ git log --oneline85f8f42 (HEAD -> main, dark-theme) Try a dark theme
f952430 Add colours with a style sheet
358630b Add a sentence about me
c50e3a0 Add my first web page

Both labels now point at the same commit.

7

Tidy up: delete the branch

The branch has done its job. Delete the label:

Terminal
$ git branch -d dark-themeDeleted branch dark-theme (was 85f8f42).

Only the label goes. The commit “Try a dark theme” is part of main now, and stays.

If something went wrong

error: the branch '...' is not fully merged. Git refuses to delete a branch whose commits are not in your current branch, so you do not lose work by accident. Merge it first. If you really want to throw that work away, git branch -D (capital D) deletes it anyway.

8

When both lines have moved on: a merge commit

A fast-forward is only possible when nothing happened on main in the meantime. Often something did. Try it: make a branch for a list of hobbies.

Terminal
$ git switch -c add-hobbiesSwitched to a new branch 'add-hobbies'

Add the highlighted lines to index.html:

index.htmlhighlighted: the lines to add or change
<!DOCTYPE html><html lang="en"><head>  <meta charset="utf-8">  <title>My page</title>  <link rel="stylesheet" href="style.css"></head><body>  <h1>Hello, I'm learning Git!</h1>  <p>This is my first web page.</p>  <p>I like walking, photography and good coffee.</p>  <h2>My hobbies</h2>  <ul>    <li>Walking</li>    <li>Photography</li>  </ul></body></html>
Terminal
$ git add index.html$ git commit -m "Add a list of hobbies"[add-hobbies b8140ac] Add a list of hobbies
 1 file changed, 5 insertions(+)

Now go back to main and change something else there: the page title, which browsers show on the tab.

Terminal
$ git switch mainSwitched to branch 'main'

The hobbies have disappeared from index.html: they only exist on add-hobbies. Change the title, the highlighted line:

index.htmlhighlighted: the lines to add or change
<!DOCTYPE html><html lang="en"><head>  <meta charset="utf-8">  <title>About me</title>  <link rel="stylesheet" href="style.css"></head><body>  <h1>Hello, I'm learning Git!</h1>  <p>This is my first web page.</p>  <p>I like walking, photography and good coffee.</p></body></html>
Terminal
$ git add index.html$ git commit -m "Change the page title"[main 15e66cc] Change the page title
 1 file changed, 1 insertion(+), 1 deletion(-)

Both branches have moved on from the same starting point. --graph draws it:

Terminal
$ git log --oneline --graph --all* 15e66cc (HEAD -&gt; main) Change the page title
| * b8140ac (add-hobbies) Add a list of hobbies
|/
* 85f8f42 Try a dark theme
* f952430 Add colours with a style sheet
* 358630b Add a sentence about me
* c50e3a0 Add my first web page

Read it from the bottom up: four shared commits, then the line splits in two.

Now merge. This merge needs one thing from you, so read this before you type the command. Git opens a tab called MERGE_MSG in VS Code with the message for the merge commit, Merge branch 'add-hobbies', and the terminal waits with “hint: Waiting for your editor to close the file...”. The message is fine as it is: close the tab (click the × on it). Git then finishes the merge, the waiting line disappears, and the terminal shows what is below. Click back in the terminal before you type the next command.

Terminal
$ git merge add-hobbiesAuto-merging index.html
Merge made by the 'ort' strategy.
 index.html | 5 +++++
 1 file changed, 5 insertions(+)

“Auto-merging index.html” means that Git combined the two versions of the file. This time Git could not just move a label forward, so it made a new commit, a merge commit, that joins the two lines. “ort” is the name of the method Git uses to combine them; you can ignore it.

Terminal
$ git log --oneline --graph*   618e8f4 (HEAD -&gt; main) Merge branch 'add-hobbies'
|\
| * b8140ac (add-hobbies) Add a list of hobbies
* | 15e66cc Change the page title
|/
* 85f8f42 Try a dark theme
* f952430 Add colours with a style sheet
* 358630b Add a sentence about me
* c50e3a0 Add my first web page

index.html now has the new title and the hobbies. Git combined the two changes because they were in different parts of the file.

Fast-forward merge and merge commitFast-forwardonly the label movesMerge commita new commit joins the two linesmainbeforemainafter the mergedark-thememainadd-hobbies
Figure 5.2

Two kinds of merge. Left: nothing happened on main, so the merge only moves the main label forward (a fast-forward). Right: both branches have new commits, so Git makes a merge commit with two parents.

Delete the finished branch:

Terminal
$ git branch -d add-hobbiesDeleted branch add-hobbies (was b8140ac).
If something went wrong

The terminal says “Waiting for your editor to close the file...” and nothing happens. Git is waiting for you to close the MERGE_MSG tab in VS Code. Find the tab and close it.

error: there was a problem with the editor 'code --wait'. Git could not start VS Code, because the terminal cannot find VS Code’s code command. On a Mac, do Lesson 2, Step 2, item 3; on Windows and Linux, close VS Code completely and open it again. The merge is not finished yet: once code works, type git commit and close the tab that opens.

The terminal filled with a strange screen with ~ down the left side. Git opened the editor Vim, because no editor is set (the core.editor setting from Lesson 2 is missing). Press Esc, type :wq and press Enter to accept the message and finish the merge. Then set the editor: git config --global core.editor "code --wait".

The terminal shows GNU nano at the top. The same on Linux, with the editor nano. Press Ctrl+X to accept the message and finish the merge. Then set the editor as above.

9

Try it: branches in pictures

Branches are easier to understand when you can see them. Use the buttons below as you like; each one shows the command it stands for. Some ideas:

  • Click Commit twice on main. Then make a new branch, commit twice on it, switch back to main, and merge the branch: a fast-forward.
  • Now commit on main and on a branch, then merge: a merge commit.
  • Try to merge a branch that is already merged.
Try it

A model of a repository’s history. The green circle is the commit you are on; HEAD -> marks your current branch.

10

What you learned

  • A branch is a label on a commit. main is your main line; others are for trying things.
  • HEAD means “where you are now”. The branch you are on moves when you commit.
  • git switch changes your files to match the branch you switch to.
  • git merge BRANCH brings a branch’s work into the branch you are on: by fast-forward if nothing else changed, otherwise with a merge commit.
  • git branch -d deletes a label. The commits stay.
Command What it does
git branch Lists branches; * marks the one you are on
git switch -c NAME Creates a branch and switches to it
git switch NAME Switches to an existing branch
git merge NAME Brings branch NAME into the current branch
git branch -d NAME Deletes a branch that has been merged
git log --oneline --graph --all Draws the history of all branches
11

Check yourself

1
What is a branch in Git?
2
You are on main and run git merge dark-theme. What happens?
3
When does Git make a merge commit instead of a fast-forward?
4
After git branch -d dark-theme, what happens to the commit “Try a dark theme”?
Finished this lesson?