Git重命名空文件的检测

5
我最近遇到了一个问题,两个分支中将空文件重命名为不同名称并进行合并却没有引起冲突。以下是重新创建此问题的步骤。
  1. Create an empty file.

    git init
    touch empty
    git add empty
    git commit -m "add empty file"
    
  2. Rename it in the branch.

    git checkout -b branch
    git mv empty empty-in-branch
    git commit -m "empty -> empty-in-branch"
    
  3. Rename it differently in the master.

    git checkout master
    git mv empty empty-in-master
    git commit -m "empty -> empty-in-master"
    
  4. Merge branch into master.

    git merge --no-commit branch
    
这里显示的消息是Automatic merge went well; stopped before committing as requestedgit status只显示了新文件empty-in-branch,但没有删除empty-in-master,所以如果在这个阶段提交,我们将得到两个文件。 我希望这会被标记为需要手动解决的合并冲突(即决定保留哪个空文件)。如果原始文件不为空,就会发生这种情况。 空文件是否有影响重命名检测的特殊性?是否有任何参数可以添加到git merge中,以便它能检测到冲突(例如调整合并策略)?

确实是有趣的行为。不确定原因,但是... Git根据文件内容存储文件。因此,两个空文件在技术上被认为是相同的。由于可能存在大量重叠的情况,因此在这里使用一些特殊逻辑是有意义的。 - Barett
它看起来确实可能有针对空文件的特殊处理。但是 Git 已经根据其哈希值仅存储每个对象的一份副本,因此大量重复的空文件和大量重复的非空文件之间没有真正的区别(即没有明显需要特殊处理空文件的必要)。 - Matthew Strawbridge
1个回答

2
此提交更改了递归合并中的重命名操作,不再考虑空文件: https://github.com/git/git/commit/4f7cb99ada26be5d86402a6e060f3ee16a672f16。旧版本的Git仍会将其报告为冲突。请注意保留HTML标签。
$ git --version
git version 1.7.9.5
# ... follow OP instructions to reproduce
$ git merge --no-commit branch
CONFLICT (rename/rename): Rename "empty"->"empty-in-master" in branch "HEAD" rename "empty"->"empty-in-branch" in "branch"
Automatic merge failed; fix conflicts and then commit the result.
$ git status
# On branch master
# Unmerged paths:
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#   both deleted:       empty
#   added by them:      empty-in-branch
#   added by us:        empty-in-master
#
no changes added to commit (use "git add" and/or "git commit -a")

Git不会自动跟踪重命名,因此如果没有重命名检测功能,Git只会看到两个提交都删除了文件empty,并且每个提交都添加了一个新文件。
有一种选项可以更改git-diff的行为(https://github.com/git/git/commit/90d43b07687fdc51d1f2fc14948df538dc45584b),但目前还没有将其作为git merge的选项公开。
其他合并策略似乎也无法提供所需的行为。

谢谢 - 有用的信息。第一个链接说“这将在合并时导致修改/删除冲突,让用户自己解决”,但不幸的是这并没有发生。 - Matthew Strawbridge
那只有当空文件添加内容时才会发生。您可以查看提交上的测试并查看该行为。 - onionjake

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