Git 之 交互式 rebase

使用 git rebase -i <branch> 可以进入交互式模式,可以对 某一范围内的提交 进行重新编辑

默认情况下,直接使用 git rebase -i 命令的操作对象为自最后一次从 origin 仓库拉取或者向 origin 推送之后的所有提交。

合并提交

假设我要把 master 上红色区域的分支合并成一个提交

《Git 之 交互式 rebase》

首先找到起始 commit 的 前一个,也就是 865b2ac,rebase 会显示当前分支从这个 comimt 之后的所有 commit。

执行 git rebase -i 865b2ac,会自动唤出编辑器,内容如下:

《Git 之 交互式 rebase》

这些信息表示从 865b2ac commit 操作后有 4 个提交。每个提交都用一行来表示,按时间顺序展示,首行是最早的提交,末行是最新的提交,行格式如下:

(action) (partial-sha) (short commit message)

当修改这个文件后,git 会依次把这些 commit 按照 action 重新执行。action 有很多种,默认都是 pick,即使用该 commit,不作任何修改。

我们现在想把后三个提交合并到第一个中去,这里需要用到 squash,该 action 表示 使用该提交,但是把它与前一提交合并,所以只需把后四个的 action 改为 squash 即可。

《Git 之 交互式 rebase》

保存之后,会唤出编辑器提示基于历史的提交信息创建一个新的提交信息,也就是需要用户编辑一下合并之后的 commit 信息,更改提示信息并保存即可。

合并完之后的历史记录:

《Git 之 交互式 rebase》

拆分提交

如果想把某个 commit 拆分成多个 commit,可以使用 edit 作为 action,edit 表示 使用该提交,但是先在这一步停一下,等我重新编辑完再进行下一步。

初始状态如下:

《Git 之 交互式 rebase》

just add a new line 这个 commit 修改了两个文件 myfile.txtanothorfile.txt,我们希望把它拆成两个 commit,每个文件的修改各提交一个 commit

执行 git rebase -i 13243ea,然后修改 865b2ac 这个 commit 的 action 为 edit

《Git 之 交互式 rebase》

保存并退出后,git 会提示在 865b2ac 上停止了

➜  git rebase -i 13243ea
Stopped at 865b2ac... just add a new line
You can amend the commit now, with
    git commit --amend
Once you are satisfied with your changes, run
    git rebase --continue

这里可以使用 git commit --amend 命令对 commit 信息进行重新编辑(什么是 git commit –amend

我们这里是要拆分 commit,所以要先对 commit 内容 reset,然后重新提交

➜  git reset HEAD^ # 撤销提交
Unstaged changes after reset:
M   myfile.txt
M   anotherfile.txt
➜  git add myfile.txt # 拆解出第一个提交
➜  git commit -m 'first part of split commit'
[detached HEAD d0727f7] first part of split commit
 1 file changed, 1 insertion(+)
➜  git add anotherfile.txt # 拆解出第二个提交
➜  git commit -m 'second part of split commit'
[detached HEAD 2302fc7] second part of split commit
 1 file changed, 1 insertion(+)
 create mode 100644 anotherfile.txt
➜  git rebase --continue
Successfully rebased and updated refs/heads/master.

拆分完成后使用 git rebase --continue 即结束 rebase,结果如下:

《Git 之 交互式 rebase》

删除提交

如果想删除某个提交,使用 git rebase -i 后直接在编辑器中删除那一行 commit 即可

《Git 之 交互式 rebase》

假设删除的是 commit 2,那么编辑完成后 git 会比较 commit 1 与 commit 3 的差异,如果有冲突,需要手动解决冲突后 add 并 git rebase --continue

《Git 之 交互式 rebase》

    原文作者:时间被海绵吃了
    原文地址: https://segmentfault.com/a/1190000012897755
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞