Git 之 交互式 rebase

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

默认状况下,直接使用 git rebase -i 命令的操做对象为自最后一次从 origin 仓库拉取或者向 origin 推送以后的全部提交。segmentfault

合并提交

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

clipboard.png

首先找到起始 commit 的 前一个,也就是 865b2ac,rebase 会显示当前分支从这个 comimt 以后的全部 commit。编辑器

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

clipboard.png

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

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

当修改这个文件后,git 会依次把这些 commit 按照 action 从新执行。action 有不少种,默认都是 pick,即便用该 commit,不做任何修改。code

咱们如今想把后三个提交合并到第一个中去,这里须要用到 squash,该 action 表示 使用该提交,可是把它与前一提交合并,因此只需把后四个的 action 改成 squash 便可。对象

clipboard.png

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

合并完以后的历史记录:ip

clipboard.png

拆分提交

若是想把某个 commit 拆分红多个 commit,可使用 edit 做为 action,edit 表示 使用该提交,可是先在这一步停一下,等我从新编辑完再进行下一步。

初始状态以下:

clipboard.png

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

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

clipboard.png

保存并退出后,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,结果以下:

clipboard.png

删除提交

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

clipboard.png

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

clipboard.png

相关文章
相关标签/搜索