git rebase 修改中间的commit

0. 前言

今天在移植最新版本 kfence 功能的时候,一共需要移植大概40多个 patch,中间有很多patch 存在冲突,需要手动修改后才能合并。当所有的patch 都合并完成进行编译的时候,发现其中一个 patch 手动合并出了个错误。

假如共有 40 个 patch,编号 1 - 40,现在问题是第 20 个patch 需要再修改一下,而 21 - 40 的patch 有很多手动修改的,怎么能快速有效的在不 reset 的基础上修改第 20 个patch呢?

这就是本文需要说明的 git rebase命令。

1. git rebase -i HEAD~n

先来看下 option -i:

-i
--interactive
Make a list of the commits which are about to be rebased. Let the user edit that list before rebasing. This mode can also be used to split commits (see SPLITTING COMMITS below).

The commit list format can be changed by setting the configuration option rebase.instructionFormat. A customized instruction format will automatically have the long commit hash prepended to the format.

See also INCOMPATIBLE OPTIONS below.

通过该选项,产生一个将要 rebase 的commit list,可以让用户在 rebase 之前进入交互的模式。

HEAD~n,会列出从 HEAD 开始的倒数 n commit list,例如 n = 4 时:

当执行 git rebase -i HEAD~4 命令,就会弹出从 HEAD 开始的倒数 4 个 commit list,最后一个是 HEAD commit。

当将第一行 commit,即倒数第 4 个 commit 的命令从 pick 改成 edit 时,则代码rebase 停在这个 commit,用以 amend 处理。

当保存修改并退出交互之后,就会发现倒数第 4 个commit 进入stop 状态,等待 amend。

剩下来就简单了:

  • 修改代码;
  • git add
  • git commit --amend
  • git rebase --continue

2. 交互中的命令

在交互的窗口中,除了之前说的 edit 命令,本文也补充说下其他的命令:

  • p/pick,保持 commit;
  • r/reword,保留commit,但是需要修改 commit  message;
  • e/edit,保留 commit,但这里需要停下来等到 amend;
  • s/squash,保留commit,但会将该 commit 合并到前一个 commit 中;
  • f/fixup,类似 squash,但是不会保留 commit message;
  • x/exec,等于在 shell 中运行命令;
  • d/drop,丢弃该 commit;

官方文档:

https://git-scm.com/docs/git-rebase/

猜你喜欢

转载自blog.csdn.net/jingerppp/article/details/133138361