一文讲清楚 git rebase

内容分享1个月前发布 DunLing
0 0 0

今天我来系统地讲清楚 Git rebase,尤其是 git rebase xxx onto yyy 这类命令的含义。


一、什么是 rebase?

git rebase 的本质:
把一条分支上的提交,重新应用到另一条分支的后面,就像把分支“基座”换到新的起点上。

  • merge 是把两个分支的历史合并在一起,保留分叉痕迹。
  • rebase 是“搬家”,把你的提交放到目标分支的最新位置,好像一直在那个分支上开发的一样(历史更干净)。

二、基本用法

1. 最常见的形式

git checkout feature
git rebase main

意思是:

  • 把 feature 分支上的提交,重新应用到 main 分支的 最新提交 后面。
  • 效果:feature 的基点从原来的地方,变成了 main 的最新提交。

2. –onto 的形式

git rebase –onto <newbase> <upstream> <branch>

解释:

  • newbase:新的基点(要搬到这里)
  • upstream:旧的起点(从哪儿开始“切”)
  • branch:要 rebase 的分支

过程相当于:

  1. 找出 branch 相比于 upstream 多出来的提交。
  2. 把这些提交“剪下来”。
  3. 粘贴到 newbase 后面。

三、例子说明

假设提交历史是这样的:

A---B---C (main)
         
          D---E---F (feature)
  • main 分支在 C
  • feature 分支有额外提交 D、E、F。

情景1:普通 rebase

git checkout feature
git rebase main

结果:

A---B---C (main)
             
              D'--E'--F' (feature)

D、E、F 被“重新应用”在 C 之后(实则是新提交 D’、E’、F’)。


情景2:带 onto

git rebase --onto main C feature

含义:

  • upstream = C
  • 找出 feature 分支比 C 多的提交(即 D、E、F)。
  • newbase = main
  • 把 D、E、F 移到 main 上。

效果:

A---B---C (main)
         
          D---E---F   (原 feature 会游离/临时保存)
             ↓
A---B---C---D'--E'--F' (feature)

(等价于普通的 git rebase main,由于 upstream 就是 main 的最新提交)


情景3:复杂一点

假设:

A---B---C---D (main)
     
      E---F---G (feature)

命令:

git rebase --onto D B feature

解释:

  • upstream = B
  • 找出 feature 相比 B 多出来的提交(E、F、G)。
  • newbase = D
  • 把 E、F、G 搬到 D 后面。

结果:

A---B---C---D (main)
                
                 E'--F'--G' (feature)

相当于“把 feature 分支从 B 那里切下来,粘贴到 D 后面”。


四、总结口诀

  • 普通 rebase
  • git rebase target
  • → 把当前分支基点搬到 target 后面。
  • 带 onto 的 rebase
  • git rebase –onto newbase upstream branch
  • → 把 branch 相对 upstream 的提交,剪下来贴到 newbase 后面。

记忆法
–onto 用来“改基点”,upstream 用来“切分提交”,branch 就是要动的分支。

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
none
暂无评论...