【问题标题】:Why does git revert give me conflicts为什么 git revert 会给我带来冲突
【发布时间】:2019-02-24 10:47:25
【问题描述】:

说我有一个空的 git 存储库。这是我执行的命令:

echo 'aaa' > file
git add .
git commit -m 'a'
echo 'bbb' >> file
git commit -am 'b'
echo 'ccc' >> file
git commit -am 'c'

然后我执行git reflog获取日志:

d3f79b4 HEAD@{0}: commit: c
4c79a7f HEAD@{1}: commit: b
a31df0d HEAD@{2}: commit (initial): a

现在我想恢复为commit: b,这意味着我想将file

aaa
bbb
ccc

aaa
bbb

我尝试执行命令:git revert 4c79a7f,但我收到一些关于冲突的错误消息:

error: could not revert 4c79a7f... b
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

file 变成:

aaa
<<<<<<< HEAD
bbb
ccc
=======
>>>>>>> parent of 4c79a7f... b

我不明白为什么会发生这种冲突。

此外,如果我在每次提交时创建三个文件,如下所示:

touch file1
git add .
git commit -m 'a'
touch file2
git commit -am 'b'
touch file3
git commit -am 'c'

我可以恢复到任何历史提交。

我正在学习 git,所以我知道我可以使用 git reset,但我现在想学习 git revert

【问题讨论】:

  • git revert 将尝试通过在您的历史记录中的当前点应用其反向作为新提交来删除相关提交引入的更改。如果提交中引入的更改及其负面影响将应用于随后已删除或更改的文件,则 git 将无法执行此操作,因为它不了解如何执行此操作。例如,如果您将代码行中的一个简单数字从 1 增加到 2:variable += 2; (was 1) 在提交中,然后删除整行,如果您现在尝试恢复此更改,git 将不知道是什么去做。

标签: git git-revert git-merge-conflict


【解决方案1】:

git revert 4c79a7f,您正在尝试恢复(即“撤消”)提交 b,而不是返回它。但是git不知道怎么做:它不知道是否应该保留ccc

【讨论】:

    【解决方案2】:

    当 git 尝试执行revert 时,它会为每个文件生成一个补丁(使用文件的差异格式),这与提交引入的更改的差异完成相反。

    您的“问题”是由于差异格式以及如何应用补丁造成的。

    差异示例:

    diff --git a/GitUI/UserControls/RevisionGrid/RevisionGridToolTipProvider.cs b/GitUI/UserControls/RevisionGrid/RevisionGridToolTipProvider.cs
    index 985995f39..91af87f84 100644
    --- a/GitUI/UserControls/RevisionGrid/RevisionGridToolTipProvider.cs
    +++ b/GitUI/UserControls/RevisionGrid/RevisionGridToolTipProvider.cs
    @@ -23,7 +23,6 @@ public void OnCellMouseEnter()
                 _toolTip.AutoPopDelay = 32767;
             }
    
    -        private int _oldIndex = -1;
             public void OnCellMouseMove(DataGridViewCellMouseEventArgs e)
             {
                 var revision = _gridView.GetRevision(e.RowIndex);
    @@ -36,9 +35,8 @@ public void OnCellMouseMove(DataGridViewCellMouseEventArgs e)
                 var oldText = _toolTip.GetToolTip(_gridView);
                 var newText = GetToolTipText();
    
    -            if (newText != oldText || _oldIndex != e.RowIndex)
    +            if (newText != oldText)
                 {
    -                _oldIndex = e.RowIndex;
                     _toolTip.SetToolTip(_gridView, newText);
                 }
    

    您可以看到添加 (+) 和删除 (-) 的代码。 但是您也可以看到修改的行周围有上下文行。

    如果应用补丁的文件中的上下文行之一已更改,则不会自动应用补丁,并且存在合并冲突。

    这是你的情况。

    您在修改的行上没有冲突,但在上下文行上......

    【讨论】:

    • 从技术上讲,revert 实际上使用了完整的三向合并而不是带有上下文的补丁,但效果是一样的:它是相邻的更改(在补丁中,是上下文行)这就是问题所在。
    猜你喜欢
    • 2018-02-26
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2012-07-18
    相关资源
    最近更新 更多