Git Hour 2: Branching, merging, and team collaboration
- Make it clearfast forward mergewithThree-way mergerThe difference: How to use Git
git merge-baseFind the common ancestor, how to generate a merge commit with two parents, and when to use it--no-ff、--ff-only、--squash。 - Read conflict markers (including
diff3/zdiff3ancestor segment), will usegit mergetool、--ours/--theirsandgit rerereResolve conflicts efficiently and know what stage 1/2/3 is in the index. - understand rebase = rebase commits one by one to a new base point and generate a new hash, follow the golden rule of "do not rewrite other people's commits based on their work", and use it skillfully
rebase -i(pick/squash/fixup/reword/edit/drop)、--autosquash、--update-refs、--onto。 - use
cherry-pick -xTo move the patch back, usestashTo temporarily close the changes, useworktreeWork on multiple branches simultaneously. - understand
origin/mainYesRemote tracking branches(Local read-only snapshot), able to readgit branch -vvahead/behind, configured correctlypull.rebase、fetch --prune, and only use--force-with-lease --force-if-includesRewrite the remote branch. - Complete a Pull Request according to team specifications: branch naming, small and focused commits, review checklists, Conventional Commits, annotation tags and semantic versions, and be able to handle common collaboration conflicts.
1-hour time allocation table
| # | time | module | core content | animation/interaction | Experiment (~/git-lab) |
|---|---|---|---|---|---|
| 0 | before class | Connection and warm-up | Reuse myapp from Lesson 1 to establish a two-person collaboration environment of "bare repository + two clones" | Collaboration readiness self-assessment 10 items | collab/{remote,alice,bob}ready |
| 1 | 00–08 | Merger: Fast Forward and Three-Party Merger | merge base, fast forward, three-way merge,--no-ff/--ff-only, ort strategy, squash merge pros and cons | Core Animation:DAG changes for the same set of commits merge vs rebase (showing merge base with new hash) | Make forks and do ff/triparty/squash merges respectively |
| 2 | 08–15 | Conflict resolution and rerere | Conflict markers, stage 1/2/3, mergetool, diff3/zdiff3,--ours/--theirs、rerere | Conflict Resolver: Select ours/theirs/ to merge manually and watch the index changes | Create conflicts → zdiff3 → rerere automatic reuse |
| 3 | 15–24 | Rebase and interactive rebase | Replaying commits with new hashes, the golden rule,rebase -iSix commands,--autosquash、--update-refs、--onto | Interactive todo editor: tweak commands and preview result history | fixup! commit + autosquash organize PR history |
| 4 | 24–31 | cherry-pick, stash and worktree | Patch rollback,-x, three commits of stash, worktree and shared object library | stash stack and worktree directory simulation | Hotfix: worktree fix + cherry-pick back to main |
| 5 | 31–38 | Remote branches and tracking relationships | origin/mainessence,branch -vv、push -u、pull --rebase、fetch --prune、--force-with-lease | Three places (local/tracking branch/remote) state synchronization simulator | Push conflicts between two people: non-fast-forward → pull --rebase |
| 6 | 38–46 | Pull Request Workflow and Code Review | Correspondence between branch naming, small PR, review list, PR merging method and local commands | PR life cycle process + merge button comparison | Simulate a full PR review using local commands |
| 7 | 46–53 | Commit specs, tags and releases | Conventional Commits, lightweight vs. annotation tags,git describe、SemVer | Commit Checker + Version Calculator | Tag notes and generate change logs |
| 8 | 53–60 | Collaboration Readiness Review and Conflict Rehearsal | Team configuration baseline, location and recovery of common collaboration accidents | Interactive troubleshooting tree (non-fast-forward, rebase midway conflicts, mismatched main, stash conflicts...) | Four accident recurrences and repairs |
| — | After class | cheat sheet · Comprehensive experiment | Two-person collaboration: create and resolve conflicts, organize history before PR, release v1.1.0 | Final exam (12 questions) | Comprehensive experiment |
Knowledge Coverage Matrix Knowledge Coverage Matrix
| target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | key commands | experiment |
|---|---|---|---|---|---|---|---|---|---|---|
| Determine and execute fast forward/three-party/squash merge | ✓ | · | ✓ | · | · | ✓ | · | · | merge-base、merge --no-ff/--ff-only/--squash | M1 Experiment |
| Understand and resolve conflicts | · | ✓ | ✓ | ✓ | ✓ | · | · | ✓ | ls-files -u、checkout --ours、mergetool | M2, comprehensive experiment |
| Reuse conflict resolution (rerere) | · | ✓ | ✓ | · | · | · | · | ✓ | rerere.enabled、rerere status/diff/forget | M2 Experiment |
| Rewrite local history (rebase/-i) | · | · | ✓ | · | ✓ | ✓ | · | ✓ | rebase -i --autosquash --update-refs、--onto | M3, comprehensive experiment |
| Patch rollback and temporary workspace | · | · | · | ✓ | · | · | ✓ | ✓ | cherry-pick -x、stash、worktree | M4 Hotfix |
| Remote tracking and secure push | · | · | · | · | ✓ | ✓ | · | ✓ | branch -vv、fetch --prune、push --force-with-lease | M5 double push |
| PR workflow and code review | ✓ | · | ✓ | · | ✓ | ✓ | ✓ | ✓ | diff main...feature、range-diff | M6 Analog PR |
| Commit specs, tags and versions | · | · | ✓ | · | · | ✓ | ✓ | · | tag -a、describe、log --format | M7 released |
| Collaborative incident location and recovery | · | ✓ | ✓ | ✓ | ✓ | · | · | ✓ | reflog、rebase --abort、reset --hard ORIG_HEAD | M8 Walkthrough |
What’s excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | where to study |
|---|---|---|
| Branch protection, rulesets, CODEOWNERS, required reviewers for GitHub/Azure Repos | It belongs to the hosting platform capability; this lesson only talks about the Git mechanism behind PR | Lesson 3(Azure Repos and GitHub), Lesson 4 (AWS CodeCommit and GitLab) |
| Commit signing (SSH/GPG/gitsign), pre-commit hooks, commit information checking in CI | Automation and supply chain security | Lesson 5 (Git in CI/CD and Automation) |
| Git Flow / GitHub Flow / Choices, monorepo, and submodules of trunk development | Belongs to branch strategy and repository architecture | Lesson 6 |
reflog goes deep,git bisect, filter-repo clear secrets | It belongs to in-depth debugging and historical recovery (this lesson only uses the basic operations of reflog on M8) | Lesson 7 |
| Internal implementation of the merge algorithm (ort's rename detection, recursive merge base details) | more than 1 hour | git-scm.com: merge-strategies |
How to use this courseware
Principles · Diagrams · Animations · Commands · Experiments · Production Examples · Troubleshooting · Tests · Voice · Videos. It is recommended to read the "Principle" and "Animation" first, and then do the "Experiment" in ~/git-lab.
A test score ≥ 70% or clicking "Mark this module complete" will be counted as progress and saved in this browser (it will be cleared after refreshing when local storage is disabled).
The "Voice" tab uses the built-in Web Speech API (zh-CN) of the browser to read the explanation script; if there is no Chinese voice package, the explanation script can still be read or handed over to the TTS tool.
ortBecome the default merge strategy (2.34);zdiff3Conflict Styles (2.35, "Zealous diff3");rebase --update-refs(2.38);push --force-if-includes(2.30);--autosquashAlso works with non-interactive rebase (2.44); deprecated and removed starting in 2.50merge-recursiveThe first step; added in 2.56git add --resolved、git branch --delete-merged、git replay --linearizeand experimentalgit history drop. Ubuntu 24.04 comes with Git 2.43. If you want to use 2.44+, please follow Lesson 1.ppa:git-core/ppaUpgrade.Module 0 · Connection and warm-up (completed before class)
- CompletedLesson 1: Understand the workspace/staging area/commit and can be used
git log --oneline --graphLook at history; practice repository~/git-lab/myapp(Myapp of Flask + Redis, including Dockerfile and compose.yaml). - Environment: Ubuntu 24.04 (Azure VM or WSL) / macOS / Git Bash for Windows. All commands in this lesson are POSIX shell.
- This lesson does not require any cloud account: use the local oneNaked repository(bare repository) acts as a "remote repository on GitHub", two clone directories
alice、bobRepresenting two developers.
Step 1: Check the Git version with the repository from Lesson 1
First, rebuild the repository of Lesson 1 to the courseware state (Must do: The comprehensive experiment of Lesson 1 has beenv1.2.0Push to origin. If you do not rebuild, this lesson will conflict when M7 releases v1.2.0):
bash ~/bootstrap-git-lab.sh --force
git --version cd ~/git-lab/myapp && git status -sb && git log --oneline --graph --all -8
git version 2.56.0 ## main...origin/main * fd29861 (experiment) wip: experiment with cache layer | * 912a321 (origin/feature/login, feature/login) docs: document /login | * f6f172d feat(auth): add login stub |/ * f4ac97b (HEAD -> main, tag: v1.1.0, origin/main) Merge branch 'hotfix/redis-timeout' |\ | * 17f033d (hotfix/redis-timeout) fix: set redis socket timeout * | abb417c fix: remove FAKE_SECRET from settings.env …
bash ~/bootstrap-git-lab.sh --forceIt is the script of Lesson 1, Module 0 (the author and timestamp are fixed, and it will be reconstructed to a state that is completely consistent with the courseware within 1 second); after~/git-lab/myappIf it is messed up by practice, it can be executed again at any time. The single-person experiment of M1–M3 in this lesson is directly in~/git-lab/myappcarried out in; collaborative experiments starting from M4 are established in step 2~/git-lab/collabin progress.
The experiment of this lesson relies on the repository of Lesson 1app.py(located in the root directory of the repository) (main/v1.1.0 version):
redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_timeout=2)
…
count = redis.incr("hits")
return f"Hello from myapp! I have been seen {count} times.\n"
…
@app.route("/healthz")
def healthz():
return {"status": "ok"}
Step 2: Set up a two-person collaboration environment (repeatable)
The script will: ① Check the generated~/git-lab/remote/myapp.git(The "origin" of Lesson 1 includes main, feature/login and tags v1.0.0, v1.1.0); ② Clone it into a new bare repository~/git-lab/collab/remote/myapp.git(Equivalent to the remote repository on the platform); ③ Clone outalice、bobTwo working directories and set them separatelyrepository leveluser.name/email (will not change your global configuration). Because the clone source is the origin of Lesson 1 instead of your myapp working repository, the exercises M1–M3 do in myapp will not affect the collaboration environment. The results obtained by the two pathsapp.pyTotally consistent.
Save the following script as~/setup-collab.sh:
#!/usr/bin/env bash
# Lesson 2: Two-person collaborative environment. Repeatable ($LAB/collab will be deleted and rebuilt)
# Prerequisite: The bootstrap-git-lab.sh of Lesson 1 has been run (generating $LAB/myapp and $LAB/remote/myapp.git)
set -euo pipefail
LAB="${LAB:-$HOME/git-lab}"
SRC="$LAB/remote/myapp.git" # "origin" of Lesson 1: main, feature/login, tag v1.0.0 v1.1.0
if [ ! -d "$SRC" ]; then
echo "$SRC not found, please run the script of Lesson 1 first: bash ~/bootstrap-git-lab.sh --force"; exit 1
fi
cd "$LAB" # Avoid the current directory in the collab to be deleted
rm -rf "$LAB/collab" && mkdir -p "$LAB/collab/remote"
git clone -q --bare "$SRC" "$LAB/collab/remote/myapp.git"
for who in alice bob; do
case $who in alice) name=Alice ;; bob) name=Bob ;; esac
git clone -q "$LAB/collab/remote/myapp.git" "$LAB/collab/$who"
git -C "$LAB/collab/$who" config user.name "$name"
git -C "$LAB/collab/$who" config user.email "$who@example.com"
done
echo "OK: remote=$LAB/collab/remote/myapp.git, developer directory alice/bob"
git -C "$LAB/collab/alice" branch -vv
git -C "$LAB/collab/alice" tag -l
bash ~/setup-collab.sh cd ~/git-lab/collab/alice && git remote -v
OK: remote=/home/azureuser/git-lab/collab/remote/myapp.git, developer directory alice/bob * main db1616e [origin/main] docs: add local run instructions v1.0.0 v1.1.0 origin /home/azureuser/git-lab/collab/remote/myapp.git (fetch) origin /home/azureuser/git-lab/collab/remote/myapp.git (push)
db1616eis the commit pushed to origin by the "teammates" in Lesson 1 (1 commit more than v1.1.0), which is generated by the Lesson 1 script at a fixed time, so it's the same for everyone. Afterwards, new commits by Alice and Bob use their respective identities and current time, and the hash will be different from the courseware.
.gitObjects and references in GitHub, Azure Repos, and GitLab servers store exactly this kind of repository. Go to a workspace and check it outmainNon-naked repository pushmainwill be rejected (receive.denyCurrentBranch), so "remote" must be used--bare。Step 3: Repository-level configuration recommended in this lesson (explained one by one in subsequent modules)
for d in ~/git-lab/collab/alice ~/git-lab/collab/bob; do git -C "$d" config merge.conflictStyle zdiff3 # M2: Show common ancestors in conflicts git -C "$d" config rerere.enabled true # M2: Remember conflict resolution git -C "$d" config pull.rebase true # M5: Rebase when pulling instead of merging git -C "$d" config fetch.prune true # M5: Automatically clean up deleted remote branches git -C "$d" config rebase.autoSquash true # M3: Automatically organize fixup! Commit git -C "$d" config rebase.updateRefs true # M3: Move overlapping branches together git -C "$d" config push.useForceIfIncludes true # M5: with --force-with-lease done
These can also be added--globalSet as personal default. This lesson deliberately uses repository-level configuration to facilitate you to compare the behavior differences "with/without" a certain configuration.
Warm-up: Answer from memory (30 seconds)
What exactly is a branch in Git?
A movable pointer to a commit (.git/refs/heads/<name>or a line in packed-refs containing a 40-bit hash). Creating a branch costs almost nothing;HEADUsually points to the current branch (symbolic reference). This is the basis of all operations in this lesson: merging and rebasing are actually "generating new commits + moving branch pointers".
What is recorded in the commit object?
tree (snapshot), parent (0, 1 or more), author, committer, commit information. The commit hash is calculated from these contents - so whenever parent changes, the hash must change. With this in mind, rebasing the M3 is easy to understand.
Collaboration Readiness Self-Assessment (10 items)
tick youIt can be done nowproject (results saved in this browser). Come back and check it again after finishing this lesson and completing the comprehensive experiment.
Module 1 · Merging: Fast Forward and Three-Way Merging
- use
git merge-baseFind the common ancestor (merge base) and determine whether a merger will befast forwardStillThree-way merger。 - Explain the input of a three-way merge (three snapshots of base / ours / theirs) and the output (a merge commit with two parents).
- in
--ff(default),--no-ff、--ff-only、--squashMake a reasoned choice between squash merge and know the pros and cons of squash merge.
What: What the merge is doing
git merge featureThe meaning is:Integrate the changes brought by the commits on the feature branch that are not yet in the current branch into the current branch. Git first calculates the two branchescommon ancestor(merge base), and then handle it in two situations:
| situation | Judgment conditions | Git actions | result |
|---|---|---|---|
| fast-forward | merge base == the commit of the current branch (the current branch is the ancestor of the other party and has no new commits) | Only move the current branch pointer forward to the commit of feature | No new commits are generated, history is still a straight line |
| three-way/true merge | Both sides have their own commits after merge base (history fork) | Compare the differences between base→ours and base→theirs to synthesize a new tree; if there is no conflict, it will be automatically committed. | generate amerge commit, there are 2 parents (the first one is ours, the second one is theirs) |
| Already up to date | feature is the ancestor of the current branch | do nothing | No change |
Why: Why "three parties"
When only comparing two versions (both sides), Git has no way of knowing whether a certain line is "added by A" or "deleted by B". With this third version of common ancestor, the rules are clear:Only one side has been changed → adopt the changed side; both sides have been changed to the same → adopt; both sides have made different modifications to the same area → conflict(M2). This is why the merge base is the core of the entire merge mechanism.
How: Steps for a three-way merger
git merge-base HEAD feature→ Common ancestor B (if there are multiple "best common ancestors", ort will first recursively merge them into a virtual ancestor).- Compare the three versions of B, HEAD (ours), and feature (theirs) for each path: first perform rename detection, and then press hunk in the file to perform a three-way merge.
- No conflict: write a new tree and create a commit object (
parent HEAD+parent feature), move the current branch pointer; record at the same timeORIG_HEAD(Pre-merge position for easy undo). - There is a conflict: write the conflict into the workspace and index (stage 1/2/3), write
.git/MERGE_HEAD, stop and wait for you to solve it (M2).
A quick look at merge options
| Options | Can fast forward | When fast forwarding is not possible | Typical uses |
|---|---|---|---|
(default)--ff | fast forward | Three-way merger | Daily local merge |
--no-ff | Still create merge commit | Three-way merger | Keep the boundaries of "this group of commits belong to a certain feature"; GitHub "Create a merge commit" and Azure Repos "Merge (no fast forward)" are all like this |
--ff-only | fast forward | reject:fatal: Not possible to fast-forward, aborting. | Ensure linear history; prevent accidental merge commits when synchronizing main (merge.ff only、pull --ff-only) |
--squash | Combine all the opponent's changes into one copy and put it inStaging area, do not commit or record MERGE_HEAD; you can manuallygit commit, get aonly 1 parentOrdinary commit of | Squash the messy feature branches into one commit (PR "Squash and merge") | |
Merge strategy: ort
strategy(-s) determine "how to calculate", strategy options (-X) to fine-tune it. sinceGit 2.34The default policy isort("Ostensibly Recursive's Twin"), it isrecursiveA rewritten version, the results are basically the same as recursive but faster and the rename processing is more accurate; since 2.50, Git has deprecated and removed the old merge-recursive implementation (now written-s recursivewill also be handled by ort). Other strategies:octopus(When merging more than 3 branches at a time, there must be no conflicts),ours(completely ignoreChanges made by the other party only record the merge relationship),subtree. Commonly used-XOptions:-X ours/-X theirs(Only favor one side on the conflicting hunk, non-conflicting changes will be merged as usual),-X ignore-space-change、-X find-renames=40%。
-s ours(Strategy: Discard the other party’s entire content) and-X ours(Strategy option: Pick our side in a conflict) It's not the same thing at all. The former is often used to "state that an old branch has been processed and will no longer be merged." Misuse will quietly throw away other people's code.When: pros and cons of squash merge
| Advantages | Disadvantages | |
|---|---|---|
| squash merge | main Previous PR = a commit,git logClean; revert the entire feature only requires one commit; "wip" and "fix typo" in the PR will not enter the trunk | Loss of fine-grained history (git bisectcan only locate the entire PR); the original branch and mainno ancestral relationship, continuing to develop and merge on the original branch will cause repeated conflicts;git branch -dConsider the branch "unmerged" (requires-D); signatures of multiple authors requireCo-authored-by: endnote |
| merge commit(--no-ff) | The original commit and branch structure is kept intact and availablegit log --first-parentJust look at the trunk | The history graph is complex; "wip" commits go into trunk (so usually paired with pre-PRrebase -iOrganizing, M3) |
| rebase + fast forward | Linear history, keeping every commit | Rewritten commit hashes for feature branches (the golden rule of M3) |
Compare with similar concepts
| merge | rebase(M3) | cherry-pick(M4) | |
|---|---|---|---|
| Whether to rewrite existing commits | No | Yes (generate new hash) | No (copy out new commit) |
| Whether to record "merge relationship" | Yes (2 parents) | No | No (available-xIndicate the source in the message) |
| Number of conflicts | at most once | Each replayed commit may conflict | Each selected commit |
-X theirsIt is equivalent to overwriting with the other party's version" - only affects the conflicting hunk, the non-conflicting part is still the result of the merger of both sides. ③ "You can continue to use the original branch after the squash merge" - Yes, but the next merge will bring the squashed changes again and cause conflicts; the correct approach is to delete the original branch and reopen the branch from the latest main.Figure 1-1 Fast forward vs three-way merge (DAG: arrow points from child commit to parent commit)
Figure 1-2 Historical comparison of the output of the four merger methods
Core Animation: the same group of commits, the commit graph (DAG) after merge and rebase
Starting point: main has commit E after B, and feature has commits C and D after B (the hash is taken from the example repository actually run on Git 2.51 in this lesson). Select "merge" or "rebase" and play it step by step. Pay attention to three things:where is the merge base、Which commits are newly created (new hashes)、How to move branch pointer。
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git merge-base A B | Find common ancestors | --allList all best ancestors;--is-ancestor A BUse exit codes to determine ancestor relationships (commonly used in scripts) |
git merge <branch> | Merge into current branch | --no-ff、--ff-only、--squash、--no-edit、-m、--log(List the merged commits in the message) |
git merge -s / -X | Select Strategy/Strategy Options | -s ort(default),-s ours、-X theirs、-X ignore-space-change |
git merge --abort | Abandon the ongoing merge and revert to before the merge | It may not be possible to fully recover if there are uncommitted changes in the workspace before merging - commit or stash before merging |
git log --graph --first-parent | View trunk history only along the first parent | cooperate--no-ffThe history of |
git branch --merged / --no-merged | List branches that have/have not been merged into the current branch | Branches merged by squash will be displayed as "unmerged"; new in 2.56git branch --delete-mergedDelete a local branch that has been merged into its upstream |
git config merge.ff | Default merge behavior | false(always --no-ff) oronly(always --ff-only) |
cd ~/git-lab/myapp git log --oneline --graph main feature/greeting -6 # Complete step 1 of "Experiment" paging first git merge-base main feature/greeting git merge-base --is-ancestor main feature/greeting && echo "can fast forward" || echo "has been forked and needs to be merged by three parties"
* ae12701 (HEAD -> main) feat(config): read REDIS_PORT | * 0544839 (feature/greeting) docs: how to run | * b1432cd feat(api): change greeting |/ * f4ac97b (tag: v1.1.0) Merge branch 'hotfix/redis-timeout' |\ | * 17f033d fix: set redis socket timeout * | abb417c fix: remove FAKE_SECRET from settings.env f4ac97b045741bd4b587553d05e81bb3e10594ff Has been forked and needs to be merged by three parties
git merge --ff-only feature/greeting # forked → rejected git merge --no-edit feature/greeting # Three-party merge git log --oneline --graph -6 git cat-file -p HEAD | head -4 # See the two parents of the merge commit
hint: Diverging branches can't be fast-forwarded, you need to either: hint: hint: git merge --no-ff hint: hint: or: hint: hint: git rebase hint: hint: Disable this message with "git config set advice.diverging false" fatal: Not possible to fast-forward, aborting. Auto-merging app.py Merge made by the 'ort' strategy. README.md | 1 + app.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) * 8fa5bb7 (HEAD -> try-merge) Merge branch 'feature/greeting' into try-merge |\ | * 0544839 (feature/greeting) docs: how to run | * b1432cd feat(api): change greeting * | ae12701 (main) feat(config): read REDIS_PORT |/ * f4ac97b (tag: v1.1.0) Merge branch 'hotfix/redis-timeout' tree fc245367a0995aced280b4389427410a8444f927 parent ae12701124c59b9df32dfa715e440091ac7e911d parent 0544839c8dbf66df329a543859887d74a41ad0e2 author Alice <alice@example.com> 1794781305 -0500
The above output is attry-mergeexecuted on the branch (see steps 2–3 of the “Experiment” tab), so the merged informationinto try-merge; Merging on main does not have this suffix. Notef4ac97bIt is also a merge commit left over from Lesson 1 (the hotfix branch is merged into main).
How to verify:merged commitgit cat-file -pThere are two linesparent;git rev-parse HEAD^1 HEAD^2Give the first parent and the second parent respectively.Common mistakes:put HEAD~2(two steps back along the first parent) andHEAD^2(Second Father) Confusion.Production use:CI is used to determine "whether this push is fast forward"merge-base --is-ancestor;Undo a merge you just made.git reset --hard ORIG_HEAD(when not pushed) orgit revert -m 1 <merge>(when pushed).
squash merge
git switch try-squash git merge --squash feature/greeting git status -s # Changes are in the staging area, there is no MERGE_HEAD git commit -m "feat(api): new greeting and run docs (#12)" git branch -d feature/greeting # Report not fully merged, need -D
Auto-merging app.py Squash commit -- not updating HEAD Automatic merge went well; stopped before committing as requested M README.md M app.py [try-squash 7d2c0a1] feat(api): new greeting and run docs (#12) error: the branch 'feature/greeting' is not fully merged hint: If you are sure you want to delete it, run 'git branch -D feature/greeting'
Experiment 1: For the same fork, do fast forward, three-way merge and squash merge respectively (about 6 minutes)
~/git-lab/myapp, does not affect the collaboration directory):cd ~/git-lab/myapp && git switch main # Lesson 1 repository, main is located at f4ac97b (v1.1.0)
git switch -c feature/greeting
sed -i 's/Hello from myapp!/Hello, Git!/' app.py
git commit -qam "feat(api): change greeting"
echo "Run with: docker compose up" >> README.md
git add README.md && git commit -qm "docs: how to run"
git switch main
sed -i 's/port=6379/port=int(os.getenv("REDIS_PORT", "6379"))/' app.py
git commit -qam "feat(config): read REDIS_PORT"
grep -n 'port=' app.py
git log --oneline --graph main feature/greeting -6
6:redis = Redis(host=os.getenv("REDIS_HOST", "redis"), port=int(os.getenv("REDIS_PORT", "6379")), socket_timeout=2)
Lesson 1's main has been merged into the hotfix,port=6379, socket_timeout=2Both parameters are present, sed only replaces the port part, and the result is still legal Python. BSD sed for macOS needs to be writtensed -i ''; Git Bash and Ubuntu can use the above writing method.
git branch try-merge main git branch try-squash main
use try-*branch to experiment with realmainIt doesn't move, making it easy to practice repeatedly. Fast forwarding requires "the target is the descendant of the current branch". Step 5 will first rebase the copy of feature on main (M3 details) to create this relationship.
git switch try-merge git merge --ff-only feature/greeting || echo "→ Reject: Fork cannot be fast forwarded" git merge --no-edit feature/greeting git log --oneline --graph -5 git log -1 --format='%p' # The merge commit has two parent commits (HEAD^1 and HEAD^2)
git switch try-squash git merge --squash feature/greeting git commit -qm "feat(api): greeting + run docs (squashed)" git log --oneline --graph -4 git cat-file -p HEAD | grep -c ^parent # 1 parent
git switch -c try-ff2 feature/greeting git rebase -q main # now try-ff2 = main + 2 replay commits git switch -c try-main main git merge --ff-only try-ff2 git log --oneline --graph -4
Updating ae12701..962c274 Fast-forward README.md | 1 + app.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) * 962c274 (HEAD -> try-main, try-ff2) docs: how to run * dbd4498 feat(api): change greeting * ae12701 (main) feat(config): read REDIS_PORT * f4ac97b (tag: v1.1.0) Merge branch 'hotfix/redis-timeout'
git rev-parse try-merge^{tree} try-squash^{tree} try-main^{tree}
Three rows of hashes are the same: obtained in three waysThe file snapshot is exactly the same, the difference is only in the committed graph. This is exactly the question of "the merging method is the team's agreement on the historical shape" rather than "whether the code is correct or not."
git switch main git branch -D try-merge try-squash try-ff2 try-main git branch -D feature/greeting # No longer needed; want to restore the entire repository: bash ~/bootstrap-git-lab.sh --force
Case 1: A large number of "Merge branch 'main' of github.com/…" commits appear on main
Question:Team member habitsgit pull(Default merge), a meaningless merge commit is generated every time there is a local commit and it lags behind the remote.git logdifficult to read,bisectAlso disturbed.Method:Unified configurationpull.rebase true(M5) orpull.ff only;The platform side only allows merging into main via PR (branch protection in Lesson 3).Effect:The trunk is left with merge commits or squash commits generated by PRs.Limitations:The history that has been generated should not be rewritten (it will affect everyone) and will only take effect for subsequent commits.
Case 2: Continue to develop on the old branch after squash, and the second PR conflict becomes a piece of cake.
Question:After PR #40 was merged using “Squash and merge”, the developer continued to commit on the same branch and opened PR #41. The platform showed a large number of conflicts and merged changes.Root cause:The squash commit has no ancestor relationship with the original branch commit, and the merge base still stays at the position when the branch was opened.Method:After squash is merged, delete the remote and local branches and open a new branch from the latest main; if there are new commits, usegit rebase --onto origin/main <The last merged commit of the old branch > featureOnly new commits (M3) are moved.
Case 3: The release branch requires "fast forwarding" to advance
Question:The release branch was accidentally merged into a fix with a merge commit, causing the release content to be inconsistent with main.Method:Promote the use of release scriptsgit merge --ff-only origin/main, abort and notify if it fails; or check in CIgit merge-base --is-ancestor origin/release origin/main。Effect:release is always an ancestor snapshot of main and can be traced back.
Common errors and solutions
fatal: Not possible to fast-forward, aborting.
Reason:used--ff-only(or configuredmerge.ff only / pull.ff only), and the two branches have bifurcated.
git log --oneline --graph --all -10 git merge-base HEAD <branch>
Fix:Choose one of two - accept merge commits (git merge --no-ff), or first rebase your own branch on the other party (git rebase <branch>) and then fast forward.
fatal: refusing to merge unrelated histories
Reason:The two branches do not have any common ancestor (e.g. localgit initLater, I want to merge the repository that has initialized README on the platform).
Fix:When confirming that you really want to merge two independent histories:git merge --allow-unrelated-histories origin/main, there are usually conflicts with files such as README that need to be dealt with.
error: Your local changes to the following files would be overwritten by merge
Reason:The workspace has uncommitted changes that involve the same file as the changes to be merged. Git refuses to merge to avoid losing your changes.
git status -s git stash push -m "before merge" && git merge feature && git stash pop
Fix:Commit or stash (M4) first, then merge.
After merging, it was found that the wrong branch was merged (not yet pushed)
git reset --hard ORIG_HEAD # Return to before merging git reflog -5 # Or find the position before merging from reflog
If it has been pushed, do not reset, usegit revert -m 1 <merge-commit>Generate a reverse commit (-m 1Indicates that the first parent is the main line). Note: After reverting a merge, if you want to merge the same branch again in the future, you need to revert the revert first.
error: The branch 'feature/x' is not fully merged.
Reason:The branch's commit is not in the history of the current branch (or its upstream) - common after a squash/rebase merge.
Fix:First make sure the content has been incorporated (git diff main...feature/xis empty or the PR has been merged), thengit branch -D feature/x。
1. Write a command to determine whether main can be fast-forwarded to origin/main (for scripts, output yes/no).
git merge-base --is-ancestor main origin/main && echo yes || echo no
2. Merge feature/login into main, and keep a merge commit regardless of whether it can be fast-forwarded. The merged commits are listed in the commit information.
git switch main git merge --no-ff --log feature/login
The team wants "one PR and one commit on main", but is worried about losing details. What would you suggest?
Use squash merge to satisfy "one PR, one commit". At the same time: the PR should be small (M6), and the details should be kept in the PR page and review records; squash commit information should be written according to Conventional Commits, with the PR number andCo-authored-by:;Delete the branch immediately after merging. If the team needs to bisect fine-grained commits, use "rebase -i finishing + merge commit (--no-ff) before PR" instead.git log --first-parentGet the same clean backbone view.
Verified instructional videos
Official documentation
Video storyboard (approximately 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: A commit chain A-B, the main label is attached to B; C and D grow from B, and the feature label is attached to D.
Narrator: When main itself has no new commits, the merge only needs to slide the main label forward to D - this is called fast forward and does not generate any new commits.
Screen: There is an extra E on main, indicating a fork in history; B flashes yellow, marking merge base.
Narrator: When there are new commits on both sides, Git first finds the common ancestor, and then compares the changes from the ancestor to both sides.
Screen: Three tree icons (base, ours, theirs) merge into a funnel, generating a red dot M, with two parent arrows extending from M.
Narrator: A three-way merge produces a merge commit with two parent commits. The first parent is the current branch and the second parent is the merged branch.
Picture: four side-by-side small pictures: ff, no-ff, squash, rebase, and finally three merge buttons on the PR page.
Narrator: The snapshots are the same, but the shape of history is different. Which merger method is chosen is the team's agreement on history.
Module 2 · Conflict Resolution and Rerere
- Read conflict markers
<<<<<<</|||||||/=======/>>>>>>>, knowing whether each paragraph comes from base, ours or theirs. - Understanding conflicts in indexesstage 1(base)/ 2(ours)/ 3(theirs), can use
git ls-files -u、git show :2:file、git checkout --ours/--theirs。 - Configuration
merge.conflictStyle zdiff3withgit mergetool, turn onrerereLet Git remember and automatically reuse your conflict resolutions.
What: When will conflict occur?
A three-way merge compares base→ours to base→theirs by hunk (adjacent block of changed lines).Both sides modified the same area but in different ways.produced whenContent conflict(content conflict). In addition there arestructural conflict: Modify and delete at the same time (modify/delete); add files with the same name on both sides (add/add); rename, modify or rename both sides to different names (rename/rename); change binary files on both sides.
Why: Why doesn’t Git decide for you?
Git only understands lines of text, not semantics.I have been seenChange tovisited Still counted, only a human (or tester) knows which pair. In turn, be wary of:No textual conflict does not mean no semantic conflict——The function signature was changed on one side, and the call of the old signature was added on the other side. The merge was "successful" but the code compilation failed. Therefore, tests must be run after the merge (CI will also run the "merge result" once before the PR merge).
How: What does the conflict scene look like?
When there is a conflict, Git does three things: ① Write the conflict mark to the workspace file; ② The path in the index is no longer stage 0, but three blobs of stage 1/2/3 are stored at the same time; ③ WriteMERGE_HEAD(merged) or rebase/cherry-pick's state directory.git status show both modified(short formUU)。
Conflict stylemerge.conflictStyle | Show content | Evaluation |
|---|---|---|
merge(default) | ours segment + theirs segment | You can’t see “what it was” and it’s hard to tell who changed what. |
diff3 | ours + ||||||| base + theirs | Being able to see common ancestors makes judgments more accurate. |
zdiff3(2.35+,“zealous diff3”) | Same as diff3, but moves the same first and last lines on both sides out of the conflict area | Recommended: The conflict area is smaller while retaining ancestral information |
Three stages in the index
| stage | meaning | in merge | in rebase/cherry-pick | View |
|---|---|---|---|---|
| 1 | common ancestor base | merge base | The parent commit of the replayed commit | git show :1:path |
| 2 | ours | Current branch (HEAD) | Upstream/New Base Point(New history under construction) | git show :2:path |
| 3 | theirs | merged branches | Your own commit being replayed | git show :3:path |
git checkout --theirs fileWhat you get isyour ownversion.Standard process for resolving conflicts
git statusSee which files conflict;git diff(Show combined diff in case of conflict).- Edit the file to remove the mark and write the correct content; or
git checkout --ours/--theirs pathTake one side of the entire document; orgit mergetool。 git add pathMarked resolved (stage 1/2/3 → stage 0). Available since Git 2.56git add --resolved: Only cache resolved conflict paths and abort when residual conflict markers are found - avoid<<<<<<<Commit it in.- Run the test and then
git commit(merge) orgit rebase --continue/git cherry-pick --continue。 - Regret:
git merge --abort/git rebase --abort; Just want to redo a certain file:git checkout -m path(Regenerate conflict markers).
rerere:reuse recorded resolution
turn onrerere.enabledFinally, Git records the "preimage" (preimage) of the conflict when it occurs, and records the "postimage" (postimage) after you resolve and commit it, which is stored in.git/rr-cache/. meet next timesame conflict(For example, when repeatedly rebasing long-term branches, redoing merges after undoing, and doing the same integration on multiple branches), the previous solution is automatically applied. By default, it only changes the workspace and does not automaticallygit add(can be setrerere.autoUpdate true), you still have a chance to check.
When: Select tool
- Small conflict: Editor + zdiff3 is the fastest; VS Code and JetBrains have built-in three-column merge editors.
- Large files or many conflicts:
git mergetool(merge.toolCan be setvimdiff、meld、vscode、kdiff3etc.). - Generated files (lock files, compiled products): Do not merge manually, take one side and regenerate (such as
git checkout --theirs package-lock.json && npm install)。 - Recurring conflicts: rerere + make branches shorter-lived (M6).
git addIt just resolves the conflict”——git addIt just tells Git "I have processed this file", and if there is still a conflict mark in the file, it will still be temporarily stored (so added in 2.56--resolvedinspection). ② “The fewer conflicts, the better, so use-X ours"Automatically resolve" - that is to discard the other party's modifications without looking at the content. ③ "rerere will automatically commit for me" - no, it only pre-fills the solution results.Figure 2-1 The status of workspace, index and HEAD when conflict occurs
Figure 2-2 Recording and reuse of rerere
Interaction: Conflict Resolver (observe workspace and index changes)
Scene: mainI have been seenChange tocounted, feature/a change it tovisited. Select your operation type (merge or rebase - note that the meaning of ours/theirs changes), then select your solution, then click "git add" and "continue". Below shows the index entries and the actual output you would see.
Core commands and parameters
| command | function | Description |
|---|---|---|
git status / git diff | List conflicting files / combine diff | git diff --name-only --diff-filter=UList only conflicting files |
git ls-files -u | List unmerged index entries (stage 1/2/3) | git show :1:pathView base version |
git checkout --ours/--theirs path | Take one side of the entire file | Still need togit add;Equivalent new commandgit restore --ours path |
git checkout -m path | Regenerate conflict markers | Change the mess and want to start over;--conflict=zdiff3Interchangeable styles |
git mergetool | Solve them one by one using the configured merge tool | merge.tool、mergetool.keepBackup false(leaving no .orig) |
git add --resolved | Stage only resolved conflict paths (2.56+) | Abort when remaining conflicting tokens are found |
git rerere status / diff / forget | View the path of rerere records / Differences between current and recorded / Delete wrong records | rerere.enabled true、rerere.autoUpdate |
git log --merge -p path | Show only the commits that caused the conflict | Find out "why the other party changed it like this" |
git config --global merge.conflictStyle zdiff3 git config --global rerere.enabled true git config --global merge.tool vscode git config --global mergetool.vscode.cmd 'code --wait --merge $REMOTE $LOCAL $BASE $MERGED' git config --global mergetool.keepBackup false
VS Code--mergeReceive the four paths of the two input versions, the baseline version, and the result file in order toVS Code Documentationshall prevail; usevimdiff、meldWhen waiting for a tool with built-in support, justgit config merge.tool meld, no need to write cmd.
git merge feature/a git status --short git ls-files -u sed -n '9,18p' app.py
Auto-merging app.py
CONFLICT (content): Merge conflict in app.py
Automatic merge failed; fix conflicts and then commit the result.
Recorded preimage for 'app.py'
UU app.py
100644 8c3254bd25f76f60558b1968574f261c31e3d59a 1 app.py
100644 65b0d59d7efa6b0a58019bc3c16135273954b832 2 app.py
100644 62119aae375bc42ceb40769b6b05209ffb694cd0 3 app.py
@app.route("/")
def hello():
count = redis.incr("hits")
<<<<<<< HEAD
return f"Hello from myapp! I have been counted {count} times.\n"
||||||| ae12701
return f"Hello from myapp! I have been seen {count} times.\n"
=======
return f"Hello from myapp! I have been visited {count} times.\n"
>>>>>>> feature/a
How to read:The HEAD section is ours,|||||||The segment is the merge base (the following ae12701 is the ancestor commit),======= Arrive >>>is theirs. After comparison, we can see that base is seen, and both sides are changed to different words (counted/visited) - people need to decide.Recorded preimageDescription rerere is enabled.
Experiment 2: Create conflicts → zdiff3 resolution → rerere automatic reuse (about 6 minutes)
cd ~/git-lab/myapp git config merge.conflictStyle zdiff3 git config rerere.enabled true git switch -c feature/a sed -i 's/been seen/been visited/' app.py git commit -qam "feat: say visited instead of seen" git switch main sed -i 's/been seen/been counted/' app.py git commit -qam "feat: say counted instead of seen"
git merge feature/a git ls-files -u git show :1:app.py | grep 'return f' git show :2:app.py | grep 'return f' git show :3:app.py | grep 'return f'
return f"Hello from myapp! I have been seen {count} times.\n"
return f"Hello from myapp! I have been counted {count} times.\n"
return f"Hello from myapp! I have been visited {count} times.\n"app.py, delete the conflict mark and keep onlyvisitedThat line. Or use the command:git checkout --theirs app.py # In merge theirs = feature/a = visited
grep -n '[<=>|]\{7\}' app.py || echo "No residual conflict mark"
git add app.py # Git 2.56+ available: git add --resolved
git commit --no-edit
Updated 1 path from the index No residual conflict tags Recorded resolution for 'app.py'. [main 65a4b6d] Merge branch 'feature/a'
git reset --hard HEAD~1 git merge feature/a git diff # The conflict has been automatically resolved, but the file is still in the "unmerged" state git status --short # Still showing UU
Auto-merging app.py CONFLICT (content): Merge conflict in app.py Automatic merge failed; fix conflicts and then commit the result. Resolved 'app.py' using previous resolution. UU app.py
rerere wrote the file as the last solution result, but did not do it for yougit add. After checking that everything is correctgit add app.py && git commit --no-edit。
git merge --abort; git merge feature/a git rerere forget app.py # Delete the record first and let the conflict reappear git checkout -m app.py git mergetool --tool=vimdiff # Or the tool you configured; :wqa Save and exit
git add app.py && git commit --no-edit git log --oneline --graph -4 git branch -d feature/a
Case 1: Conflict tag is committed to main, service startup fails
Question:Developers miss one thing when resolving conflicts>>>>>>>, directlygit add .After pushing, Python reportsSyntaxError。Method:Enable pre-commit locallycheck-merge-conflictHooks (Lesson 5), CI Plusgit diff --check(It also reports conflict flags); used after the team upgrades to Git 2.56git add --resolvedinstead ofgit add .。Effect:Conflict markers are intercepted before commit.
Case 2: Long-term integration branch is rebased weekly to repeatedly resolve the same conflicts
Question:A platform upgrade branch spanning three months was rebased to main weekly, resolving the same conflicts on the same configuration files each time.Method:turn onrerere.enabled;Split the conflict hotspot files (such as splitting the routing registry by module); Better yet, split the upgrade into multiple small PRs that can be merged independently, and use feature switches to hide unfinished functionality (Lesson 6).Limitations:rerere only recognizes "exactly the same conflict block", and it still needs to be solved manually after the context changes.
Case 3: package-lock.json conflict
Question:The two developers each added dependencies, and the lock file conflicted with thousands of lines.Method:Without manual merging:git checkout --theirs package-lock.json(or ours) and then renpm installgenerate, thengit add;Also available in.gitattributesSet up a custom merge driver for lock files in .Principles:Build file conflict → take one side + regenerate + run test.
Common errors and solutions
error: Committing is not possible because you have unmerged files.
Reason:There are also paths in stage 1/2/3 status.
git diff --name-only --diff-filter=U
Fix:Solve one by one andgit add;If you don’t want this merger, justgit merge --abort。
CONFLICT (modify/delete): config.py deleted in feature and modified in HEAD.
Reason:One side deleted the file and the other side modified it.
Fix:Confirm whether to retain: Reservedgit add config.py, use to deletegit rm config.py. If the other party renamed the file and the changes were not recognized, you can try-X find-renames=30%Re-merge.
error: you need to resolve your current index first
Reason:Before the conflicts of the last merge/rebase are resolved, branch off or merge again.
git status # will show You have unmerged paths / rebase in progress
Fix:Complete (add + commit/--continue) or abort (--abort) the current operation.
I used --ours in rebase, but my modifications disappeared.
Reason:In rebase, ours is the upstream (new base point), and theirs is your replayed commit.
Fix:Not yet continue:git checkout --theirs pathorgit checkout -m pathStart over; already continue: usegit reflogFind the commit before rebase (M8 troubleshooting tree).
rerere automatically applied an incorrect solution
git rerere forget app.py git checkout -m app.py # Regenerate conflicts and resolve them manually
If you want to clear everything: Delete.git/rr-cacheDirectory.
1. When mergingdocs/api.mdIf there is a conflict, you are sure to adopt the entire version of the merged branch and write the command.
git checkout --theirs docs/api.md git add docs/api.md git commit --no-edit
2. List all currently conflicting files and check whether conflict marks remain in the workspace.
git diff --name-only --diff-filter=U git diff --check # Report leftover conflict marker and whitespace errors
There are no conflicts in the merge, but CI fails to compile on the merged main. What could be the reason? How to prevent it?
Semantic conflict: For example, Aget_user(id)Change toget_user(id, tenant), B added in another fileget_user(id)call. The textual layers do not overlap and cannot be discovered by Git. Prevention: PR must be based on latest main tests (platform's "branch must be latest" requirement or merge queue, Lesson 3); local before merginggit fetch && git rebase origin/mainPost-run testing; keep PRs small and short-lived.
Verified instructional videos
No independent short verified video was found specifically explaining rerere, the FOSDEM talk above contains relevant content.
Official documentation
- git-merge: How conflicts are presented
- git-mergetool
- git-rerere
- Pro Git 7.9 Rerere
- Pro Git 7.8 Advanced Merging
Video storyboard (approximately 90 seconds)
Picture: The same line of code seen, the left side is changed to counted, the right side is changed to visited, the two arrows collide together and sparks appear.
Narrator: Both sides have changed the same place but in different ways. Git will not choose for you. This is a conflict.
Screen: Three drawers 1, 2, and 3 appear under the same file name in the index cabinet, labeled base, ours, and theirs respectively.
Narrator: During a conflict, the index keeps three versions of the same file. After git add, the three drawers are merged into one.
Screen: Comparison of ordinary conflict markers and zdiff3 markers on the left and right. In zdiff3, there are more ancestor segments in the middle.
Narrator: With zdiff3 enabled, you can see what was originally there, making it much easier to tell who changed what.
Image: Notebook records solutions and automatically fills them in the next time the same conflict occurs.
Narrator: rerere Remember the way you resolved the conflict, and it will be automatically reused next time you encounter the same conflict, but it will still be committed after you check it.
Module 3 · Rebase rebase and interactive rebase
- Explain the execution process of rebase: find the merge base → collect the unique commits of this branch → check out the new base point → cherry-pick one by one → move the branch pointer; and why the hash of the new commit must be different.
- say and obeygolden rule: Don't rewrite commits that others have already built on their work (history that has been pushed to shared branches).
- Skilled use
git rebase -ipick/reword/edit/squash/fixup/drop, matchgit commit --fixupwith--autosquashOrganize PR; use--update-refsTo maintain overlay branches, use--ontoMigrate a commit.
What: rebase does
Execute on featuregit rebase main: "Commit the features that are on feature but not on main, in orderreapplyto main 's latest commit, and then have feature point to the last new commit". The original commits C and D were not modified (Git objects are immutable), but C' and D' were generated; the old commits are still in the object library and can be retrieved from the reflog (the default is to retain at least 30 days for unreachable entries, Lesson 7).
Why: Why the hash must change
commit hash = hash(tree +parent+ author + committer + message). After replay, the parent has changed (from B to E), and the committer time has also changed, so the hash must be different - even if the changes are exactly the same.This is where the dangers of rebase come from: C and D in other people's hands and C' and D' that you pushed are completely different commits in Git's view.
How: execution steps (corresponding to Git output)
- Calculate upstream:
git rebase mainMedium upstream = main; when the parameter is omitted, the upstream configured by the current branch is used (@{upstream})。 - Collect commits to replay:
git log main..feature(And by default, commits whose patch content already exists in the upstream, such as those that have been cherry-picked, are skipped). Merge commits are discarded by default and history linearization (needs to be retained)--rebase-merges)。 - Detach HEAD to the new base point main and cherry-pick one by one (output
Rebasing (1/2)). Stop when conflict: resolve →git add→git rebase --continue;or--skipSkip this commit,--abortBack to where we started. - After all success
refs/heads/featureChange to the last new commit:Successfully rebased and updated refs/heads/feature.,ORIG_HEADPoints to the location before rebase.
golden rule
✔ Yes: Submissions that have not been pushed locally; only feature branches that you use yourself (pushed for backup or PR) - use after rewriting
--force-with-leasePush(M5).✘ Not allowed:
main、release/*Waiting for shared branches; branches that colleagues have pulled down and continued to commit on.interactive rebase rebase -i
git rebase -i mainwill open a todo list (Oldest commit on top, executed from top to bottom), one command per line:
| command | function | Typical uses |
|---|---|---|
pick (p) | Use as is | Default |
reword (r) | Use, but stop to modify the commit message | Change to Conventional Commits format (M7) |
edit (e) | Use, then pause for you to modify (amend or split) | Split a commit that is too large:git reset HEAD~Commit it in multiple batches, and then--continue |
squash (s) | Merge into previous commit,Merge two pieces of commit informationand open the editor | Consolidate several related commits into one and keep the description |
fixup (f) | Merge into previous commit,Discard this commit(fixup -CThe information committed here will be used instead) | Fixes such as "fixing typos" and "fixing tests" |
drop (d) | Discard the commit (removing this line has the same effect) | Remove debugging code and temporary notes |
exec (x) | Run shell command, stop on failure | git rebase -i --exec "make test" main: Verify that each commit passes the test |
break / update-ref / label / reset / merge | Pause / update other branches / for--rebase-merges | Advanced |
--autosquash: Let Git automatically schedule fixup
When you want to modify the first commit during review, you don’t have to manually edit the todo:git commit --fixup=<sha>The generated information isfixup! <Original title>commit; aftergit rebase -i --autosquash mainwill automatically move it below the target commit and mark it asfixup。--squash=<sha>Correspondsquash!;--fixup=amend:<sha>The target's commit information can be modified at the same time;--fixup=reword:<sha>Just change the information. settingsrebase.autoSquash trueEffective by default; non-interactive since Git 2.44git rebase --autosquashThey will also be processed.
--update-refs:stacked branches
If feature/pr-part2 is based on feature/pr, part2 still points to the old commit after rewriting feature/pr. Execute on part2git rebase -i --update-refs main, will appear in todoupdate-ref refs/heads/feature/pr, when rebase ends, Git updates these two branches at the same time (introduced in Git 2.38, you can setrebase.updateRefs true)。
--onto: Migrate a section of commit
git rebase --onto <newbase> <upstream> <branch>: takeupstream..branchThis commit is replayed on newbase. Typical scenario: feature-b was originally separated from feature-a, and now we just want to move b’s own commits to main:git rebase --onto main feature-a feature-b。
When: rebase or merge?
| scene | Recommended | Reason |
|---|---|---|
| Synchronize the latest changes to mainownfeature branch | git rebase origin/main | No "Merge main into feature" noise commit, PR diff is clean |
| Organize your commits before PR | rebase -i --autosquash | Reviewers see a logical sequence of commits |
| Feature branches shared by multiple people | merge (or rebase after coordination) | Follow the golden rule |
| Merge features into main | Team agreement: PR merge button (M6) | Don't rebase main itself locally |
Figure 3-1 rebase: replay one by one, old commits become unreachable objects
Figure 3-2 --onto and --update-refs
Interaction: rebase -i's todo editor (preview rewritten history)
Below is a branch ready for PR (oldest on top). Select commands for each line, use ↑↓ to adjust the order, or click "autosquash" to let Git automaticallyfixup!Commits are queued below the target. Click "Perform rebase" to see the results: which commits were merged, which were discarded, and which got new hashes.
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git rebase <upstream> | Replay the current branch onto upstream | --continue / --skip / --abort / --quit |
git rebase -i <base> | Interactively organize commits after base | -i HEAD~3Organize the last 3;--rootinclude root commit |
git commit --fixup=<sha> | generatefixup! Commit | --fixup=amend:<sha>、--fixup=reword:<sha>、--squash=<sha> |
--autosquash | Automatically sort and tag fixup!/squash! | rebase.autoSquash true |
--update-refs | Also update other branches pointing to the rewritten commit | rebase.updateRefs true(2.38+) |
--onto <newbase> | Port upstream..branch to newbase | --keep-base: The base point remains unchanged, only sorting and commit |
--exec "<cmd>" | Run command after each commit | Verify each commit builds |
--rebase-merges | Preserve merge structure within branches | Linearizes by default (discarding merge commits) |
git range-diff | Compare the commit sequences of the two versions before and after rebase | git range-diff main ORIG_HEAD HEADor@{1}...HEAD |
Read-only demo:This paragraph is the same as the one in "Comparison before and after review" below.feature/pr、feature/pr-part2They are two additional overlay branches created by the courseware author. They will not be created in this lesson, so there is no need to run them - just read the output; practice Experiment 3 on the "Experiment" page.
# Demo (doesn’t have to be run): two overlay branches + one fixup!, one cleanup git log --oneline main..feature/pr-part2 GIT_SEQUENCE_EDITOR=cat git rebase -i --autosquash --update-refs main # cat only prints todo and does not modify it
5b6cb8d feat: part2 6140466 fixup! feat(util): add helper 3246ca7 chore: tmp notes d36244d feat(util): add sub 2bcfb92 wip f7ee252 feat(util): add helper pick f7ee252 # feat(util): add helper fixup 6140466 # fixup! feat(util): add helper pick 2bcfb92 # wip pick d36244d # feat(util): add sub pick 3246ca7 # chore: tmp notes update-ref refs/heads/feature/pr pick 5b6cb8d # feat: part2 … Successfully rebased and updated refs/heads/feature/pr-part2. Updated the following refs with --update-refs: refs/heads/feature/pr
How to read:fixup! The commit is automatically moved to line 2 and marked asfixup;update-refThe position of the line is where feature/pr will point to in the future.GIT_SEQUENCE_EDITOROnly controls the todo editor (GIT_EDITORControl commit message editor), which can be used in scripts to edit todos non-interactively, e.g.GIT_SEQUENCE_EDITOR="sed -i '3s/^pick/drop/'"。
Split an overly large commit (edit)
git rebase -i main # Change the target commit line to edit git reset HEAD~ # After stopping: Undo the commit and return the changes to the workspace git add util.py && git commit -m "feat(util): add helper" git add notes.txt && git commit -m "docs: notes" git rebase --continue
Comparison before and after review
git range-diff main feature/pr@{1} feature/pr # Demonstration (no need to run), the branch is the same as above
Outputting=Indicates that the committed content has not changed,!Indicates changes,</>Indicates deleted/newed commits. Reviewers use it to confirm "what exactly did you change in force-push".
Lab 3: Organize a messy branch into a reviewable PR (~7 minutes)
cd ~/git-lab/myapp && git switch main
git switch -c feature/util
printf 'def add(a, b):\n return a+b\n\n' > util.py # Leave a blank line at the end so that fixup can fit in cleanly
git add util.py && git commit -qm "feat(util): add helper"
echo "print('debug')" >> util.py && git commit -qam "wip"
printf '\ndef sub(a, b):\n return a - b\n' >> util.py && git commit -qam "add sub"
echo "todo: tests" > notes.txt && git add notes.txt && git commit -qm "chore: tmp notes"
git log --oneline main..a + bformat. Use fixup to commit the response instead of amend directly:sed -i 's/a+b/a + b/' util.py git add util.py git commit --fixup=$(git log --format=%h --grep='add helper' -1) git log --oneline main..
a91c2d0 fixup! feat(util): add helper 7be31f2 chore: tmp notes 4c0de11 add sub e2a77b9 wip 19f3c4a feat(util): add helper
wipTo remove debugging code, you need to use drop - but will drop cause conflict with the subsequent add sub? Give it a try! ):git rebase -i --autosquash main
pick 19f3c4a feat(util): add helper fixup a91c2d0 fixup! feat(util): add helper drop e2a77b9 wip reword 4c0de11 add sub drop 7be31f2 chore: tmp notes
After saving: dropping wip will make the context of "add sub" inconsistent with the current file, and may cause conflicts on util.py - this is the embodiment of "each commit is a patch, replayed one by one". Solution: Delete the conflict mark andprint('debug'), retain the sub function, and thengit add util.py && git rebase --continue. You can also directly use the following command to write the resolved content and continue:
printf 'def add(a, b):\n return a + b\n\ndef sub(a, b):\n return a - b\n' > util.py && git add util.py && git rebase --continue
Then enter reword: change the information tofeat(util): add sub helper。
git log --oneline main.. cat util.py git range-diff main ORIG_HEAD HEAD | head -20
b3e9a17 feat(util): add sub helper
0c4d6e2 feat(util): add helper
def add(a, b):
return a + b
def sub(a, b):
return a - b
Note ORIG_HEADIt may be updated by internal steps during rebase; if the range-diff result is incorrect, usefeature/util@{1}(previous position in reflog) instead.
git rebase main --exec "python3 -c 'import ast,sys; ast.parse(open(\"util.py\").read())'"
If any commit fails, it will stop and let you fix it.--continue. Replace it in real projectsmake testorpytest -q。
git switch -c feature/util-ext echo "def mul(a, b): return a * b" >> util.py && git commit -qam "feat(util): add mul" # Simulation feature/util has been squashed into main (PR #7): git switch main && git merge --squash feature/util && git commit -qm "feat(util): add/sub helpers (#7)" git switch feature/util-ext # Only move util-ext's own commits to main: git rebase --onto main feature/util feature/util-ext git log --oneline main..feature/util-ext # Only 1 commit left git switch main
Case 1: Someone rebased the shared develop branch and pushed it
Question:Friday a member on developrebase -iCompress commits andgit push -f, a large number of duplicate commits and conflicts appeared after others pulled, and two commits of a colleague were overwritten.Processing:The overwritten commit is retrieved from the colleague's local reflog or his clone; others executegit fetchfor later usegit rebase --onto origin/develop < old origin/develop> my-branchMigrate your own work (or rely on Git's fork-point detection when pulling).Prevention:Forced push for shared branches is prohibited on the platform (Lesson 3); only for personal use--force-with-lease(M5)。
Case 2: Force-push during review prevents reviewers from seeing what has been changed
Question:Developers amend + force-push every time they modify, and reviewers have to re-read the entire PR every round.Method:The team agrees that only additional additions will be made during the review periodfixup!Commit and execute after passing the reviewgit rebase -i --autosquashPush again; if force-push is needed, post it in PR commentsgit range-diffSummary.Effect:Each round of review only looks at increments.
Case 3: stacked PRs
Question:A large function is divided into three PRs (data model → API → UI) that depend on each other in sequence. After modifying the first one, you need to manually rebase the last two.Method:Execute on the topmost branchgit rebase -i --update-refs origin/main, update three branches at a time, and then usegit push --force-with-lease origin pr1 pr2 pr3push. After the first PR is merged (squash), usegit rebase --onto origin/main pr1 pr2Move subsequent branches over.
Common errors and solutions
error: could not apply 16c3666... fixup! feat(util): add helper
Reason:Conflict when replaying a commit (commonly caused by reordering or dropping commits it depends on).
git status # Display interactive rebase in progress and Last command done git diff # See conflicts # After solving: git add <file> && git rebase --continue # Don't want this commit: git rebase --skip Abort the entire rebase: git rebase --abort
fatal: It seems that there is already a rebase-merge directory, and I wonder if you are in the middle of another rebase.
Reason:The last rebase did not end (the terminal was closed or the process was interrupted),.git/rebase-mergeStill.
Fix:git rebase --continueorgit rebase --abort;Confirm that there is no rebase in progress.git rebase --quit(Keep current HEAD, clear status only).
After rebase, git push was rejected:! [rejected] feature -> feature (non-fast-forward)
Reason:Rebase rewrites the pushed commit and the remote branch is no longer an ancestor of the local branch.
Fix:After confirming that this is your own branchgit push --force-with-lease --force-if-includes(M5)。Don'texecute git pull——It will merge old commits back, creating duplicate commits.
Commits repeated twice after rebase (same information, different hashes)
Reason:After rebase, the remote branch of the old version is pulled/merged, or someone else merges it based on the work of the old commit.
git log --oneline --graph -15 git reflog -15
Fix:When not pushedreflog entry > when git reset --hard <rebase completes; Pushed needs to be coordinated with the team.
hint: Waiting for your editor to close the file... then gets stuck
Reason:core.editorThe pointed graphical editor does not add a wait parameter (such as VS Code requirescode --wait)。
Fix:git config --global core.editor "code --wait";or use in terminalnano/vim。
1. Review requests to modify commits on your branch4c0de11, write the command sequence of "add patch first, then automatically merge after passing the review".
git add -p git commit --fixup=4c0de11 git push # Reviewers only see the increment # After passing the review: git rebase -i --autosquash origin/main git push --force-with-lease --force-if-includes
2. feature-b is branched from feature-a, which has been squashed into main. Only commits unique to b are moved to the latest main.
git fetch origin git rebase --onto origin/main feature-a feature-b
A colleague said: "I just pulled it down and found that the branch you rebase has forked from my local branch, and there are a bunch of duplicate commits." How should you help him recover? How to avoid it in the future?
Recovery: Let him go firstgit reset --hard ORIG_HEADOr go back from reflog to before pull; thengit fetch, use git rebase --onto origin/feature < old origin/feature commit > his-branchMigrate only his own new commits (orgit pull --rebase, Git will use fork-point to try to identify the rewritten upstream commit). Avoid: Do not rebase shared branches; communicate in advance when finishing needs to be executed by one person at the same time; the platform prohibits forced push of shared branches; personal force-push is always used--force-with-lease。
Verified instructional videos
Official documentation
- git-rebase
- Pro Git 3.6 Rebasing (including "The Perils of Rebasing")
- Pro Git 7.6 Rewriting History
- git-range-diff
Video storyboard (about 100 seconds)
Picture: The history of bifurcation, the C and D of feature are "peeled off" like transparent stickers.
Narrator: rebase first finds the common ancestor and collects the unique commits on your branch.
Screen: Each sticker is posted to the end of main. A new hash number appears with each sticker, and the old C and D become gray dotted lines.
Narrator: Each commit is reapplied once, and if the parent commit changes, so does the hash. The old commits are still there, just no one points to them.
Screen: Todo list, pick lines were changed to fixup, drop, reword, and the resulting history changed from five commits to two neat commits.
Narrator: Interactive rebasing allows you to organize messy commits into a logical sequence before opening a PR.
Screen: There is a prohibition sign on the shared main branch, and a warning of repeated commits appears on a colleague's computer.
Narrator: Golden rule: Don't rewrite someone else's commit based on their work. Your own branch can be rewritten, but shared branches cannot.
Module 4 · cherry-pick, stash and worktree
- use
git cherry-pickTo copy the specified commit to another branch (hotfix move, backport), use-xRecord the source and know the differences and risks between it and merge (duplicate commit). - understand
git stashActually creates 2–3 commit objects (workspace, index, optional untracked files), will usepush -m、-u、list、show -p、apply/pop、branch。 - use
git worktreeCheck out different branches in different directories at the same time (sharing the same object library), replacing "stash → cut branches → and then cut back".
What: What problems do the three tools solve?
| Tools | Problem solved | essence |
|---|---|---|
cherry-pick | "I only want that one fix, not the whole branch" | Computes the diff of the target commit relative to its parent commit, applies it to the current HEAD and generatesnew commit(new hash, same as rebase's single step) |
stash | "When you are halfway through the changes at hand, you have to immediately deal with other things." | Save changes to the workspace and index as special commits, hung inrefs/stash(stack structure, relying on reflog to record multiple entries), and then restore the workspace to HEAD |
worktree | "I need to open two branches at the same time (long-term testing, emergency repair, comparison)" | Add a working directory to the same repository, with independent HEAD and indexes, but shared object libraries and references |
Why / How:cherry-pick
git cherry-pick <sha>: Apply the changes of sha to sha^. Conflict handling is the same as rebase: resolve →git add→git cherry-pick --continue;--abort/--skip。-x: Append at the end of the commit information(cherry picked from commit < full hash >). When picking from a public branch to another public branch (such as main → release/1.2)Be sure to use, to facilitate auditing.- Scope:
git cherry-pick A..B(excluding A),A^..B(including A);-n/--no-commitOnly apply without committing (Git 2.56 documentation makes it clear: it will not be set at this timeCHERRY_PICK_HEAD)。 - Pick and merge commit needs
-m 1Specify which parent is the main thread.
Why / How:stash
git stash pushCreate a "WIP commit" W: whose first parent is HEAD and whose second parent is commit I which records the index state; use-uThere are untracked files when there is a third parent U record.refs/stashpoints to the latest W, older entries are kept inrefs/stashin the reflog, so it is calledstash@{0}、stash@{1}。
| command | Effect |
|---|---|
git stash push -m "msg" | Save changes to tracked files (workspace + index);-uIncludes untracked files;-- pathCollect only some files;--stagedOnly collapse the temporarily saved part |
git stash list / show -p stash@{1} | View the stack / view the diff of an item |
git stash apply / pop | Apply; pop = drop after successful application.pop does not delete entries in case of conflict |
git stash branch <name> [stash] | Open a new branch from the HEAD when stash was created and apply it, which is least likely to cause conflicts. |
git stash drop / clear | Delete an entry (available after accidental deletion)git fsck --unreachable | grep commitretrieve) |
Why / How:worktree
git worktree add ../myapp-hotfix -b hotfix/1.1.1 v1.1.0directory will be created../myapp-hotfix, of which.gitis a file pointing to the main repository.git/worktrees/myapp-hotfix/(Storing the working tree's own HEAD and index). Objects, branches, tags, and configurations are all shared, so after a commit is made in the hotfix directory, the commit can be seen immediately in the home directory.Limitations:The same branch cannot be checked out in two working trees at the same time (to avoid two indexes covering each other), use--detachOr open another branch.
When: Which one to choose?
| scene | Recommended |
|---|---|
| Halfway through the change, it takes 2 minutes to pull the latest code/cut branches | git stash(Or commit a WIP commit directly and amend/fixup later) |
| Emergency fix took an hour while local tests were running | git worktree add |
| Bring a fix on main to release/1.2 | git cherry-pick -x |
| Want all changes from another branch | merge or rebase, don’t cherry-pick one by one |
git stashNew files will be closed" - not by default, required-u. ③ "worktree is the second clone" - No, it shares the object library and is used when deletinggit worktree remove, don’t just delete the directory (otherwise you need togit worktree prune)。Figure 4-1 cherry-pick: copy a patch
Figure 4-2 The internal structure of stash and the directory relationship of worktree
Interaction: stash stack and worktree simulator
You are modifying the README (uncommitted) on main, and suddenly you need to fix the bug of online v1.1.0. Try the "stash route" and the "worktree route" respectively and observe the changes in the workspace, stash stack and worktree list.
Core commands and parameters
| command | function | Description |
|---|---|---|
git cherry-pick -x <sha>… | Copy the commit and document the source | -nNot committed;-m 1Pick and merge commit;--continue/--skip/--abort |
git cherry -v main feature | List commits in feature with "patch not yet in main" (+) and the existing (-) | Check if backport is complete |
git stash push -u -m "msg" [-- path] | Collapse changes | --staged、--keep-index、-p(interactive selection) |
git stash list / show -p / apply / pop / drop / branch | Manage stash stack | apply --indexRestore the temporary state at the same time |
git worktree add <path> [-b new] [commit-ish] | Add new working tree | --detach;The same branch cannot be checked out in two places |
git worktree list / remove / prune / lock | Manage working tree | remove --forceDiscard uncommitted changes |
cd ~/git-lab/collab/alice
echo tmp >> README.md
git stash push -m "wip readme"
git stash list
git stash show -p stash@{0}
git stash pop
Saved working directory and index state On main: wip readme
stash@{0}: On main: wip readme
diff --git a/README.md b/README.md
index 6cc66bd..fcf0ba6 100644
--- a/README.md
+++ b/README.md
@@ -3,3 +3,4 @@
A tiny Flask + Redis hit counter used throughout the Docker and Git courses.
Run locally: `docker compose up --build`
+tmp
…
Dropped refs/stash@{0} (dbed11836ef5c7efd54d4df135b6ec84ce1a5ca2)
git checkout -- README.md # End of demonstration: discard the tmp line and restore a clean workspace
git worktree add -b hotfix/1.1.1 ../alice-hotfix v1.1.0 # v1.1.0 from Lesson 1
git worktree list
cd ../alice-hotfix
sed -i 's/{"status": "ok"}/{"status": "ok", "service": "myapp"}/' app.py
git commit -qam "fix(health): include service name in healthz"
cd ../alice
git cherry-pick -x hotfix/1.1.1
git log -1 --format='%h %s%n%b'
Preparing worktree (new branch 'hotfix/1.1.1') HEAD is now at f4ac97b Merge branch 'hotfix/redis-timeout' /home/azureuser/git-lab/collab/alice db1616e [main] /home/azureuser/git-lab/collab/alice-hotfix f4ac97b [hotfix/1.1.1] [main 72c9ded] fix(health): include service name in healthz Date: Sun Nov 15 17:22:29 2026 -0500 1 file changed, 1 insertion(+), 1 deletion(-) 72c9ded fix(health): include service name in healthz (cherry picked from commit 9b649d00ea5cf938c3708e4ef3e129b9b244bd12)
Note:from cherry-pick outputDate:It is the author time of the original commit (the author information is retained, and the committer becomes you). This paragraph is just a demonstration. Please perform the following cleanup before doing the "Experiment" paging, otherwise Experiment 4 will fail because the branch and working tree already exist:
git worktree remove --force ../alice-hotfix; git branch -D hotfix/1.1.1; git reset -q --hard origin/main
Experiment 4: worktree hot repair + cherry-pick back to main + stash finishing (about 6 minutes)
cd ~/git-lab/collab/alice && git switch main && git pull -q echo "## Roadmap" >> README.md # Tracked file modifications echo "draft" > notes.txt # Untracked files git tag -l # v1.0.0, v1.1.0: v1.1.0 is running online git status -s
git worktree add -b hotfix/1.1.1 ../alice-hotfix v1.1.0
cd ../alice-hotfix
sed -i 's/{"status": "ok"}/{"status": "ok", "service": "myapp"}/' app.py
git diff # only changed the return value of healthz
git commit -qam "fix(health): include service name in healthz"
git log --oneline -1
cd ../alice && git status -s # The changes in the main workspace remain intactgit stash push -u -m "roadmap draft" git cherry-pick -x hotfix/1.1.1 git stash pop git log -1 --format='%h %s%n%b'
Saved working directory and index state On main: roadmap draft
[main 72c9ded] fix(health): include service name in healthz
Date: Sun Nov 15 17:22:29 2026 -0500
1 file changed, 1 insertion(+), 1 deletion(-)
…
Dropped refs/stash@{0} (3a054705ac63e978c8e76ea1dee78227b1cccf34)
72c9ded fix(health): include service name in healthz
(cherry picked from commit 9b649d00ea5cf938c3708e4ef3e129b9b244bd12)
If healthz on main has been modified (for example, a demonstration of "command" paging without cleaning it), cherry-pick will conflict - solve it according to the process of M2git cherry-pick --continue。
git cherry -v main hotfix/1.1.1
- 9b649d00ea5cf938c3708e4ef3e129b9b244bd12 fix(health): include service name in healthz
-Indicates that the patch already exists in main (albeit with a different hash).
git worktree remove ../alice-hotfix git worktree list git stash list # should be empty git checkout -- README.md && rm -f notes.txt # Discard demo changes (or commit them) git reset --hard origin/main # Discard the local cherry-pick commit and let M5 start from a clean main
Case 1: Maintaining backports for multiple release lines
Question:The product maintains three lines: 2.3, 2.4, and main at the same time. Security repairs require access to all of them.Method:Fix merge into main with PR; usegit cherry-pick -xOpen a backport PR for each release branch (many teams use robots to automatically generate it); use it before releasinggit cherry -v release/2.4 main | grep '^+'Check for omissions.Limitations:When the code differences between old versions are large, there are many cherry-pick conflicts, and manual rewriting of patches is required. At this time, the commit information still retains the source description.
Case 2: "Modifications lost" after stash pop conflict
Question:The developer had a conflict when popping, and executed it in a panic.git reset --hard, thinking stash is gone too.Facts:pop will not delete stash entries in case of conflict,git stash listStill visible; available even if droppedgit fsck --no-reflog | grep "dangling commit"Retrieve WIP after commitgit stash apply <sha>。Prevention:Work committed for more than a few minutes is committed as WIP; used in case of conflictgit stash branch。
Case 3: Using worktree to run tests in parallel in a large repository
Question:A complete test of a single repository takes 20 minutes, during which time branches cannot be cut.Method:Create a worktree for each long task (share an object library of several GB, no need to clone), run tests in the worktree, and continue development in the home directory; the task endsgit worktree remove. Many AI coding agents also use worktrees to keep multiple tasks from interfering with each other.
Common errors and solutions
error: could not apply 7c5610a... fix: hotfix / hint: after resolving the conflicts, mark the corrected paths
Reason:The context of the patch does not exist on the target branch or has changed.
Fix:Resolve conflicts →git add → git cherry-pick --continue;or--abort. Note that ours = current branch, theirs = selected commit.
The previous cherry-pick is now empty, possibly due to conflict resolution.
Reason:The change already exists in the current branch.
Fix:git cherry-pick --skip;You really need to commit it empty--allow-empty。
error: Your local changes to the following files would be overwritten by merge ... (stash pop)
Reason:The workspace has been modified in a way that conflicts with stash.
git stash branch recover-wip stash@{0} # Restore at the base point when stash was createdfatal: 'hotfix/1.1.1' is already used by worktree at '/home/…/alice-hotfix'
Reason:The same branch cannot be checked out in two working trees.
Fix:Go to that directory to work; orgit worktree remove;When the directory has been manually deletedgit worktree prune。
No local changes to save (new files are still there after stash)
Reason:The default stash does not contain untracked files.
Fix:git stash push -u;Ignore files required-a(Use with caution, it will include node_modules, etc.).
1. Commit the maina1b2c3d and e4f5a6bGo back to release/1.2 and document the source in the commit message.
git switch release/1.2 git cherry-pick -x a1b2c3d e4f5a6b
2. Collapse only the staged modifications and keep the unstaged parts in the workspace to continue editing.
git stash push --staged -m "staged part"
You are running a 30-minute integration test (depending on the current working directory), and an online fault needs to be fixed immediately and a PR opened. what will you do?
Don't stash or cut branches (this will break running tests). usegit fetch && git worktree add -b hotfix/x ../myapp-hotfix origin/mainRepair, commit,git push -u origin hotfix/xOpen a PR; if you need to enter the release branch after merging, thencherry-pick -x;finallygit worktree remove ../myapp-hotfix。
Verified instructional videos
No specific explanation foundgit worktreeFor verified videos, please refer to the official documentation and the storyboard below.
Official documentation
Video storyboard (approximately 90 seconds)
Screen: The last repair commit on main glows, the copier copies the same patch and pastes it on the release branch, with cherry picked from written on the corner of the sticker.
Narrator: cherry-pick copies the changes and generates a new commit. Use -x to note where it comes from.
Screen: The semi-finished products on the table are put into the drawer, the drawer is labeled stash@{0}, and the desktop is restored to cleanliness.
Narrator: stash saves the unfinished changes as a special commit and returns the workspace to a clean state. Add -u to new files.
Picture: A second door opens in the same repository, and two workbenches share a repository shelf.
Narrator: worktree opens a second working directory for the same repository, shares all objects, and is suitable for processing two branches at the same time.
Module 5 · Remote branches and tracking relationships
- Distinguish between three types of "main": in the remote repository
refs/heads/main, local remote-tracking branchrefs/remotes/origin/main, local branchrefs/heads/main;Know that only fetch/push will updateorigin/main。 - understand
git branch -vvwithgit status -sbof[ahead N, behind M]; usepush -uEstablish an upstream relationship; usefetch --pruneClean up deleted remote branches. - Proper configuration
pull.rebase, and only usegit push --force-with-lease --force-if-includesRewrite your own remote branch.
What: remote, remote-tracking branch, upstream
| concept | storage location | who will update it | Description |
|---|---|---|---|
| remote(like origin) | .git/configin[remote "origin"]:url + fetch refspec | git remote add/set-url | Just an "alias + mapping rule" |
Remote tracking branches origin/main | refs/remotes/origin/main | only fetch(including fetch inside pull) and successfulpush | Local read-only snapshot, cannot be committed directly (checkout will enter detached HEAD) |
| upstream(upstream / tracking) | branch.main.remote=origin + branch.main.merge=refs/heads/main | push -u、branch -u, automatically set when creating a local branch from a remote branch | Decide without parameterspull/push/statusCompare with whom; write@{u} |
The default fetch refspec is+refs/heads/*:refs/remotes/origin/*: Copy all remote branches to localrefs/remotes/origin/down(+Indicates that non-fast forward updates are allowed, so others forcefully push yourorigin/xwill also change).
Why: Why does status say “up to date” but is actually behind?
git statusThe comparison is between local main andlocal origin/main, it is not connected to the Internet. The precise meaning of "Your branch is up to date with 'origin/main'" is "consistent with the state you last fetched". So the first step in collaboration is alwaysgit fetch。
How: pull = fetch + integration
| Configuration/parameters | Behavior when local and remote forks | Evaluation |
|---|---|---|
pull.rebase false(--no-rebase) | After fetch, merge, resulting in "Merge branch 'main' of..." commit | Historically noisy |
pull.rebase true(--rebase) | After fetch, rebase your local commit toorigin/mainabove | RecommendedUsed for feature branches and daily synchronization |
pull.ff only(--ff-only) | You can only fast forward, and an error will occur if you fork. | Branches suitable for read-only tracking (like main on a CI machine) |
| None configured | Modern Git rejects and prompts when forkingfatal: Need to specify how to reconcile divergent branches. | Warning starts with Git 2.27; please configure explicitly |
pull.rebaseIt can also be set tomerges(Retain local merge commits when rebasing, which is equivalent to--rebase-merges)。rebase.autoStash trueIt can be automatically stashed before pull --rebase and restored automatically afterwards.
Force push: -f vs --force-with-lease vs --force-if-includes
| way | Check | risk |
|---|---|---|
git push -f | Without checking, directly overwrite the remote | Commits pushed by others during this period will be silently erased. |
--force-with-lease | Only the remote current value == your localorigin/<branch>Only covered ("I thought the remote was X, if not, don't move") | If you (or the IDE backend) justfetchpassed,origin/xUpdated to someone else's commit, the lease still passes → still overwrites other people's work |
--force-with-lease --force-if-includes(2.30+) | Extra check: The current value of the remote-tracking branch must have beenintegrate intoYour local branch (appears in the local branch's reflog) | Recommended combination:Fetch will also be rejected if other people's commits are not integrated. Can be setpush.useForceIfIncludes true |
A more rigorous way of writing it is to explicitly specify the expected value:git push --force-with-lease=feature/x:< expected old hash >, the safest among scripts.
When: Fixed actions for daily collaboration
- Start working:
git switch main && git pull(pull.rebase=true, there are usually no local commits on main, the result is fast forward) →git switch -c feature/xyz。 - First push:
git push -u origin feature/xyz(or setpush.autoSetupRemote true, first timegit pushThe upstream with the same name is automatically created). - Sync trunk:
git fetch && git rebase origin/main;After rewritinggit push --force-with-lease --force-if-includes。 - Regular cleaning:
git fetch --prune(orfetch.prune true); available starting from Git 2.56git branch --delete-mergedClean up local branches that have been merged into upstream.
git fetch"Will change my code" - no, fetch only updatesrefs/remotes/*The object library, workspace, and local branches are not moved. ② "After deleting the remote branch, other people'sorigin/xwill disappear automatically” - No, they are neededfetch --prune。③ “--force-with-lease"Absolutely safe" - when used alone, automatic fetch in the background will make it invalid, so add--force-if-includes。Figure 5-1 Main in three positions
Figure 5-2 Judgment of --force-with-lease and --force-if-includes
Interaction: Alice, Bob and remote repository synchronization simulator
Each column shows the commit chain at that location. Click the button to perform the action and observeorigin/mainWhen changes occur, when push is rejected, and how forced push overwrites other people's commits. The commit number simulates a hash.
Core commands and parameters
| command | function | Description |
|---|---|---|
git remote -v / git remote show origin | View remote and branch tracking status | showWill be able to connect to the Internet and list the stale branches |
git fetch [--prune] [--all] | Download objects and update remote-tracking branches | fetch.prune true |
git branch -vv / git branch -r | Local branches and their upstream and ahead/behind/remote-tracking branches | [origin/x: gone]Indicates that the remote has been deleted |
git push -u origin <branch> | Push and set upstream | push.autoSetupRemote true |
git branch -u origin/main | Set upstream for current branch | --unset-upstream |
git pull --rebase | fetch + rebase | pull.rebase true、rebase.autoStash true |
git push --force-with-lease --force-if-includes | Safely rewrite your own remote branches | push.useForceIfIncludes true |
git push origin --delete <branch> | Delete remote branch | The platform can usually be automatically deleted after merging the PR |
git rev-list --left-right --count main...origin/main | Calculate ahead/behind number | used in scripts |
cd ~/git-lab/collab/bob git push origin main # Alice has pushed first
To /home/azureuser/git-lab/collab/remote/myapp.git ! [rejected] main -> main (fetch first) error: failed to push some refs to '/home/azureuser/git-lab/collab/remote/myapp.git' hint: Updates were rejected because the remote contains work that you do not hint: have locally. This is usually caused by another repository pushing to hint: the same ref. If you want to integrate the remote changes, use hint: 'git pull' before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
git fetch git status -sb | head -1 git branch -vv
## main...origin/main [ahead 1, behind 1] * main bf0f390 [origin/main: ahead 1, behind 1] fix(health): report up status
How to read:(fetch first)It means that there are remote commits that are not in your local object library; if the push is rejected after fetch, it will be displayed.(non-fast-forward)。ahead 1, behind 1= Fork: You have 1 commit that the other party doesn't have, and the other party has 1 commit that you don't have.
git push --force-with-lease # Others have pushed, but you haven’t fetched it yet. git fetch git push --force-with-lease --force-if-includes # fetched but not integrated
! [rejected] feature/x -> feature/x (stale info) error: failed to push some refs to '…/myapp.git' ! [rejected] feature/x -> feature/x (remote ref updated since checkout) error: failed to push some refs to '…/myapp.git' hint: Updates were rejected because the tip of the remote-tracking branch has hint: been updated since the last checkout. If you want to integrate the hint: remote changes, use 'git pull' before pushing again.
git fetch --prune git branch -vv | grep ': gone]' #Remotely deleted, local branch still exists
From /home/azureuser/git-lab/collab/remote/myapp - [deleted] (none) -> origin/feature/x feature/x f44e7af [origin/feature/x: gone] feat: y
Experiment 5: Push conflict between two people → resolve with pull --rebase → safe force push (about 7 minutes)
cd ~/git-lab/collab/alice && git switch main && git pull -q sed -i 's/"status": "ok"/"status": "healthy"/' app.py git commit -qam "fix(health): report healthy status" git push origin main
cd ~/git-lab/collab/bob && git switch main # Note: Bob does not pull at this time sed -i 's/"status": "ok"/"status": "up"/' app.py git commit -qam "fix(health): report up status" git push origin main || echo "→ Rejected, integrate remote first" git fetch && git branch -vv
git pull --rebase git status | head -6 grep -n -A8 'def healthz' app.py
Auto-merging app.py
CONFLICT (content): Merge conflict in app.py
Rebasing (1/1)error: could not apply bf0f390... fix(health): report up status
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
…
interactive rebase in progress; onto 2799b55
Last command done (1 command done):
pick bf0f390 # fix(health): report up status
No commands remaining.
You are currently rebasing branch 'main' on '2799b55'.
16:def healthz():
17-<<<<<<< HEAD
18- return {"status": "healthy"}
19-||||||| parent of bf0f390 (fix(health): report up status)
20- return {"status": "ok"}
21-=======
22- return {"status": "up"}
23->>>>>>> bf0f390 (fix(health): report up status)
in rebaseHEADSegments (ours) belong to Alicehealthy, bringbf0f390The segment is Bob's ownup(See M2's "ours/theirs inversion"). After discussing it, the two decided to keep it{"status": "healthy"}:
git checkout --ours app.py # Ours = upstream = Alice's version in rebase git add app.py git rebase --continue # Bob's commit becomes an empty commit and is automatically discarded (if empty is prompted, use git rebase --skip) git log --oneline --graph -3 git push origin main
Successfully rebased and updated refs/heads/main. * 2799b55 (HEAD -> main, origin/main) fix(health): report healthy status * db1616e docs: add local run instructions * f4ac97b (tag: v1.1.0) Merge branch 'hotfix/redis-timeout' Everything up-to-date
cd ~/git-lab/collab/alice git switch -c feature/x && echo x > x.txt && git add x.txt && git commit -qm "feat: x" git push -u origin feature/x cd ../bob && git fetch -q && git switch feature/x && echo y > y.txt && git add y.txt && git commit -qm "feat: y" && git push -q cd ../alice && git commit -q --amend -m "feat: x (amended)" git push --force-with-lease # (stale info) reject git fetch git push --force-with-lease --force-if-includes # (remote ref updated since checkout) reject git push --force-with-lease --no-force-if-includes # Demonstration trap: turn off if-includes check
! [rejected] feature/x -> feature/x (stale info) ! [rejected] feature/x -> feature/x (remote ref updated since checkout) + f44e7af...41ca40d feature/x -> feature/x (forced update)
The third orderSuccessfuland covers Bob'sfeat: y(f44e7af) - This is exactly what you want to do with just--force-with-leasetrap. Because module 0 step 3 is setpush.useForceIfIncludes true, usually write--force-with-leaseIt will automatically come with a check, use it here--no-force-if-includesTurn it off explicitly to demonstrate. Recovery method: Bob still has the commit locally,cd ../bob && git push --force-with-leasebeforegit fetchAgaingit rebase origin/feature/x, put y back on top of Alice's new commit and push. Correct approach: Alice should firstgit pull --rebaseIntegrate Bob's commit and push it forward.
git push origin --delete feature/x cd ../bob && git fetch --prune && git branch -vv git switch main && git branch -D feature/x
Case 1: IDE background fetch makes --force-with-lease invalid
Question:After developers get used to rebase--force-with-lease, one day overwriting two commits that a colleague had just pushed to a shared feature branch. Investigation found that the IDE automatically fetched every 3 minutes,origin/featureIt has been committed by a colleague, and the lease check has passed.Method:Team unitygit config --global push.useForceIfIncludes true; Shared branches are prohibited from being pushed on the platform.Effect:Background fetch no longer causes false overwrites.
Case 2: Hundreds of expired remote-tracking branches
Question:git branch -r800 branches are listed, most of the corresponding PRs have been merged, and completion and IDE have become slow.Method:git config --global fetch.prune true; The platform turns on "Automatically delete branches after merging"; for local usegit branch -vv | grep ': gone]'Find a local branch that can be deleted (available in Git 2.56git branch --delete-merged)。
Case 3: Pull on CI machine generates merge commit
Question:Deploy script on servergit pull, one time someone modified a file on the server and committed it, pull generated a merge commit, and the deployed code was inconsistent with main.Method:The deployment script is changed togit fetch origin && git reset --hard origin/main(orgit pull --ff-onlyAlarm if failure occurs); manual commit is prohibited on the server; it is better to deploy the built image (Docker lesson).
Common errors and solutions
! [rejected] main -> main (non-fast-forward)
Reason:The remote branch is not an ancestor of your local branch: someone else pushed it first, or you rewrote the history of the push.
git fetch && git status -sb && git log --oneline --graph --all -10
Fix:Shared branch:git pull --rebasePush again later. Own branch and confirmed to be caused by rebase:git push --force-with-lease --force-if-includes。
fatal: Need to specify how to reconcile divergent branches.
Reason:Local and remote forks without configuring pull integration.
Fix:git config --global pull.rebase true(recommended); or this timegit pull --rebase / --no-rebase。
fatal: The current branch feature/x has no upstream branch.
Reason:The new branch is pushed for the first time and has not yet been upstreamed.
Fix:git push -u origin feature/x;orgit config --global push.autoSetupRemote true。
There is no tracking information for the current branch.
Reason:no parametersgit pullThe time branch has no upstream.
Fix:git branch --set-upstream-to=origin/feature/x。
error: src refspec main does not match any
Reason:There is no branch named main locally (no commits have been made, or the branch is called master).
Fix:git branch -aConfirm the branch name; commit the empty repository first; orgit push origin HEAD:main。
1. Without changing any local branches, see which commits the remote main has more than your local main.
git fetch origin git log --oneline main..origin/main
2. One-time configuration: pull default rebase, automatically clean up remote branches, automatically create upstream for the first push, and check whether it has been integrated when pushing.
git config --global pull.rebase true git config --global fetch.prune true git config --global push.autoSetupRemote true git config --global push.useForceIfIncludes true
git statusIt says "Your branch is up to date with 'origin/main'", but my colleague said he had pushed the fix ten minutes ago. Why?
status is not connected to the Internet, it compares the local main with the localrefs/remotes/origin/main, the latter is only updated during fetch/pull/push. executegit fetchThe status will be displayed behind.
Verified instructional videos
Official documentation
Video storyboard (approximately 90 seconds)
Image: Cloud repository and laptop with a "photo" labeled origin/main.
Narrator: origin/main is the photo you took of the remote during the last fetch. The status is only compared with this photo.
Picture: Alice pushes first, and Bob is blocked by a red baffle when pushing, showing rejected.
Narrator: When the remote has a commit that you don't have, the push will be rejected. First fetch, then use pull --rebase to put your own commit on top of the latest commit.
Screen: Three hammers: force, force-with-lease, force-if-includes. The first two smashed other people's commits, and the third was blocked by a safety lock.
Narrator: When rewriting your own remote branch, use force-with-lease plus force-if-includes to make sure you have seen and integrated the latest commits from the remote.
Module 6 · Pull Request Workflow and Code Review
- Correspond each step of PR to Git commands: open branch, push, compare (three-point diff), update (add commit/force-push), merge (three buttons), delete branch.
- Follow the team's branch naming convention, keep PRs small and focused (< 400 lines of changes from experience), and write good PR descriptions.
- Use a review checklist to conduct code reviews, checking both the code and the commit history; know the respective responsibilities of authors and reviewers.
What: What is PR/MR?
A Pull Request (GitHub, Azure Repos, Bitbucket) or Merge Request (GitLab) is "please pull mysource branchmerge intotarget branch” request, the platform provides on it: diff view, row-level comments, CI status check, approval, merge button.Git itself only knows about branches and commits, PR metadata (comments, approvals) are stored in the platform database, not in the repository.
Why: Why PR?
- quality: Second pair of eyes + automated checks (tests, lint, security scans) run before merging.
- knowledge sharing: Reviewers understand code changes to avoid "only one person understands".
- traceable: Each change can be traced back to the discussion, ticket number, and approver (compliance requirements, such as SOC 2).
How: Correspondence between PR life cycle and Git commands
| PR steps | Git operations behind the scenes |
|---|---|
| Create a branch | git switch -c feat/123-redis-port origin/main |
| Open PR | git push -u origin feat/123-redis-port, then select the source/target branch on the platform (GitHub CLI:gh pr create) |
| “Files changed” view | three point diff:git diff origin/main...feature = git diff $(git merge-base origin/main feature) feature, only the changes in feature since the fork are displayed, excluding subsequent changes in main |
| “Commits” view | git log origin/main..feature(Two points: Commit with feature and without main) |
| Modify based on review | Append commit orcommit --fixupaftergit push;After sorting out the historypush --force-with-lease |
| “This branch is out-of-date” | There is a new commit on the target branch:git fetch && git rebase origin/main(Or the platform’s Update branch button, mostly in merge mode) |
| “This branch has conflicts” | The three-way merge attempted by the platform failed: local rebase/merge resolved the conflict and then pushed (M2) |
| CI check | The platform usually has a clear understanding of the relationship between the source branch and the target branch.Trial merge results"Run (GitHubrefs/pull/N/merge) |
| merge button | Create a merge commit = merge --no-ff;Squash and merge = merge --squash+ commit; Rebase and merge = fast forward after replaying step by step (GitHub will generate a new hash) |
| delete branch | git push origin --delete feature;localgit fetch --prune + git branch -D |
Branch naming convention (example, customized by the team)
| prefix | Example | Purpose |
|---|---|---|
feat/orfeature/ | feat/123-redis-port | New function (with work order number for easy traceability) |
fix/ | fix/456-healthz-timeout | Bug fixes |
hotfix/ | hotfix/1.2.1 | Online emergency repair (M4) |
chore/、docs/、refactor/ | docs/readme-run | Consistent with Conventional Commits type (M7) |
release/ | release/1.3 | Release Lines (Lesson 6 Branching Strategies) |
in branch name/In Git, a directory-style reference path is formed, so they cannot exist at the same time.feat and feat/xtwo branches (cannot lock ref). Avoid spaces,..、~^:?*[\characters (git check-ref-format --branchVerifiable).
Small PR principle
- A PR only does one thing; it is best to commit separate PRs for refactoring and functionality.
- Empirical data: The quality of review decreases as the number of lines of changes increases. It is generally recommended to control it within 200-400 lines; for large functions, use feature switches or superimpose PR (M3's
--update-refs) split. - Branches are short-lived (1–3 days) and have more conflicts (M2) as they get older.
- PR description answer:Why changed, what changed, how to verify, risks and rollback, and associate the work order.
Reviewer checklist
| Dimensions | checkpoint |
|---|---|
| correctness | Whether requirements are implemented; boundary conditions; error handling; concurrency and idempotence |
| test | Have tests been added/modified? Is CI all green? Does the test actually fail when the bug exists? |
| safe | No secret was committed (.env, key); input verification; whether dependent changes are trustworthy |
| Readability and design | Naming, function length, duplicate code; compliance with existing architecture |
| Operation and maintenance | Logs, indicators, configuration items (such asREDIS_PORTWhether there is a default value) and whether database migration can be rolled back |
| Commit history | Commit information conforms to the specification (M7); no "wip" or "fix typo" pile-up (or plan squash); no extraneous files |
| Documentation | README / CHANGELOG / API document synchronization update |
When: Which merge button to choose?
See module 1 comparison table. Common combination: small team + small PR →Squash and merge;Need to retain commit granularity and high commit quality →Rebase and mergeormerge commit;The platform level can usually enable only one of these, along with the "require linear history" branching rule (Lesson 3).
git diff main feature" - Two-point diff will display the subsequent changes to main in "reverse" form, and PR uses three-point diff. ② "The review only looks at the code, not the commit" - the commit history will remain in the repository permanently, and the review is also the last chance to sort out the history. ③ "You can merge if the review is passed" - you have to wait for the CI based on the latest target branch to pass; otherwise you will encounter semantic conflicts in M2.Figure 6-1 PR life cycle (platform layer vs Git layer)
Figure 6-2 Two-point diff vs three-point diff
Interaction: the life cycle of a PR (choose what to do at each step and see the consequences)
You are responsible for PR #42 “feat(config): read REDIS_PORT”. There are multiple options for each step, and selection will display the corresponding Git command, changes on the platform, and reviewer reactions. Goal: merge without disturbing colleagues and with a clean history.
Core commands and parameters
| command | function | Description |
|---|---|---|
git diff origin/main...HEAD | All changes introduced by this branch (PR diff) | --stat、--name-only |
git log --oneline origin/main..HEAD | Commits of this branch (PR commits) | --reversein chronological order |
git fetch origin pull/42/head:pr-42 | Pull the PR on GitHub to the local branch for review | The reference paths of Azure Repos / GitLab are different, see Lessons 3 and 4 |
git range-diff | Compare the commit sequence before and after force-push | M3 |
git check-ref-format --branch <name> | Verify whether the branch name is legal | Naming convention checks can be done in CI |
gh pr create / checkout / view | GitHub CLI action PR | Platform Tools, Lesson 3 Detailed Introduction |
# Author: Self-examination before opening a PR git fetch origin git rebase origin/main git log --oneline origin/main..HEAD git diff --stat origin/main...HEAD git diff --check origin/main...HEAD # Blank errors, conflict markers
7f1e2d3 feat(config): read REDIS_PORT from environment a0b9c8d test(config): cover REDIS_PORT default app.py | 2 +- tests/test_config.py | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-)
# Reviewer: Check out other people's branches locally for review and run them git fetch origin git switch --detach origin/feat/123-redis-port # Read-only view, do not create local branches git diff origin/main...HEAD python3 -m pytest -q # or docker compose run --rm web pytest git switch-
Experiment 6: Simulate a complete PR using local commands (about 7 minutes)
This experiment does not require a platform account: Alice is the author, Bob is the reviewer, and "PR" is the branch on the remote + your conversation in the terminal; the merge is executed and pushed by Bob pressing "squash and merge" locally (this step is completed by the platform button in the real project).
cd ~/git-lab/collab/alice && git switch main && git pull -q
git switch -c feat/123-redis-port
sed -i 's/port=6379/port=int(os.getenv("REDIS_PORT", "6379"))/' app.py
git commit -qam "feat(config): read REDIS_PORT from environment"
mkdir -p tests && printf 'import os\n\ndef test_default_port():\n assert int(os.getenv("REDIS_PORT", "6379")) == 6379\n' > tests/test_config.py
git add tests && git commit -qm "test(config): cover REDIS_PORT default"
git check-ref-format --branch feat/123-redis-port
git push -u origin feat/123-redis-portcd ~/git-lab/collab/bob && git fetch -q git log --oneline origin/main..origin/feat/123-redis-port git diff origin/main...origin/feat/123-redis-port
Reviewer's comment: "Please describe the REDIS_PORT variable in the README."
cd ~/git-lab/collab/alice echo "- REDIS_PORT: Redis port, default 6379" >> README.md git commit -qam "docs: document REDIS_PORT" git push -q # After Bob's reply to LGTM: synchronize the trunk and organize it (keep 3 meaningful commits here) git fetch -q && git rebase origin/main git push --force-with-lease --force-if-includes
cd ~/git-lab/collab/bob && git switch main && git pull -q git merge --squash origin/feat/123-redis-port git commit -qm "feat(config): read REDIS_PORT from environment (#123)" \ -m "Co-authored-by: Alice <alice@example.com>" git push origin main git push origin --delete feat/123-redis-port git log --oneline -3
cd ~/git-lab/collab/alice git switch main && git pull -q && git fetch --prune git branch -vv | grep gone git branch -D feat/123-redis-port # squash After merging, -d will consider it not merged
Case 1: PR with 3000 lines was not reviewed for two weeks
Question:The "Payment Module Refactoring" PR contained renaming, formatting, and logic changes, and the reviewers had no idea where to start. The PR was stalled and conflicted with main.Method:Split into three PRs: ① Pure formatting/renaming (machine verifiable, quick approval); ② Introducing a new interface (feature switch is turned off); ③ Switching the caller. use--update-refsMaintain overlay branches.Effect:Each PR is merged within one day.
Case 2: The review passed but the main compilation failed after merging
Question:The PRs passed by two respective CIs were merged one after another, and the combined compilation failed (semantic conflict, M2).Method:Enable "Require branch to be latest before merging" or merge queue (Lesson 3) to have CI run on "target branch latest commit + PR".
Case 3: Secrets enter history with PR
Question:Commit 2 in the PR contains.env, the 3rd commit removed it and the reviewer only looked at the final diff. The squash merge leaves main without the file, butPR’s source branch and platform’srefs/pull/*still preservedit.Method:Revoke and rotate the secret immediately (most important); add "commit-by-commit review" to the review list; enable the platform's push protection and secret scanning (Lesson 3), pre-commit hooks (Lesson 5); clean up the history in Lesson 7.
Common errors and solutions
This branch has conflicts that must be resolved
Reason:The platform's trial merge of the source branch and the target branch failed.
git fetch origin && git rebase origin/main # Resolve conflicts (M2) git push --force-with-lease --force-if-includes
Used instead when the team does not allow rewriting of the PR branchgit merge origin/mainThen push it normally.
There are a bunch of files that were not changed by me in the PR's Files changed.
Reason:The branch was forked from another feature branch (not main), or the wrong target branch was selected.
git log --oneline origin/main..HEAD # See which commits are not yours
Fix:git rebase --onto origin/main < wrong base point >(M3), or modify the target branch of the PR.
error: cannot lock ref 'refs/remotes/origin/feat/x': 'refs/remotes/origin/feat' exists
Reason:References are stored in directory form,feat with feat/xConflict (common in remote deletion)featAfter you have not prune).
Fix:git fetch --prune;Rename branch if conflict still exists.
The reviewer said "I can't understand what you changed after force-push"
git range-diff origin/main feature@{1} feature
During the review period, priority will be given to additional commits or fixup commits, and they will be sorted out after approval.
1. Check the statistics of changes to be introduced by PR locally (target branch origin/main, source branch is the current branch).
git fetch origin git diff --stat origin/main...HEAD
2. Pull PR #57 on GitHub to the local branchreview/57Conduct a review.
git fetch origin pull/57/head:review/57 git switch review/57
A new member asked: "Our team uses squash merge, so it doesn't matter if the commits in my PR are a little messy?" What's your answer?
After squashing, only one commit is left on main, but: ① Reviewers must read the commits one by one during the review process. A good commit sequence makes the review faster; ② The information committed by squash is composed of the PR title and each commit information by default, and still needs to be edited according to the specifications; ③ The PR page and source branch (before deletion) will retain the original commit, and issues such as confidentiality will still exist; ④ Develop the habit of organizing commits, which is also applicable when switching to projects using merge commit.
Verified instructional videos
Official documentation
- GitHub Docs: About pull requests
- GitHub Docs: About merge methods
- Azure Repos: Create pull requests
- Google Engineering Practices: Code Review
- git-check-ref-format
Video storyboard (approximately 90 seconds)
Screen: There are two layers, the upper layer is the PR page, and the lower layer is the Git commit graph. The two are connected with a dotted line.
Narrator: PR is a discussion and review layer added by the platform on top of branches. There are still branches, commits and a merge underneath.
Image: Two-point diff side-by-side with three-point diff, with red reverse changes appearing in the two-point diff.
Narrator: PR uses a three-point diff to show only the changes introduced to your branch since the fork.
Screen: A review checklist with items ticked one by one, and finally three options pulled out under the merge button.
Narrator: Small and focused PR, clear description, review item by item, then choose the merge method as agreed by the team, and delete the branch after the merge.
Module 7 · Commit Specifications, Labeling and Publishing
- Press Conventional Commits to write commit information:
type(scope)!: description+ Text + Endnotes (BREAKING CHANGE:、Refs:、Co-authored-by:)。 - distinguishlightweight tags(just a reference to the commit) vs.Notes label(Independent tag object, including tagger, date, information, and can be signed), know that annotation tags are required for publishing, and tags need to be pushed separately.
- use
git describeGenerate traceable version numbers and use SemVer rules to deduce the next version from the commit type.
What: Good commit message
Git convention: the first line isTitle(About 50 characters, imperative mood, no periods), a blank line, thenText(Approximately 72 characters wrapped, descriptionwhychange instead of repeating the diff), and finallyendnote(trailers,Key: valueformat, can begit interpret-trailersand platform analysis).
Conventional Commits 1.0.0
<type>[optional scope][!]: <description> [optional body] [optional footer(s)]
| type | meaning | SemVer Impact |
|---|---|---|
feat | new features | MINOR(1.2.0 → 1.3.0) |
fix | Bug fixes | PATCH(1.2.0 → 1.2.1) |
feat! / fix!or endnoteBREAKING CHANGE: … | Incompatible changes | MAJOR(1.2.0 → 2.0.0) |
docs、style、refactor、perf、test、build、ci、chore、revert | The specification itself only defines feat/fix, and the rest of the types come from Angular conventions, which are widely used by commitlint's config-conventional and so on. | Publishing is not triggered by default (perfOften configured as PATCH) |
Why: Why should we regulate
- Person:
git log --onelineSee the nature of changes at a glance; review and rollback are faster. - Tools: Automatically generate CHANGELOG, automatically calculate version numbers (semantic-release, release-please, git-cliff, etc., Lesson 5); CI uses commitlint to verify.
- Traceback: Endnotes
Refs: #123Related work orders;Co-authored-by:Give multiple authors credit (which platforms like GitHub will recognize).
How: Tags
lightweight tags git tag v1.2.0 | Notes label git tag -a v1.2.0 -m "…" | |
|---|---|---|
| storage | only refs/tags/v1.2.0, pointing directly to the commit | refs/tags/v1.2.0point to atag object, the tag object then points to the commit |
git cat-file -t v1.2.0 | commit | tag |
| metadata | None | Tagged by, date, message; available-sSignature (Lesson 5) |
git describe Default | Ignore (requires--tags) | use |
| Purpose | Personal temporary bookmarks | Officially released |
Labels will not followgit pushAutomatic push: usegit push origin v1.2.0, orgit push --follow-tags(Only push the annotation tag pointing to this push commit; can be setpush.followTags true). avoidgit push --tagsPush all local tags (including temporary lightweight tags) at once. Published tagsDo not move or delete the rebuild——Tags fetched by others will not be overwritten by default. As a result, the v1.2.0 in everyone's hands is different.
git describe
git describeFind the note label closest to HEAD and output<tag>-< distance commit number >-g< short hash >, for examplev1.2.0-1-g89f0ff9: 1st commit after v1.2.0, hash 89f0ff9 (gmeans git). Only output when HEAD is exactly on the labelv1.2.0. Commonly used parameters:--tags(Including lightweight tags),--abbrev=0(Just the tag name),--dirty(Add when there are changes in the workspace-dirty)、--always(Short hash is output when there is no label). Lesson 5 will talk about: Shallow clones without tags in CI will cause describe to fail.
Semantic version SemVer 2.0.0
MAJOR.MINOR.PATCH: Incompatible API changes → MAJOR; backward-compatible new features → MINOR; backward-compatible fixes → PATCH. pre-release version1.3.0-rc.1Priority lower than1.3.0;Build metadata1.3.0+build.42Does not affect priority.0.y.zRepresents initial development period and any changes may be incompatible. Git tag names are usually addedvprefix (v1.3.0), the SemVer specification itself states that "v1.2.3" is not a semantic version, just a common tag naming convention.
When
- For each commit: write the title according to the specifications; when modifying the behavior, explain the reasons in the text.
- squash merge: edit the final squash commit information (PR title is the title), which is the only information entering main.
- Release: Add a note tag to the main (or release branch) and push the tag to trigger the release pipeline (Lesson 5).
git push"The labels will be pushed up together" - No. ② "The difference between lightweight labels and annotation labels is only whether there is a description" - annotation labels are independent objects.describe, signing, and publishing tools all rely on it. ③ "choreThe type will change the version number" - not by default, only feat, fix and breaking changes affect SemVer.Figure 7-1 Object structure of lightweight tags vs. annotation tags
git cat-file -t v1.2.0Output tag, lightweight tag output commit)Figure 7-2 From commit to version number
Interactive: Commit information checker + next version number calculator
Enter a commit message (can be multiple lines) on the left, and the checker will judge it one by one according to Conventional Commits 1.0.0 and common commitlint rules. Submissions after v1.2.0 are listed on the right. After checking/cancelling, the next version number andgit describeoutput.
Core commands and parameters
| command | function | Description |
|---|---|---|
git commit -m "title" -m "text" --trailer "Refs: #123" | Multiple paragraphs of information + endnotes | --trailerRequires newer Git (2.32+) |
git tag -a v1.3.0 -m "msg" [commit] | Notes label | -ssignature;git tag v1.3.0for lightweight tags |
git tag -l "v1.*" --sort=-v:refname | List by version number in descending order | -nDisplay the first line of information |
git show v1.3.0 / git cat-file -p v1.3.0 | View tags and objects | |
git push origin v1.3.0 / --follow-tags | push tag | push.followTags true |
git tag -d v1.3.0 / git push origin --delete v1.3.0 | Delete local/remote tags | Only error tags that have not been used yet |
git describe [--tags] [--abbrev=0] [--dirty] [--always] | Describe the current commit based on tags | Full history and tags required in CI |
git log v1.2.0..HEAD --format='%s' | List commit titles since last version | Ingredients for generating change logs |
git shortlog -sn v1.2.0..HEAD | Statistics by author | Contributors in release notes |
cd ~/git-lab/collab/alice && git switch main && git pull -q git tag -a v1.2.0 -m "release 1.2.0" git tag v1.2.0-light git cat-file -t v1.2.0; git cat-file -t v1.2.0-light echo z > z.txt && git add z.txt && git commit -qm "chore: z" git describe git describe --tags --abbrev=0 git cat-file -p v1.2.0 git tag -d v1.2.0 v1.2.0-light && git reset -q --hard origin/main # Clean up after the demonstration: the "Experimental" page will be officially released v1.2.0
tag commit v1.2.0-1-g8b3222c v1.2.0 object 1f41ce010cdd7327e8ece13a6f884c38b2c7c1fd type commit tag v1.2.0 tagger Alice <alice@example.com> 1794781355 -0500 release 1.2.0 Deleted tag 'v1.2.0' (was …) Deleted tag 'v1.2.0-light' (was 1f41ce0)
Note:The collaboration repository already has notes tags v1.0.0 and v1.1.0 for Lesson 1, so the demo starts with v1.2.0. The second article describes is used--tags, lightweight tagv1.2.0-light with v1.2.0When pointing to the same commit, Git prefers pragma tags.
# Simple change log: grouped by type for t in feat fix perf; do echo "## $t"; git log v1.2.0..HEAD --format='- %s (%h)' | grep -E "^- $t(\(|!|:)" || true done
Lab 7: Spec Commit → Compute Version → Publish Note Label (~6 minutes)
cd ~/git-lab/collab/alice && git switch main && git pull -q git tag -l git describe --tags --always
v1.0.0 v1.1.0 v1.1.0-3-g5e6f7a8
v1.0.0 and v1.1.0 are annotation tags created by the Lesson 1 script and cloned together with the collaborative repository.-3Indicates that there have been 3 commits after v1.1.0 (README commit by teammates in Lesson 1 + commits you merged in M5 and M6, the number depends on what experiments you have done). When there are no labels--alwaysA short hash will be output.
sed -i 's/socket_timeout=2/socket_timeout=3/' app.py
git commit -qam "fix(redis): raise socket timeout to 3s" -m "Redis on the shared host occasionally needs more than 2s under load."
printf '\n\n@app.route("/version")\ndef version():\n return os.getenv("APP_VERSION", "dev") + "\\n"\n' >> app.py
python3 -c "import ast; ast.parse(open('app.py').read()); print('syntax ok')"
git commit -qa -m "feat(api): add /version endpoint" --trailer "Refs: #130"
git log -2 --format='%h %s%n%(trailers)'
socket_timeout=2Hotfix branch from Lesson 1 (merged into v1.1.0)./versionUse the same as in Lesson 1@app.routeWritten appended to the end of the file.
LAST=$(git describe --tags --abbrev=0) echo "Last version: $LAST" git log "$LAST"..HEAD --format=%s if git log "$LAST"..HEAD --format=%B | grep -qE '^BREAKING CHANGE:|^[a-z]+(\(.+\))?!:'; then echo "→ MAJOR" elif git log "$LAST"..HEAD --format=%s | grep -qE '^feat(\(.+\))?:'; then echo "→ MINOR" else echo "→ PATCH"; fi
Previous version: v1.1.0 feat(api): add /version endpoint fix(redis): raise socket timeout to 3s feat(config): read REDIS_PORT from environment (#123) fix(health): report healthy status docs: add local run instructions →MINOR
git push origin main git tag -a v1.2.0 -m "v1.2.0" -m "$(git log v1.1.0..HEAD --format='- %s')" git push origin v1.2.0 git ls-remote --tags origin
cd ~/git-lab/collab/bob && git pull -q && git fetch --tags git describe # should output v1.2.0 git show v1.2.0 --stat | head -12
Case 1: Automatic release eliminates arguments about version numbers and change logs
Question:Before each release, the team spent half a day sorting through the change logs and arguing about version numbers.Method:Use Conventional Commits + PR title checking (the PR title becomes the commit title when squashing the merge); use release-please or semantic-release to automatically generate CHANGELOG and tags on main (Lesson 5).Effect:Publishing becomes one click.Limitations:Depends on the quality of the committed information. When reviewing, you need to check whether the type is accurate (such as misusefeatwould result in unnecessary MINOR).
Case 2: The tag was deleted and rebuilt, and the two build machines produced different v2.4.0
Question:The publisher discovered that v2.4.0 was missing a commit, deleted the tag, rebuilt it on the new commit, and pushed it. Build machines that have fetched old tags will still build with the old commits (git fetch does not overwrite existing tags by default).Method:Make tags immutable: v2.4.1 if you miss it; enable tag protection rules on the platform (Lesson 3).
Case 3: The production environment does not know which version is running
Question:The deployed code version cannot be determined during online troubleshooting.Method:Build-time injectiongit describe --tags --always --dirtyresults (such as Docker image labels andAPP_VERSIONenvironment variables),/versionThe endpoint returns it. Note that in CIfetch-depth: 0Or fetch tags alone (Lesson 5).
Common errors and solutions
fatal: No names found, cannot describe anything.
Reason:There are no annotation tags in the current history (only lightweight tags, or no fetch tags for CI shallow clones).
Fix:git describe --tags --always; CI ingit fetch --tags --unshallowOr set up a full clone (Lesson 5).
fatal: tag 'v1.1.0' already exists
Reason:A label with the same name already exists.
Fix:If it has not been pushed yet and the typo is confirmed:git tag -d v1.1.0after rebuilding (orgit tag -f); if pushed, a new version number will be released.
! [rejected] v1.1.0 -> v1.1.0 (would clobber existing tag)
Reason:When fetching, the remote tag with the same name points to a different commit, and Git refuses to overwrite the local tag.
Fix:Figure out which one is correct; confirm that remote is the correct onegit fetch --tags --force. Basically: don't move published tags.
Colleagues can’t see my tags
Reason:The label is not pushed.
git ls-remote --tags origin | grep v1.1.0 || git push origin v1.1.0
commitlint: subject may not be empty / type may not be empty
Reason:The committed information does not meet thetype(scope): subjectformat (e.g. "WIP", "update").
Fix:Not pushed locally:git commit --amendorrebase -iMedium reword; Already in PR: push with force-with-lease after finishing, or edit final information when relying on squash.
1. Committing4f2a1c9Create annotation tag v2.0.0 on and push only this tag.
git tag -a v2.0.0 -m "v2.0.0" 4f2a1c9 git push origin v2.0.0
2. Write a commit to indicate removal/countInterface (incompatible changes), and associated ticket #88.
git commit -m "feat(api)!: remove /count endpoint" \ -m "Use /stats instead." \ -m "BREAKING CHANGE: /count has been removed" --trailer "Refs: #88"
There are 3 fixes, 1 docs, and 1 band after v1.4.0BREAKING CHANGE:Refactor of endnotes. What is the next version number? What if it is currently 0.4.0?
There are breaking changes → MAJOR: v2.0.0 (endnote BREAKING CHANGE can appear on any type). If during the initial development period of 0.y.z, SemVer allowed any changes to occur in MINOR, many tools (such as semantic-release configuration or release-pleasebump-minor-pre-major) will release 0.5.0; the team needs to make a clear agreement.
Verified instructional videos
No verified video specifically explaining Conventional Commits / SemVer was found. Please refer to the original text of the specification.
Official documents and specifications
- Conventional Commits 1.0.0
- Semantic Versioning 2.0.0
- Pro Git 2.6 Tagging
- git-describe
- git-interpret-trailers
Video storyboard (approximately 90 seconds)
Screen: Two git logs, one full of update, fix, and wip, the other full of feat(api), fix(health).
Narrator: Standard commit information allows people to understand the nature of changes at a glance, and also allows tools to automatically generate change logs.
Image: A lightweight tag is a sticky note attached directly to the commit; a note tag is a signed and dated certificate that points to the commit.
Narrator: Official releases use annotation tags, which are independent objects that record who, when, and why they were released.
Screen: Commit types flow into the scale, feat adds one to the middle number, and BREAKING adds one to the first number.
Narrator: Semantic version: incompatible with major version upgrades, new features with minor version upgrades, fixes with revision numbers. Remember to push the tags separately.
Module 8 · Collaboration Readiness Review and Common Conflict Exercises
- Develop a Git collaboration configuration baseline for the team and explain what problems each item prevents.
- When encountering non-fast-forward rejection, rebase conflicts, mistakenly merging main into feature branches, stash conflicts, mistaken push, etc., you can diagnose first (
status、log --graph、reflog) and then choose the correct recovery method. - Master the “safety net”:
--abort、ORIG_HEAD、git reflog、git revert, and know when history can be rewritten and when reverse commits can only be appended.
What: Three levels of collaboration readiness
| level | content | This lesson/Follow-up |
|---|---|---|
| Personal configuration | identity, editor, pull/push/fetch behavior, conflicting styles, rerere | Baseline of this module |
| Team agreement | Branch naming, PR size, merge methods, commit specifications, tag rules, who can push which branches | M6, M7; Lesson 6 Branching Strategy |
| Platform mandatory | Branch protection/rule set, required review, status check, no push, tag protection | Lessons 3 and 4 |
Team configuration baseline (recommended)
| Configuration | value | Problems to prevent | module |
|---|---|---|---|
pull.rebase | true | Meaningless "Merge branch 'main' of ..." commit | M5 |
fetch.prune | true | Expired remote-tracking branches,cannot lock ref | M5 |
push.autoSetupRemote | true | “has no upstream branch” | M5 |
push.useForceIfIncludes | true | background fetch lets--force-with-lease Invalid | M5 |
push.followTags | true | Forgot to push the note label? | M7 |
merge.conflictStyle | zdiff3 | Failure to see common ancestors leads to misjudgment of conflicts | M2 |
rerere.enabled | true | Resolve the same conflict repeatedly | M2 |
rebase.autoSquash / rebase.updateRefs | true | Manually organize fixups, overlay branches and missing updates | M3 |
rebase.autoStash | true | pull --rebase failed due to changes in the workspace | M5 |
init.defaultBranch | main | The new repository branch name is inconsistent (Git 3.0 plan defaults to main) | Lesson 1 |
core.editor | "code --wait"Wait | Editor does not wait when rebase -i | M3 |
Why: The core idea of accident recovery
- Stop first, diagnose later:
git statusTell you "what operation is in progress" (merge / rebase / cherry-pick / bisect),git log --oneline --graph --all -15Look at the shape,git reflog -15Watch "What I Just Did." - Operation in progress →
--abort: Merge, rebase, cherry-pick, revert can all go back to the beginning. - Just completed, not pushed →
ORIG_HEADor reflog +reset --hard: merge, rebase, reset, pull will all write the old locationORIG_HEAD;reflog records every HEAD/branch move (90 days by default, 30 days for unreachable entries). - Pushed to shared branch →
git revert: Append a reverse commit without rewriting history; use for merge commitrevert -m 1。 - Accidental push overwrites someone else's commit→ Retrieve old commits from any place where they still exist (colleagues’ clones, your reflog, CI cache, platform event records), and then push to restore.
How: Four types of accidents in this module exercise
| accident | Typical signal | Preferred recovery |
|---|---|---|
| non-fast-forward reject | ! [rejected] … (fetch first / non-fast-forward) | git pull --rebase→ push |
| Conflict during rebase | could not apply …、interactive rebase in progress | Solution +--continue;or--abort |
| Merged main into feature branch by mistake | The feature branch appears "Merge branch 'main' into feat/x" | Not pushed:reset --hard ORIG_HEAD; Pushed and used exclusively by yourself:rebase origin/mainAfter force-with-lease |
| stash pop conflict | CONFLICT … + The stash entry is kept in case you need it again. | After resolving the conflictgit stash drop, orgit stash branch |
When: Can it be rewritten or can it only be appended?
--force-with-lease --force-if-includespush.Pushed to shared branch(main, release, multiplayer feature branches) → Only appends (revert, new commits) can be made, unless the team is coordinated and the platform allows it.reset --hardAfter committing it, it will be gone forever" - the committed object is still there and the reflog can be retrieved (butNot committedThe workspace changes cannot be reversed). ② "Revert a merge and then merge the same branch to recover" - Git thinks that those commits have been merged and need to be reverted first. ③ "If you encounter problems, delete the directory and clone again" - you will lose the local reflog, stash and unpushed branches, which are often what is needed for recovery.Figure 8-1 Accident recovery decision diagram
Figure 8-2 Mistakenly merging main into the feature branch: two repaired shapes
Interactive: Collaborative incident drill (selecting the correct recovery command)
Each scenario gives the phenomenon seen in the terminal. Select the next command you would execute and the emulator will tell you the outcome: the recovery was successful, ineffective, or made the situation worse. Complete all 6 scenarios to see your score.
Core Command: Diagnosis and Safety Net
| command | function | Description |
|---|---|---|
git status | The current operation and conflict file | The first command is always it |
git log --oneline --graph --all -20 | historical shape | --decorateShow all quotes |
git reflog [branch] -20 | HEAD / branch move record | HEAD@{2}、main@{yesterday} |
git reset --hard ORIG_HEAD | Undo the just completed merge/rebase/pull | Uncommitted changes will be discarded, stash first |
git revert [-m 1] <sha> | Append reverse commit | Used when pushed to a shared branch |
git merge/rebase/cherry-pick --abort | Abandon ongoing operation | |
git config --show-origin --get-regexp '^(pull|push|fetch|rebase|merge|rerere)\.' | Check collaboration related configuration and its source files | For readiness review |
# Collaboration readiness self-test (personal) git --version git config --show-origin --get-regexp '^(user|pull|push|fetch|rebase|merge|rerere|init)\.'
git version 2.56.0 file:/home/azureuser/.gitconfig user.name Alice file:/home/azureuser/.gitconfig user.email alice@example.com file:/home/azureuser/.gitconfig init.defaultbranch main file:/home/azureuser/.gitconfig pull.rebase true file:/home/azureuser/.gitconfig fetch.prune true file:/home/azureuser/.gitconfig push.autosetupremote true file:/home/azureuser/.gitconfig push.useforceifincludes true file:/home/azureuser/.gitconfig merge.conflictstyle zdiff3 file:/home/azureuser/.gitconfig rerere.enabled true file:/home/azureuser/.gitconfig rebase.autosquash true file:/home/azureuser/.gitconfig rebase.updaterefs true
# Recovery example: Undo the pull you just made by mistake (not pushed) git reflog -5 git reset --hard ORIG_HEAD
1f9c2ab (HEAD -> feat/x) HEAD@{0}: pull origin main: Merge made by the 'ort' strategy.
8d3e4f5 HEAD@{1}: commit: feat(api): add /version endpoint
…
HEAD is now at 8d3e4f5 feat(api): add /version endpoint
Experiment 8: Reproduction and repair of four accidents (about 8 minutes)
cd ~/git-lab/collab/alice && git switch main && git pull -q echo "a" >> README.md && git commit -qam "docs: alice note" && git push -q cd ../bob && git switch main echo "b" > CONTRIBUTING.md && git add . && git commit -qm "docs: add CONTRIBUTING" git push || true # rejected (fetch first) git pull --rebase && git push # Different files, no conflicts git log --oneline -3
cd ~/git-lab/collab/alice && git pull -q git switch -c feat/title sed -i 's/# myapp/# myapp (Flask)/' README.md && git commit -qam "docs: title" git switch main && sed -i 's/# myapp/# MyApp/' README.md && git commit -qam "docs: capitalize" && git push -q git switch feat/title git rebase main || git status | head -3 git rebase --abort && git log --oneline -1 # Return to before rebase git rebase main # Come again, this time solve the problem sed -i '/^<<<<<<<\|^|||||||\|^=======\|^>>>>>>>/d; /^# myapp$/d; /^# MyApp$/d; s/^# myapp (Flask)$/# MyApp (Flask)/' README.md head -1 README.md git add README.md && git rebase --continue
sed completes "remove conflict tags + retain merged titles" in one line. This is only for demonstration; please solve it in the editor in practice.head -1should be output# MyApp (Flask)。
git switch main && echo "c" >> README.md && git commit -qam "docs: more" && git switch feat/title git merge --no-edit main # Misoperation: Generate merge commit git log --oneline --graph -4 git reset --hard ORIG_HEAD # Not pushed: directly revoked git rebase main # Correct synchronization method git log --oneline --graph -4
If feat/title with merge commit has been pushed (and only you use it):git rebase origin/mainwill discard the merge commit and thengit push --force-with-lease --force-if-includes。
echo "local edit" >> app.py git stash push -m "local edit" echo "# committed edit" >> app.py && git commit -qam "chore: committed edit" git stash pop || true git stash list # The entry is still there! git checkout --theirs app.py 2>/dev/null || true git diff --name-only --diff-filter=U
Auto-merging app.py
CONFLICT (content): Merge conflict in app.py
On branch feat/title
Unmerged paths:
…
The stash entry is kept in case you need it again.
stash@{0}: On feat/title: local edit
app.py
In a stash conflict, "Updated upstream" (ours) is the current HEAD and "Stashed changes" (theirs) are the contents of stash. Executed after manual merginggit restore --staged app.py(No commit required after stash conflict resolution) orgit add, againgit stash drop。
# The end of this experiment: discard the demo changes git checkout HEAD -- app.py && git stash drop git switch main && git branch -D feat/title
Case 1: Review of the “main was pushed” incident on Monday morning
After:One developer's local main is far behind,git push -fRolled back the remote main by 14 commits.Recovery:A colleague's clone was fetched before the accident,origin/mainStill pointing to the correct commit, he executesgit push origin < correctly hashes >:main(Requires temporary unprotection); commit hashes in CI logs can be cross-checked.Improvements:main enables branch protection: no forced push, only PR merge allowed (Lesson 3); full staff configurationpush.useForceIfIncludes; inpush.default simple(Default), not executed on maingit push -f。
Case 2: Git configuration script for onboarding new members
Method:Provided by team repositoryscripts/git-setup.sh, write the configuration baseline and commit information template of this module (commit.template) and merge tools; the onboarding document comes with an incident walkthrough for this lesson M8.Effect:In the first week of employment, the number of "incorrect merges and incorrect push" work orders was significantly reduced.Note:Script only writes--globalThere are no items that conflict with the team, and the user identity is set by the individual.
Case 3: Revert merged and then merged again, the function "disappeared"
Question:Feature X found problems after merging, usegit revert -m 1Undo; merge feat/x again after repair. As a result, only the repair commit enters main, and the original function code is still revoked.Reason:The original commit is already an ancestor of main and is considered "merged" by Git.Method:Firstgit revert <revert commit >(Restore the original changes), then merge and fix; or rebase the feature branch into a new commit and merge again.
Common errors and solutions
! [rejected] main -> main (non-fast-forward) —— I want to push -f directly
Don't. Firstgit fetchSee clearly what’s more in the remote area:git log --oneline main..origin/main. Shared branches are alwaysgit pull --rebasePush later.
You are currently rebasing branch 'feat/x' on '1a2b3c4'. (all conflicts fixed: run "git rebase --continue")
The conflict was resolved but not continued. executegit rebase --continue;If the commit becomes empty, Git will prompt you, you cangit rebase --skip。
error: cannot pull with rebase: You have unstaged changes.
Fix:git stash → git pull --rebase → git stash pop;or configurerebase.autoStash true, also availablegit pull --rebase --autostash。
The stash entry is kept in case you need it again.
Pop conflicts, stash is not deleted. Manually after resolving conflicts (ours = current HEAD, theirs = stash)git stash drop. Uncertaingit stash branch tmp-stash。
HEAD detached at origin/main (committed on origin/main)
Reason:git checkout origin/mainChecked out remote-tracking branch (read-only snapshot), HEAD detached.
Fix:Create a branch before losing it:git switch -c fix/rescue;If it has been cut away, just start fromgit reflogFind that commit and branch it.
Interactive Troubleshooting Decision Tree: Collaboration FAQs
Covers six types of symptoms: push rejection, rebase/merge in progress, history being messed up, stash, tags and remote branches. Choose the phenomenon you see and locate it step by step.
1. You just executed on feat/xgit pull origin main(A merge commit has been generated but has not been pushed yet), and I want to go back to before pull.
git reset --hard ORIG_HEAD
# Or: git reflog finds HEAD@{n} before pull, git reset --hard HEAD@{n}2. Merge commit on main9f8e7d6A glitch was introduced, pushed. Undo it.
git switch main && git pull git revert -m 1 9f8e7d6 git push
A colleague said: "I was halfway through rebase and the terminal was closed. Now git status says it is in rebase, and I don't remember where I did it." How would you give me guidance?
Firstgit statusCheck “Last commands done / Next commands to do” and conflict files;git log --oneline -5See which commit has been replayed. If the conflict has been resolved thengit add + git rebase --continue;If not sure,git rebase --abortGo back to the beginning (the branch is restored to its original state) and execute again..git/rebase-merge/downdone、git-rebase-todoDocumentation also documents progress. worst case scenariogit reflogThe branch location before rebase can be found in (rebase (start)previous entry).
Verified instructional videos
Official documentation
Video storyboard (about 100 seconds)
Picture: red alarm light and the word "rejected" in the terminal. The character reaches out to press the force button, but is stopped by a hand.
Narrator: If there is an accident, stop first. The first command is always git status.
Screen: Three branches: in progress, not pushed, and pushed, leading to abort, ORIG_HEAD and revert respectively.
Narrator: Use abort when the operation is in progress; use ORIG_HEAD or reflog when it is completed but has not been pushed; it has been pushed to a shared branch, and you can only use revert to append reverse commits.
Screen: A team configuration list is lit up one by one: pull.rebase, fetch.prune, zdiff3, rerere, force-if-includes.
Narrator: Good default configurations can prevent most accidents. Write it into your team’s onboarding script.
Command cheat sheet
Merge (M1)
git merge-base main feature git merge-base --is-ancestor A B && echo "A is the ancestor of B" git merge feature # Fast forward if you can git merge --no-ff --log feature #Always generate merge commits git merge --ff-only origin/main # Only fast forward is allowed git merge --squash feature && git commit git merge -X ignore-space-change feature git merge --abort git reset --hard ORIG_HEAD # Undo the just completed merge (not pushed) git revert -m 1 <merge> # Undo the pushed merge git log --oneline --graph --first-parent
Conflict with rerere (M2)
git config --global merge.conflictStyle zdiff3 git config --global rerere.enabled true git diff --name-only --diff-filter=U git ls-files-u git show :1:path # base :2: ours :3: theirs git checkout --ours path; git checkout --theirs path git checkout -m path # Regenerate conflict markers git mergetool git add path # 2.56+: git add --resolved git diff --check # Residual conflict markers / whitespace errors git rerere status; git rerere forget path
Rebase (M3)
git rebase origin/main
git rebase --continue | --skip | --abort
git rebase -i origin/main # pick/reword/edit/squash/fixup/drop
git commit --fixup=<sha> # After:
git rebase -i --autosquash origin/main
git rebase -i --update-refs origin/main # Overlay branches
git rebase --onto main feature-a feature-b
git rebase origin/main --exec "make test"
git range-diff origin/main feature@{1} featurecherry-pick / stash / worktree(M4)
git cherry-pick -x <sha> [<sha>…]
git cherry-pick A^..B
git cherry -v release main
git stash push -u -m "msg" [-- path]
git stash list ; git stash show -p stash@{1}
git stash pop | apply [--index] | drop
git stash branch new-branch stash@{0}
git worktree add -b hotfix/x ../app-hotfix v1.2.0
git worktree list ; git worktree remove ../app-hotfix ; git worktree pruneRemote and Tracking (M5)
git fetch --prune git branch -vv; git status -sb git log --oneline main..origin/main # Remote extra commits git push -u origin feat/x git branch -u origin/feat/x git pull --rebase git push --force-with-lease --force-if-includes git push origin --delete feat/x git branch -vv | grep ': gone]' git branch --delete-merged # 2.56+
PR(M6)
git switch -c feat/123-desc origin/main git diff --stat origin/main...HEAD # PR diff (three points) git log --oneline origin/main..HEAD # PR commits (two points) git fetch origin pull/57/head:review/57 # GitHub git check-ref-format --branch feat/123-desc git merge --squash origin/feat/x && git commit -m "feat: … (#123)" \ -m "Co-authored-by: Name <email>"
Commit specifications and tags (M7)
git commit -m "feat(api)!: remove /count" -m "BREAKING CHANGE: …" --trailer "Refs: #88" git tag -a v1.3.0 -m "v1.3.0" git push origin v1.3.0 # or git push --follow-tags git tag -l "v*" --sort=-v:refname git describe --tags --always --dirty git log v1.2.0..HEAD --format='- %s (%h)' git shortlog -sn v1.2.0..HEAD
Collaborative configuration of baselines and safety nets (M8)
git config --global pull.rebase true
git config --global fetch.prune true
git config --global push.autoSetupRemote true
git config --global push.useForceIfIncludes true
git config --global push.followTags true
git config --global rebase.autoSquash true
git config --global rebase.updateRefs true
git config --global rebase.autoStash true
git reflog -20 ; git reset --hard HEAD@{n}Confusing comparison
| A | B | difference |
|---|---|---|
-s ours | -X ours | The former discards all the opponent's changes; the latter only favors our side on the conflict hunk. |
in merge--ours | in rebase--ours | merge: current branch; rebase: upstream (new base point) - your commit is theirs |
git diff A..B ≡ git diff A B | git diff A...B | Two-point comparison of snapshots at both ends; three-point comparison of merge-base(A,B) and B |
git log A..B | git log A...B | B has commits that A does not; commits unique to both sides (symmetric difference) |
HEAD~2 | HEAD^2 | Go back two generations along the first parent; merge the commit's second parent commit |
--force-with-lease | --force-if-includes | Whether remote is still the value I last saw; whether I have consolidated the value of the remote-tracking branch |
| lightweight tags | Notes label | Reference only; independent tag object (tagged by, date, message, signable) |
Comprehensive experiment + final exam
/versioninterface, Bob is responsible for changing the welcome language to configurable (GREETINGenvironment variables). Both of them need to reviseapp.pysame section of the README. Team agreement: feature branch + PR; before PR, you must rebase to the latest main and organize the history (wip/fixup commits are not allowed); the merge method isrebase + fast forward(linear history); commits follow Conventional Commits; releases are tagged with notes. please~/git-lab/collabCompleted in (the starting point is main in Lesson 1:db1616e, already labeled v1.0.0, v1.1.0).bash ~/bootstrap-git-lab.sh --force # Lesson 1 script: Restore origin to courseware status bash ~/setup-collab.sh # Script for module 0: rebuild alice/bob for d in ~/git-lab/collab/alice ~/git-lab/collab/bob; do git -C "$d" config merge.conflictStyle zdiff3 git -C "$d" config rerere.enabled true git -C "$d" config pull.rebase true git -C "$d" config fetch.prune true git -C "$d" config rebase.autoSquash true git -C "$d" config push.useForceIfIncludes true done git -C ~/git-lab/collab/alice describe --tags # v1.1.0-1-gdb1616e
cd ~/git-lab/collab/alice && git switch -c feat/10-version
cat >> app.py <<'EOF'
@app.route("/version")
def version():
return os.getenv("APP_VERSION", "dev") + "\n"
EOF
git commit -qam "feat(api): add /version endpoint"
echo "- GET /version: returns APP_VERSION" >> README.md && git commit -qam "wip docs"
sed -i 's/"dev"/"0.0.0-dev"/' app.py && git commit -qam "tmp"
git push -u origin feat/10-versioncd ~/git-lab/collab/bob && git switch -c feat/11-greeting
sed -i 's/f"Hello from myapp! I have been seen/f"{os.getenv(\x27GREETING\x27, \x27Hello from myapp!\x27)} I have been seen/' app.py
grep -n GREETING app.py
echo "- GREETING: greeting text" >> README.md
cat >> app.py <<'EOF'
@app.route("/greeting")
def greeting():
return os.getenv("GREETING", "Hello from myapp!") + "\n"
EOF
git commit -qam "feat(api): make greeting configurable via GREETING"
git fetch -q && git rebase origin/main
git switch main && git pull -q && git merge --ff-only feat/11-greeting && git push -q origin main
git push -q origin --delete feat/11-greeting 2>/dev/null; git branch -d feat/11-greeting
12: return f"{os.getenv('GREETING', 'Hello from myapp!')} I have been seen {count} times.\n"
in sed\x27is a single quote (supported by GNU sed; please use an editor to modify this line on macOS). Bob's PR is merged by "rebase + fast forward":--ff-onlyMain is guaranteed to be linear. Bob appended at the end of the file/greeting, appended with Alice/versionare in the same position - this will cause a conflict.
cd ~/git-lab/collab/alice git fetch git log --oneline feat/10-version..origin/main # Bob’s commit git rebase origin/main
d1cadba feat(api): make greeting configurable via GREETING
Auto-merging app.py
CONFLICT (content): Merge conflict in app.py
Rebasing (1/3)error: could not apply 298f3e6... feat(api): add /version endpoint
…
$ tail -12 app.py
<<<<<<< HEAD
@app.route("/greeting")
def greeting():
return os.getenv("GREETING", "Hello from myapp!") + "\n"
||||||| parent of 298f3e6 (feat(api): add /version endpoint)
=======
@app.route("/version")
def version():
return os.getenv("APP_VERSION", "dev") + "\n"
>>>>>>> 298f3e6 (feat(api): add /version endpoint)
first commit (feat(api): add /version endpoint) conflict at the end of app.py (both sides are appended after healthz and the ancestor section is empty): both sections must be retained. Edit file, keep/greeting with /versionTwo functions (two empty lines before each), delete conflict markers. The second commit (wip docs) will conflict again at the end of the README, and the same two lines will remain.
grep -c '[<=>|]\{7\}' app.py README.md # Both should be 0
python3 -c "import ast; ast.parse(open('app.py').read()); print('syntax ok')"
git add app.py README.md && git rebase --continue # Repeat in case of README conflict: Edit → add → --continue
If subsequent commits conflict in the same place again, rerere may be automatically applied (seeResolved … using previous resolution). After all is completedgit log --oneline origin/main..There should be 3 commits.
git rebase -i origin/main
pick xxxxxxx feat(api): add /version endpoint fixup yyyyyyy tmp reword zzzzzzz wip docs # Change to: docs: document /version endpoint
Pay attention to the order: puttmpThat line is moved below the first commit and changed to fixup.
git log --oneline origin/main..
git range-diff origin/main feat/10-version@{u} feat/10-version | head
git push --force-with-lease --force-if-includes
c41d2e8 docs: document /version endpoint 7a9b0f3 feat(api): add /version endpoint
cd ~/git-lab/collab/bob && git switch main && git pull -q git log --oneline origin/main..origin/feat/10-version git diff origin/main...origin/feat/10-version git merge --ff-only origin/feat/10-version && git push -q origin main git push -q origin --delete feat/10-version
cd ~/git-lab/collab/alice && git switch main && git pull -q && git fetch --prune git branch -D feat/10-version git log v1.1.0..HEAD --format=%s # There is feat → MINOR: v1.1.0 → v1.2.0 git tag -a v1.2.0 -m "v1.2.0" -m "$(git log v1.1.0..HEAD --format='- %s')" git push origin v1.2.0 git describe git log --oneline --graph -5
docs: document /version endpoint feat(api): add /version endpoint feat(api): make greeting configurable via GREETING docs: add local run instructions v1.2.0 * c41d2e8 (HEAD -> main, tag: v1.2.0, origin/main) docs: document /version endpoint * 7a9b0f3 feat(api): add /version endpoint * d1cadba feat(api): make greeting configurable via GREETING * db1616e docs: add local run instructions * f4ac97b (tag: v1.1.0) Merge branch 'hotfix/redis-timeout'
git pull --no-rebaseBefore generating a merge commit, usegit reflog with git reset --hard ORIG_HEADrestore; or usegit worktreeMake a hotfix on v1.1.0 andcherry-pick -xReturn to main (M4). After completion, return to Module 0 to redo the collaboration readiness self-assessment.Open-ended self-assessment (answer yourself first, then expand for reference answers)
1.whengit mergeWill it fast forward? When will the merge commit be generated?
When the current branch is the ancestor of the merged branch (merge base == current branch commit), fast forward and only move the pointer; when both sides have commits after merge base, a three-way merge is performed to generate two parent merge commits.--no-ffForce a merge commit to be generated,--ff-onlyRefuse when fast forwarding is not possible.
2.Why does the commit hash change after rebase? What collaboration risks does this pose?
The hash is calculated from tree, parent, author, committer and information; parent (and committer time) changes after replay. Old commits and new commits in the hands of others are considered different commits. Duplicate commits or conflicts will occur after pull, so do not rewrite the history that others have based on their work.
3.rebase in conflict--ours and --theirsWhat do they mean?
ours is the upstream/new base (the new history being built), and theirs are the commits you're replaying - as opposed to in merge.
4. origin/mainWhen will it be updated?git statusIs “up to date” credible?
Only fetch (including pull) and successful push will update it. status is not connected to the Internet and is only compared with the local snapshot, so it needs to be fetched first.
5.Why recommended--force-with-lease --force-if-includesinstead of-f?
-fUnconditional coverage; lease ensures that the remote is still the value you last saw; if-includes further requires that you have integrated the value of the remote-tracking branch into the local to prevent background fetch from invalidating the lease.
6.A merge commit that has been pushed to main introduces a glitch, what is the correct way to undo it? What should I pay attention to when re-merging this feature later?
git revert -m 1 <merge>Append a reverse commit without rewriting the shared history. When re-merging in the future, the original commit is considered "merged", and you need to revert the revert commit (or rebase the feature into a new commit) before merging and repairing it.
Final exam (12 questions, covering all modules)
Sources and imprints
| Topic | Verify conclusion | Source (Accessed on 2026-11-15) |
|---|---|---|
| Git 2.56 | Newgit add --resolved(Only the resolved conflict paths are temporarily stored, and aborted when residual conflict markers are found);git branch --delete-merged;git replay --linearize(analogrebase --no-rebase-merges); experimentalgit historyNewdrop;fetch.followRemoteHEAD;git cherry-pickDocumentation clarification--no-commitNot setCHERRY_PICK_HEAD | git/git RelNotes 2.56.0 |
| ort default policy | From 2.34ortreplacerecursiveBecomes the default merge strategy; first step towards deprecating and removing merge-recursive in 2.50 | RelNotes 2.34.0 · 2.50.0 |
| zdiff3 | 2.35 Added “Zealous diff3” conflict style | RelNotes 2.35.0 |
| rebase --update-refs | 2.38 Introduction | RelNotes 2.38.0 |
| Non-interactive --autosquash | Non-interactive rebase is also supported starting from 2.44--autosquash(still not compatible with apply backend) | RelNotes 2.44.0 |
| push --force-if-includes | 2.30 Introduction | RelNotes 2.30.0 |
| pull fork prompt | Not configured since 2.27pull.rebaseWarn when pulling; fixed in 2.33.1/2.34--ff-onlyEdge cases with rebase backend | RelNotes 2.27.0 · 2.34.0 |
| commit --trailer | 2.32 Introduction | RelNotes 2.32.0 |
| Command behavior and output | The "actual running results" of this lesson are obtained by running the script on Git 2.51.2 (Git for Windows): ff-only rejection, ort merge, zdiff3 conflict mark, ls-files -u, rerere recording and reuse, rebase -i todo (including update-ref), push rejection fetch first / stale info / remote ref updated since checkout, describe, stash, worktree, cherry-pick -x | git-scm.com/docs |
| Git 3.0 plan | Planned (not yet released): default branch name main, default SHA-256 for new repositorys, default reftable, etc. | BreakingChanges |
| normative | Conventional Commits 1.0.0;Semantic Versioning 2.0.0 | conventionalcommits.org · semver.org |
| Platform PR merge method | Description of GitHub’s three merge methods; platform details are expanded in Lessons 3 and 4 | GitHub Docs: About merge methods |
Video verification instructions
The following videos have been verified to have the same title, channel and video ID through the YouTube oEmbed interface (2026-11-15): ByteByteGo "Git MERGE vs REBASE: Everything You Need to Know" (0chZFIZLR_0); Academymind "Git MERGE vs REBASE" (CRlGDDprdOQ); GitKraken "Git Tutorial: Rebasing" & Merging" (a_msiOrYLgM); The Modern Coder "Learn Git Rebase in 6 minutes // explained with live animations!" (f1wnYdLEpgI); freeCodeCamp.org "Advanced Git Tutorial - Interactive Rebase, Cherry-Picking, Reflog, Submodules and more" (qsTthZi23VE), "Git for Professionals Tutorial - Tools & Concepts for Mastering Version Control with Git" (Uszj_k0DGsg), "Git and GitHub for Beginners - Crash Course" (RGOj5yH7evk); Fireship "13 Advanced (but useful) Git Techniques and Shortcuts" (ecK3EnyGD8o); GitButler "So You Think You" Know Git - FOSDEM 2024" (aolI_Rz0ZqY); Corey Schafer "Git Tutorial: Using the Stash Command" (KLEDKgMmbBI), "Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits" (FdZecVxzJbk); Philomatics "Never* use git pull" (xN1-2p06Urc); Keep On Coding "How To Pull Request in 3 Minutes" (jRLGobWwA3Y); Programming with Mosh "Git Tutorial for Beginners: Learn Git in 1 Hour" (8JJ101D3knE); Missing Semester "Lecture 6: Version Control (git) (2020)" (2sjqTHE0zok). oEmbed does not return the duration and release date, so the card does not have a duration written on it. rerere, worktree, Conventional Commits No verified feature video found, storyboard has been provided. All videos are in English and were recorded earlier than Git 2.56. For new features, please refer to this lesson and official documents.
Audio explanation
The Speech tab uses the browser's Web Speech API (speechSynthesis, zh-CN) read the explanation text aloud in real time, and English terms are pronounced in en-US. The effect depends on the voices installed in the operating system. This courseware does not have MP3 embedded; when offline audio is needed, the transcript can be generated by the TTS service.
Known limitations
- Output labeled "Actual Run Results" from Run First Lesson 1
bootstrap-git-lab.sh, and then follow the experimental steps of this lesson to execute the script on Git 2.51.2. The commits from Lesson 1 (such as f4ac97b, db1616e, tag v1.0.0/v1.1.0) are the same for everyone due to the fixed author and timestamp; the new commits in this lesson use your identity and the current time, and the hashes must be different. The blob hash only depends on the file content and can be matched if you follow the steps strictly. Paths have been rewritten to Linux style. - Hint text will vary slightly between Git versions; new options in Git 2.56 (
git add --resolved、git branch --delete-merged) does not actually run on local 2.51, subject to RelNotes description. - This lesson uses a local bare repository to simulate remote, without PR page, review and branch protection; platform-related behaviors (refs/pull/*, specific implementation of the merge button, whether Rebase and merge retain hashes) are subject to the platform documentation, explained in detail in Lessons 3 and 4.
- The use of sed to resolve conflicts in one line in the experiment is only for demonstration. In practice, please check each point in the editor or merge tool. macOS BSD sed needs to be written
sed -i ''。 - The hashes in the animation are schematic (partly taken from actual operation) and are used to illustrate the mechanism.