86

我有两个文件index.htmltemplate.html. 我将大部分内容index.html移入template.html,现在 git 认为我在添加两个文件时进行了重命名。在特定情况下是否可以防止这种情况发生?

4

4 回答 4

69

为什么 Git 认为你的文件是副本

Git 跟踪内容,而不是文件名。结果,如果两个文件具有基本相似的内容,git 会认为您复制或重命名了该文件。如果你阅读 git-log(1),你会学到:

相似性指数是不变行的百分比,不相似性指数是变化行的百分比。它是一个向下舍入的整数,后跟一个百分号。因此,100% 的相似性索引值是为两个相同的文件保留的,而 100% 的不相似性意味着旧文件中没有一行进入新文件。

所以,假设你的相似度指数是 100%,git 会认为那是一个副本。最好的办法是添加一个合理的日志消息或注释(有关更多信息,请参阅 git-notes(1))来解释如果您认为 git 做的事情不正确,会发生什么。

调整相似度指数

您也可以尝试调整 git 用于考虑复制或重命名的值。git-log(1) 的手册说:

-M[<n>], --find-renames[=<n>]

If generating diffs, detect and report renames for each commit. For
following files across renames while traversing history, see --follow. If
n is specified, it is a threshold on the similarity index (i.e. amount
of addition/deletions compared to the file’s size). For example, -M90%
means git should consider a delete/add pair to be a rename if more than
90% of the file hasn’t changed.

-C[<n>], --find-copies[=<n>]    

Detect copies as well as renames. See also --find-copies-harder.
If n is specified, it has the same meaning as for -M<n>.

同样,如果文件大多相似,这对您没有帮助,但您当然可以使用这些值来调整它们需要相似才能被视为副本或重命名。你的旅费可能会改变。

于 2013-02-22T19:28:36.400 回答
29

有一个“已接受”的答案,但它没有给出任何关于如何回答问题的提示。

来自 git-log(1) 和 git-diff(1) 的正确答案是:

   --no-renames
       Turn off rename detection, even when the configuration
       file gives the default to do so.
于 2017-10-18T09:53:57.393 回答
24

如果您在提交之前的某个时刻并且“您觉得 git 疯了”,那么只需撤消 git 认为您重命名的模糊文件的添加,执行提交,然后再次添加模糊文件并提交:

git reset ambiguous_file_git_thought_you_renamed
git commit
git add ambiguous_file_git_thought_you_renamed
git commit

这对我有用。

仔细检查没有重命名:

git diff --name-status -C HEAD^^ HEAD
M       ambiguous_file_git_thought_you_renamed
M       original_file

开头的“M”表示修改,“R”表示重命名。注意这里不存在重命名。

于 2015-12-26T12:08:22.233 回答
0

如果您修改了文件A、B和C;并删除文件 D、E 和 F;git 有可能认为 D 被重命名为 A,或类似的东西。

最简单的解决方案是将文件修改和删除分成两个提交。

于 2020-10-28T05:55:29.053 回答