139

我使用git mv. 现在我想对新文件进行比较,以将其与旧文件(旧的,现在不存在的名称)进行比较。

我该怎么做呢?

4

6 回答 6

150

您需要使用 -M 让 git 在比较时自动检测移动的文件。就像git diffknittl 提到的那样使用对我不起作用。

很简单:git diff -M应该这样做。

此开关的文档是:

-M[<n>], --find-renames[=<n>]
       Detect renames. 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.
于 2012-04-12T09:38:17.097 回答
92

除了knittl 写的内容之外,您还可以随时使用:

git diff HEAD:./oldfilename newfilename

其中HEAD:./oldfilename表示最后一次提交(在 HEAD 中)中的旧文件名,相对于当前目录。

如果您没有足够新的 git,则必须改用:

git diff HEAD:path/to/oldfilename newfilename
于 2011-04-20T14:13:35.707 回答
20

With git 2.9 (June 2016), you won't have to add -M anymore. git diff uses -M by default.

See commit 5404c11, commit 9501d19, commit a9276a6, commit f07fc9e, commit 62df1e6 (25 Feb 2016) by Matthieu Moy (moy).
(Merged by Junio C Hamano -- gitster -- in commit 5d2a30d, 03 Apr 2016)

diff: activate diff.renames by default

Rename detection is a very convenient feature, and new users shouldn't have to dig in the documentation to benefit from it.

Potential objections to activating rename detection are that it sometimes fail, and it is sometimes slow. But rename detection is already activated by default in several cases like "git status" and "git merge", so activating diff.renames does not fundamentally change the situation. When the rename detection fails, it now fails consistently between "git diff" and "git status".

This setting does not affect plumbing commands, hence well-written scripts will not be affected.

The new tests for this feature are here.

于 2016-04-05T19:36:44.077 回答
4

无论出于何种原因,使用HEAD:./oldfilename(或绝对路径)对我不起作用,但HEAD:oldfilename确实如此(感谢 cmn):

git diff HEAD:oldfilename newfilename
git diff 2a80f45:oldfilename f65f3b3:newfilename

高温高压

于 2011-12-26T04:34:07.497 回答
1

git diff -M正如其他人所说的那样激活重命名检测(正如@VonC 指出的那样,它默认从 git 2.9 激活)。但是如果你有一个大的变更集,不精确的重命名检测可能仍然会再次被关闭。Git 将显示如下警告,在您正在查看的差异中很容易错过:

warning: inexact rename detection was skipped due to too many files.
warning: you may want to set your diff.renameLimit variable to at least 450 and retry the command.

在这种情况下,请按照 git 的建议设置配置选项,例如

git config diff.renamelimit 450

并重新运行您的 diff 命令。

于 2018-10-09T07:15:48.553 回答
-5

只需运行git diff不带任何参数,或git diff -- newfilename. git 足够聪明,可以比较正确的文件/内容(即重命名前的原始内容与重命名后的更改内容)

于 2011-04-20T12:50:34.640 回答