假设我在本地分支上有以下提交历史:

A -- B -- C

如何在a和B之间插入新的提交?


当前回答

更简单的解决方案:

在最后创建你的新commit, d。现在你有: A——b——c——d 然后运行: $ git rebase -i hash- a Git会打开你的编辑器,它看起来是这样的: 选B 选C 选D 只需要像这样将D移到顶部,然后保存并退出 选D 选B 选C 现在你将拥有: A d b c

其他回答

其实很简单,答案就在这里。假设你在一个分支上。执行以下步骤:

在你想要插入新的提交(在本例中是commit a)之后,从commit创建一个临时分支: A .使用实例 执行更改并提交它们,创建一个commit,我们称它为N: git commit -a -m "Message" (或者git add后跟git commit) 在新的commit(在本例中是提交B和C)之后,将你想要的提交重新基于新的commit: Git重新建立临时分支

(可能你需要使用-p来保存合并,如果有的话-感谢ciekawy不再存在的注释)

删除临时分支: Git分支-d temp

在此之后,历史记录如下:

A -- N -- B -- C

当然,在改基过程中可能会出现一些冲突。

如果您的分支不是本地分支,这将引入重写历史,因此可能导致严重的问题。

假设你想要插入的提交是由D标识的:

# Temporarily append the commit you want to insert to the end 
git cherry-pick D
# Results in D -- A -- B -- C

# Start interactive rebase
git rebase -i B^
# Let's imagine that this is what the rebase prompt looks like:
# pick B Third commit
# pick A Second commit
# pick D First commit
# Then reorder the commits:
# pick B Third commit
# pick D First commit
# pick A Second commit
# Save and exit
# After completing the rebase you will find
# A -- D -- B -- C

这比OP的回答还要简单。

git rebase -i <any earlier commit>. This displays a list of commits in your configured text editor. Find the commit you want to insert after (let's assume it's a1b2c3d). In your editor, for that line, change pick to edit. Begin the rebase by closing your text editor (save your changes). This leaves you at a command prompt with the commit you chose earlier (a1b2c3d) as if it has just been committed. Make your changes and git commit (NOT amending, unlike most edits). This creates new a commit after the one you chose. git rebase --continue. This replays the successive commits, leaving your new commit inserted in the correct place.

当心,这将改写历史,并破坏任何试图拉扯的人。

更简单的解决方案:

在最后创建你的新commit, d。现在你有: A——b——c——d 然后运行: $ git rebase -i hash- a Git会打开你的编辑器,它看起来是这样的: 选B 选C 选D 只需要像这样将D移到顶部,然后保存并退出 选D 选B 选C 现在你将拥有: A d b c

假设提交历史是preA——A——B——C,如果你想在A和B之间插入一个提交,步骤如下:

git rebase -i hash- prea Git会打开你的编辑器。内容可能是这样的: 选A 选B 选C 更改第一个选择编辑: 编辑8668d21 选B 选C 保存并退出。 修改你的代码,然后git添加。&& git commit -m "I" Git rebase—继续

现在你的Git提交历史是preA—A—I—B—C


如果遇到冲突,Git将在此提交时停止。您可以使用git diff来定位冲突标记并解决它们。在解决所有冲突后,您需要使用git add <filename>来告诉git冲突已经解决,然后重新运行git rebase——continue。

如果你想撤销rebase,使用git rebase——abort。