gpt4 book ai didi

git - 恢复不在当前分支中的 git 提交

转载 作者:太空狗 更新时间:2023-10-29 14:03:54 24 4
gpt4 key购买 nike

我有 2 个分支:master 和 feature。

• master
• feature

我在功能分支上做了两次提交

• master
• C1 • C2 • feature

现在,我想 merge master 中的 feature。我使用 git merge --squash feature 来 merge 。

• C3 • master     // C3 is the squashed commit
• C1 • C2 • feature

此时,有没有办法从 master 恢复 C1

一个选项是恢复 C1 功能,并在 master 中再次压缩 merge 功能。

最佳答案

是的,您可以使用 merge --squash 恢复一些提交,即使它已包含在聚合中。 git-revert 的工作原理是识别在您识别的提交中引入的更改,然后创建一个新的更改来撤消(“还原”)这些更改。

它使用三向 merge 算法来执行此操作 - 使用要还原的提交作为基础,然后与该提交的祖先和当前提交 (HEAD) 进行比较。这将隔离仅在该提交中引入的更改。

看一个非常人为的例子,想象一下你有一个文件有三个变化(C0C1C2)和这些是每个版本的文件内容:

| C0    | C1    | C2    |
|-------|-------|-------|
| one | one | one |
| two | 2 | 2 |
| three | three | three |
| four | four | FOUR |

现在,如果你想还原C1,我们设置一个三向 merge 以它为基础,C0C2 每一方都要从中进行更改。

在三向 merge 算法中,您会查看每一侧,并将其与底部进行比较。如果所有三行都相等,则将该行原封不动地放入结果中。如果一方进行了更改,则将更改后的行带入结果。 (如果双方都对同一行进行了更改,则将该行标记为冲突。)

设置还原为您提供:

base     sides     result
---- ----- ------
one
/ two \
/ three \
one / four \ one
2 two
three three
four \ one / FOUR
\ 2 /
\ three /
FOUR

您可以看到结果(在右侧)撤消 C1 中引入的更改,因为其中一侧 (C0,在本例中)是唯一的,因此其更改保留在结果中。这具有撤消(“还原”)其中引入的更改的逻辑效果。

This would be true even if you had done a squash merge - in this case, it's looking at the repository's contents. It doesn't matter that CM doesn't actually have C1 as a common ancestor.

您可以在包含这些内容的简单存储库中向自己证明这一点。即使在 Squash merge 之后:

commit 9e7497c7ae34aa35cdb7d7b965a00d56bf0b9dfa
Author: Edward Thomson <ethomson@edwardthomson.com>
Date: Thu Nov 9 10:20:31 2017 +0000

Squashed commit of the following:

commit 8a8a9e73e62e21683e15269d89e1fbfbbf35cfa1
Author: Edward Thomson <ethomson@edwardthomson.com>
Date: Thu Nov 9 10:20:18 2017 +0000

C2

commit d984b27140e48c5faa8968364c415d29dcd7034c
Author: Edward Thomson <ethomson@edwardthomson.com>
Date: Thu Nov 9 10:20:08 2017 +0000

C1

您仍然可以正确还原其中一个组件。在这种情况下,我将还原 C1:

> git revert d984b27
[master 405f108] Revert "C1"
1 file changed, 1 insertion(+), 1 deletion(-)

> git show HEAD
commit 405f1080e24504fa418d423a0755a2123b85ecd8 (HEAD -> master)
Author: Edward Thomson <ethomson@edwardthomson.com>
Date: Thu Nov 9 10:20:42 2017 +0000

Revert "C1"

This reverts commit d984b27140e48c5faa8968364c415d29dcd7034c.

diff --git a/hello.txt b/hello.txt
index 9d980ae..14cf0bc 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1,5 +1,5 @@
Hello, world!
one
-2
+two
three
four

关于git - 恢复不在当前分支中的 git 提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com