Windows 的 Git:为什么 git diff 没有显示文件的工作目录和暂存索引之间的差异?

Git of Windows: Why is git diff not showing the differences between working directory and the staging index for a file?

情况:

我在 Windows 7 上安装了 Git 1.9.5.github.0。 我目前在每个或三个区域(存储库、暂存索引和工作目录)中都有一个文件版本。该文件的所有三个版本都不同,每个版本的文本行都比旧版本多。

问题:

当我输入命令 git diff、git diff --cached first_file.txt 或 git diff HEAD;响应显示它检测到差异但不显示这些差异。 ----(见下面的代码)

Z:\myFirstGit [master +0 ~1 -0]> git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   first_file.txt

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   first_file.txt

Z:\myFirstGit [master +0 ~1 -0 | +0 ~1 -0]> git diff
diff --git a/first_file.txt b/first_file.txt
index 2b6f7c0..0090cbf 100644
Binary files a/first_file.txt and b/first_file.txt differ
Z:\myFirstGit [master +0 ~1 -0 | +0 ~1 -0]> git diff head
diff --git a/first_file.txt b/first_file.txt
index e1a914a..0090cbf 100644
Binary files a/first_file.txt and b/first_file.txt differ
Z:\myFirstGit [master +0 ~1 -0 | +0 ~1 -0]> git diff --cached first_file.txt
diff --git a/first_file.txt b/first_file.txt
index e1a914a..2b6f7c0 100644
Binary files a/first_file.txt and b/first_file.txt differ

我期待的是:

 > git diff
diff --git a/first_file.txt b/first_file.txt
index e1a914a..0090cbf 100644
--- a/first_file.txt
+++ b/first_file.txt
@@ -1 +1,2 @@
 This is the first_file test.
+One more line.

问题:

为什么我得到的是响应 "Binary files a/first_file.txt b/first_file.txt differ" 而不是明确显示差异?

这通常发生在文件模式更改时。

您可以在此位中看到实际差异:

100644
--- a/first_file.txt
+++ b/first_file.txt

这意味着文件的模式已更改为644。 (参见 file modes

您的文件肯定包含使 Git 将文件视为二进制文件的数据。因此它无法显示差异。

您可以强制 Git 将您的文件视为 diff 操作的文本,方法是编写:

first_file.txt diff

.gitattributes 文件中。 参见 this similar question and the doc of .gitattribute

首先,我要感谢 Frodon 提供 link 帮助我解决了我的问题。

解决方案

问题出在文件的编码上。我最初在记事本中完成了所有或我的文本文件编辑。从 Frodon 提供的 link 中,我发现了一个 post 的人使用 Notepadd++ 找出正在使用的编码并更改它。

  1. 读完后,我在 Notepad++
  2. 中打开了我的 first_file.txt
  3. 我从菜单栏中选择了“编码”选项卡,看到编码被标记为 'Encode in UCS-2 Big Endian'。
  4. 我将编码更改为无 BOM 的 UTF-8 编码。
  5. 我将 'Change encoding' 作为文本添加到 first_file.txt 内的新行中。保存它,然后 git add first_file.txt 最后 git commit first_file.txt -m 'Changed encoding'.
  6. 现在,当我对 first_file.txt 进行编辑时,编辑内容会按应有的方式显示,并在键入命令 git diff
  7. 后显示不同之处