如何防止 git 认为我进行了重命名

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

27715 次浏览

Why Git Thinks Your Files Are Copies

Git tracks content, not filenames. As a result, if two files have substantially similar content, git will think you copied or renamed the file. If you read git-log(1), you will learn:

The similarity index is the percentage of unchanged lines, and the dissimilarity index is the percentage of changed lines. It is a rounded down integer, followed by a percent sign. The similarity index value of 100% is thus reserved for two equal files, while 100% dissimilarity means that no line from the old file made it into the new one.

So, assuming your similarity index is 100%, git will think that's a copy. Your best bet is to add a sensible log message or note (see git-notes(1) for more on that) to explain what's going on if you don't think git is doing the right thing.

Adjusting the Similarity Index

You might also try adjusting the values git uses for considering something a copy or rename. The manual for git-log(1) says:

-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>.

Again, this won't help you if the files are mostly similar, but you can certainly use these values to tune how similar they need to be in order to be considered copies or renames. Your mileage may vary.

If you are in a moment just before a commit and "you feel bad that git went mad", then just undo the addition of the ambiguous file git thought you renamed, perform a commit, then add the ambiguous file again and commit:

git reset ambiguous_file_git_thought_you_renamed
git commit
git add ambiguous_file_git_thought_you_renamed
git commit

This worked for me.

Double check no renaming took place:

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

"M" at the beginning means modified, "R" mean Renamed. Notice no Renamed exists here.

There is an "accepted" answer, but it does not give any hint on how to answer the question.

The correct answer, from git-log(1) and git-diff(1) is:

   --no-renames
Turn off rename detection, even when the configuration
file gives the default to do so.

If you have modified file A, B and C; and deleted file D, E and F; there is a chance git thinks D is renamed to A, or something similar.

The simplest solution is to split file modifications and deletions into two commits.