如何将一个提交 replay 到已经包含该提交的分支上?

14
假设我们的提交历史记录如下:
    1--2--3--4
             ^
            HEAD
其中4是最近的提交。
有没有一种方法可以将提交2(即1和2之间的差异)的更改重新应用到提交4上?
您可能想知道为什么有人要这样做。假设这是您的生产分支,它始终应处于工作状态。早些时候,当提交历史记录如下所示时:
     1--2
        ^
       HEAD
您意识到提交2可能会破坏一切,因此迅速推出了一个还原提交,提交3还原了提交2。然后某人进行了提交4,其中包含您希望保留的良好内容。这时您意识到提交2实际上是可以的,因此您想在提交4的基础上重放它。

你的历史记录是向哪个方向发展的?提交4是提交5的父提交还是反过来? - Code-Apprentice
3个回答

17

git cherry-pick A 可以做到这一点。

请参阅http://git-scm.com/docs/git-cherry-pick
给定一个或多个现有的提交,应用每个提交所引入的更改,并为每个提交记录一个新的提交。 这需要您的工作树是干净的(没有来自 HEAD 提交的修改)。

例如 git cherry-pick master~4 master~3


git cherry-pick A 创建一个空提交,因为提交已经存在。指定 --keep-redundant-commits 只会创建一个空提交并保留它。有没有办法将 1-2 之间的差异应用到 HEAD? - Pratik
你需要先使用 git rebase -i sha-commit-1 命令将其删除,然后再使用 git cherry-pick sha-commit-2 命令创建一个新的提交,其中包含被删除提交的更改。 - Anateus

4

You are probably wondering why anyone would want to do that. Lets say that this is your production branch that is always supposed to be in a working state. Lets say that earlier, when the commit history looked like

1--2
   ^
  HEAD

You had a realization and thought that commit 2 might break everything, and so you quickly pushed out a revert commit, where commit 3 reverts commit 2. Then someone makes commit 4 that contains good content you want to keep. At this point you realize that commit 2 was actually ok, and so you want to replay it on top of 4.

如果您想撤销提交3(撤销提交2),则需要恢复提交2:

git revert 3

1
如果您想撤销提交3和4引入的更改,那么请尝试以下操作:
$ git diff commit2..commit4 | git apply -R

这仅在您想要还原的提交之间的历史记录是线性的情况下起作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接