Skip to main content

git-stack-branch

📅 2026-04-16 ✏️ 2026-04-16 CS
No related notes

1 · git-stack-branch#

https://andrewlock.net/working-with-stacked-branches-in-git-part-1/ https://andrewlock.net/working-with-stacked-branches-in-git-part-2/

S: 开发中大型功能时,通常在单个长分支上做所有工作,最终提交一个巨大的 PR。 C: 大 PR 难以 review——范围大、缺乏模块化、reviewer 难以理解变更思路;同时作者在等待 review 时被阻塞,无法继续后续工作。 Q: 如何组织分支和 PR,使 review 更容易、更快获得反馈,同时自己不被阻塞? A: 使用 stacked branches——将功能拆分为多个线性依赖的小分支,每个分支对应一个小而内聚的 PR。

1.1 · 核心概念

stacked branches = 多个分支在彼此基础上线性创建:

main → feature/model → feature/api → feature/ui

1.2 · 两个核心机制

  1. --update-refs:rebase 时自动移动栈中所有中间分支指针,否则需手动 git branch --force 逐个修正
  2. --onto:PR 被 squash merge 后,原 commit SHA 变了,git rebase origin/main 会冲突;用 git rebase <已合并分支> --onto origin/main 跳过已合并 commit
# 全局开启,必备
git config --global rebase.updateRefs true
git config --global rebase.autosquash true

1.3 · 常用操作

修改栈底层 commit:在栈顶修改后 git rebase -i --update-refs main(配合 git absorb / --autosquash

rebase 到 maingit rebase origin/main(已开启 updateRefs,中间分支自动跟随)

批量 pushgit push --force-with-lease origin branch1 branch2 branch3

PR 合并后重整栈

git rebase <已合并分> --onto origin/main
git branch -D <已合并分>

1.4 · 提效工具(非必需)

  • git absorb:自动生成 fixup commit 到正确位置
  • --autosquash:rebase 时自动归位 fixup/squash commit
  • git push-stack(自定义 alias):一键 push 整个栈