Engineering Toolkit, lesson 4
Branches, merges and conflicts
Work on a branch, merge it back, and settle a conflict by hand.
"Commits and the staging area": commits, git status, git log and HEAD.
Part 1. A branch is a label that moves
You want to try a change without disturbing the version that works. A branch gives you a separate line of commits to do it on, and main stays as it was until you decide to bring the change in. Branches in git are so cheap that the usual habit is one branch per change.
Your turn
How much does git copy when you make a new branch?
.git. Making one copies nothing else, which is why making a branch is instant even in a huge repository.$ git switch -c top-words
Switched to a new branch 'top-words'
$ git branch
main
* top-wordsThe * marks the branch you're on. Now change the script so the number of top words can be given on the command line, and commit it on the branch.
import re
import sys
from collections import Counter
text = open(sys.argv[1]).read().lower()
top = int(sys.argv[2]) if len(sys.argv) > 2 else 3
words = re.findall(r"[a-z']+", text)
print("words:", len(words))
for word, n in Counter(words).most_common(top):
print(word, n)$ git commit -am "Let the user choose how many top words"
[top-words 614e29e] Let the user choose how many top words
1 file changed, 2 insertions(+), 1 deletion(-)
$ git log --oneline --all
614e29e (HEAD -> top-words) Let the user choose how many top words
a24cc41 (main) Leave out environments, secrets and data
ba52d05 Show how to run it in the README
0f2361e Ignore punctuation when counting
26f2494 Count words in a text file
$ cat .git/refs/heads/top-words
614e29e945ae08587f3dad59d7fa6e436a3c4540-a stages every tracked file that changed, so commit -am saves a step when you know you want all of it. The log shows the two labels apart: top-words has moved to the new commit, and main is still where it was. And the last command shows the branch itself, a file holding a commit id.
Example 1.1
What moves when you commit on a branch
- a24cc41maintop-words
Just after
git switch -c: two labels on the same commit. HEAD points at top-words. - a24cc41main←614e29etop-words
A commit on top-words. The new commit's parent is a24cc41, and only the label HEAD points at moves.
- a24cc41maingit switch main
Switching back puts main's version of every file in your folder, and HEAD now points at main.
Branch
A name that points at a commit and moves forward each time you commit on it. HEAD points at the branch you're on. git switch -c name makes one and switches to it.
git switch arrived in git 2.23, in 2019. Older guides use git checkout -b top-words, which does the same thing.
Part 2. Merging a branch back
Keep going with Pro
You've done the first part. Pro opens the rest of this lesson, and every other one.
- Merging a branch back
- When both sides changed the same line
Engineering Toolkit overviewSpotted a mistake? Tell us.