Git & GitHub

Branches and Merging

35 分钟

A branch is a movable label pointing at a commit. Creating one is instant and free, so use a branch for every feature or fix.

Working with branches

git switch -c feature/contact-form   # create and switch
git branch                           # list local branches
git switch main                      # go back
git branch -d feature/contact-form   # delete after merging

Name branches by purpose: feature/..., fix/..., chore/....

Merging

git switch main
git merge feature/contact-form
  • Fast-forward: if main has not moved, Git just moves the label forward.
  • Merge commit: if both branches have new commits, Git creates a commit with two parents.

Conflicts

A conflict happens when both branches changed the same lines. Git stops and marks the file:

<<<<<<< HEAD
TIMEOUT = 30
=======
TIMEOUT = 60
>>>>>>> feature/slow-api

To resolve:

  1. Open the file and decide the correct result (it may be one side, the other or a combination).
  2. Delete the markers.
  3. git add config.py
  4. git commit (or git merge --continue).

If you get lost: git merge --abort returns everything to how it was.

Conflicts are normal, not a failure. Small, frequent merges keep them small.

Rebase: a linear alternative

git switch feature/contact-form
git rebase main

Rebase replays your commits on top of the latest main, producing a straight history. Because it rewrites your commits, never rebase commits other people already have. Use it to tidy your own branch before opening a pull request.

Interactive rebase lets you squash "fix typo" commits into the real ones:

git rebase -i HEAD~4

Worked example

git switch -c fix/rounding
# edit, test
git commit -am "Round amounts instead of truncating"
git switch main && git pull
git switch fix/rounding && git rebase main
git switch main && git merge fix/rounding
git branch -d fix/rounding

Check yourself

  • What is the difference between a fast-forward and a merge commit?
  • What are the three steps after Git reports a conflict?
  • When must you not rebase?

你的进度只保存在此浏览器中。

提交审核(10 积分)