Skip to content

📐 第九章:变基操作 —— 历史的"整形手术"

什么是 Rebase?

如果说 merge 是"把两条路汇合成一条",那 rebase 就是"把你的路接到别人的路后面"。它会把你分支上的提交"重放"到目标分支的最新位置上。

text
Rebase 前:
        C---D  (feature)
       /
  A---B---E---F  (main)

Rebase 后:
              C'---D'  (feature)
             /
  A---B---E---F  (main)

注意:C' 和 D' 是全新的提交(哈希值变了),不是原来的 C 和 D

基本 Rebase 操作

bash
# 场景:你在 feature 分支上开发,main 分支有了新的提交
# 你想把 feature 分支的提交"挪到" main 的最新提交后面

git switch feature/商品详情

# 把当前分支变基到 main 上
git rebase main
Successfully rebased and updated refs/heads/feature/商品详情.

# 变基完成后,切回 main 合并(此时会是 fast-forward)
git switch main
git merge feature/商品详情

交互式 Rebase —— 整理提交历史

交互式 Rebase 是 Git 最强大的功能之一。它可以让你修改、合并、删除、重新排列提交。就像给你的提交历史做一次"编辑"。

bash
# 对最近 3 次提交进行交互式 rebase
git rebase -i HEAD~3

# 这会打开编辑器,显示类似:
pick a1b2c3d feat: 添加商品列表页面
pick b2c3d4e fix: 修复价格显示问题
pick c3d4e5f feat: 添加商品详情页面

# Rebase f4e5d6c..c3d4e5f onto f4e5d6c (3 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
text
# 把提交合并(squash):
pick a1b2c3d feat: 添加商品列表页面
squash b2c3d4e fix: 修复价格显示问题
pick c3d4e5f feat: 添加商品详情页面

# 改完后保存退出,Git 会让你编辑合并后的提交信息

💡 提示: 交互式 Rebase 的常见用法:合并琐碎的提交:把 "fix typo"、"fix again"、"真的修好了" 合并成一个有意义的提交修改提交信息:用reword改写提交信息删除无用的提交:用drop去掉调试代码的提交重新排列提交:改变提交的顺序

Rebase 的黄金法则

⚠️ 注意: ⚠️ 永远不要对已经推送到公共分支的提交进行 rebase!为什么?因为 rebase 会改变提交的哈希值(相当于创建了全新的提交)。如果你已经 push 到远程,你的队友已经基于这些提交在工作了。你 rebase 之后再 push,队友的本地历史和远程历史就会"分叉",造成一堆冲突。记住:rebase 本地未 push 的提交 = 好习惯,rebase 已经 push 的提交 = 引发混乱

Rebase vs Merge 对比

对比项MergeRebase
历史记录保留完整历史(包括分支结构)线性历史,更干净
提交哈希不变改变
合并提交产生额外的合并提交不需要合并提交
安全性更安全,不修改历史已 push 的提交不能 rebase
适用场景合并公共分支、保留完整历史同步主分支、整理本地提交
冲突解决一次性解决所有冲突可能需要逐个提交解决冲突