git diff 不能处理 Word 文档,使用 --intent-to-add 和 pandoc diff 驱动程序。

4

在互联网上可以找到几篇教程([1][2][3]),建议使用以下配置来对 git 追踪的 Word 文档进行差异比较。

  1. Configure a "pandoc" diff driver with the following settings:

    [diff "pandoc"]
        textconv=pandoc --to=markdown
        prompt = false
    
  2. Add the following to your .gitattributes file:

    *.docx diff=pandoc
    

除了在指示将其添加到git存储库后尝试对未跟踪的Word文档进行差异化之外,这似乎运行良好。 有人知道为什么在这种情况下无法正常工作吗?

以下是重现步骤,假设已详细说明上述配置。

  1. Create a Word document in a git repository

    touch my_document.docx
    
  2. Open the file in Microsoft Word, add some content to the Word document (e.g, the characters "asdf"), and save it

  3. Indicate your intent to add the document

    git add -N my_document.docx
    
  4. Try to see the diff:

    git diff my_document.docx
    #> couldn't parse docx file
    #> fatal: unable to read files to diff
    

在macOS上,使用git版本2.17.1时,我遇到了“fatal: unable to read files to diff”的错误。不过,只需将文件添加到索引中,然后运行git diff --cached,即可得到以下差异:

diff --git a/my_document.docx b/my_document.docx
new file mode 100644
index 0000000..17f1b0d
--- /dev/null
+++ b/my_document.docx
@@ -0,0 +1 @@
+asdf

为什么diff驱动程序不能与git add -N一起使用?

它说“#> 无法解析docx文件”,因为那可能不是正确的docx标记,你期望什么?后面的命令通过常规的diff运行文件,因此进行文本比较。 - orhtej2
@orhtej2 啊,谢谢。我明白了。这个问题最终是由于 pandoc --to=markdown /dev/nulltouch my_document.docx && pandoc --to=markdown my_document.docx 之间的差异造成的。您是否想将您的评论扩展为答案? - Adam Liter
1
似乎这是 pandoc 中的一个边缘情况错误,完全空白的文档会让它无法避免地出现问题,这是不良行为。 - jthill
@jthill 是的,也许吧。我已经打开了一个问题(https://github.com/jgm/pandoc/issues/4717)。我们会看看他们怎么说。 - Adam Liter
1个回答

3

这是因为 pandoc --to=markdown /dev/null/ 在不出错的情况下正确地返回空值,而 pandoc --to=markdown a/my_document.docx 则会在 a/my_document.docx 是一个空文件的情况下出错。

所以,在你第一次将 my_document.docx 添加到索引中并运行 git diff --cached 来比较索引和 HEAD 的情况下,比较将针对 /dev/null 进行,一切都将正常工作。

然而,如果你使用 git add -N 表示打算添加一个新文件 my_document.docx,那么一个同名的空文件将被添加到索引中。在这种情况下,pandoc 在尝试将索引中的空文件转换为 Markdown 时会出错。


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