自从成为 Linux 内核 Reviewer 后,我发现经常有需求去提交内核补丁集,然而,补丁集可能存在问题需要修复,但并不是最后一个commit,即不符合 git commit –amend 的条件。我们以如下 commit 列表为例进行说明,如果commit 5e43fda6c7e3 的代码提交信息有问题需要修改,则需要使用交互式变基(interactive rebase)来完成。

# 查看提交历史,找到要修改的提交之前的那个提交
$ git log --oneline
ce5603d746e1 (HEAD -> update_process) docs/zh_CN: update the translation of process/5.Posting.rst
5e43fda6c7e3 docs/zh_CN: update the translation of process/2.Process.rst
6cc2550da7eb docs/zh_CN: update the translation of process/7.AdvancedTopics.rst
1c3590dfdbf0 docs/zh_CN: update the translation of process/6.Followthrough.rst
a9a9c7f57db1 docs/zh_CN: update the translation of process/1.Intro.rst

1. 启动交互式变基

# 启动交互式变基,即 git rebase -i COMMIT_HASH^
# 替换 COMMIT_HASH 为要修改的提交之前的提交哈希
git rebase -i 5e43fda6c7e3^

2. 标记要修改的提交

在打开的编辑器中:

  1. 找到要修改的提交行,即 pick ce5603d746e1;
  2. 将行首的 pick 改为 reword(或简写 r),即,使用当前 commit,但是仅修改代码提交信息;
  3. 保存文件并关闭编辑器; 示例:
reword ce5603d746e1 docs/zh_CN: update the translation of process/5.Posting.rst
pick 5e43fda6c7e3 docs/zh_CN: update the translation of process/5.Posting.rstv

3. 修改提交信息

Git 自动会打开新的编辑器修改代码提交信息:

  1. 编辑提交信息
  2. 保存文件并关闭编辑器 上述操作即可完成变基操作,再次试用 git log –oneline 查看代码提交信息即可发现代码提交信息已修改。

4.F&Q

  • 如果遇到冲突:
# 解决冲突后
git rebase --continue
  • 若想放弃操作:
git rebase --abort