如何恢复由于不正确的 .gitattributes 而损坏的 PNG 文件?

Ben*_*n.W 1 git png gitattributes

我添加 & 提交 & 推送了几个 PNG 文件到我的 git repo 中,但不幸的是,我有一个不正确的 .gitattributes 文件,如下所示:

* text
# no settings for PNG files
Run Code Online (Sandbox Code Playgroud)

PNG 文件被 git 视为文本文件。现在我无法再打开它们,而且我也丢失了它们的原始副本。有什么办法可以恢复它们吗?谢谢!


更新.gitattributes添加 PNG 文件时已经在 repo 中。这意味着我无法在提交历史记录中找到PNG 文件的良好状态。所有提交都是在 Windows 上进行的。

Den*_*niz 5

让我们假设您有 2 个提交:

  • 在第一个中,所有 PNG 文件都作为二进制文件处理,文件是健全的。
  • 第二次提交包括.gitattributes文件,所有 PNG 文件都被损坏,因为它们被视为文本文件。

这是git log输出:

commit d075d282795362e03318d93c36406822facc015c (HEAD -> master)
Author: John Doe <john.doe@users.noreply.github.com>
Date:   Tue Mar 26 17:12:16 2019 +0100

    Bad state
    Gitattributed file added, PNG files are treated as text, they are now corrupted

commit fcaa5a87eb816ddafbd256e83ea4be004a87a6e8
Author: John Doe <john.doe@users.noreply.github.com>
Date:   Tue Mar 26 17:11:36 2019 +0100

    Good state
    PNG Files are treated as binary, they are not corrupted yet
Run Code Online (Sandbox Code Playgroud)

首先将所有 PNG 文件重置为初始状态:

git reset fcaa5a87eb816ddafbd256e83ea4be004a87a6e8 -- *.png

然后提交更改而不添加任何文件:

git commit -m 'Fix PNG files'

丢弃工作目录中的所有更改:

git checkout '*.png'

最后删除错误.gitattributes输入或替换为:

*.png binary

您还可以使用包含许多其他文件类型的gitattributes 模板


更新:

如果没有图像完好无损的“良好”状态,您可以尝试通过操作文件来解决问题。您需要添加缺少的换行符。您不知道正确的位置,因为 git 已将它们全部删除。根据我的经验,如果在第一行的末尾只添加一个回车符,它会修复大多数小 PNG 文件。我不知道为什么,也不能保证,但你仍然可以尝试:

首先删除所有 PNG 文件:

rm -f *.png

然后将 PNG 文件声明为二进制文件.gitattributes

*.png binary

恢复文件:

git checkout '*.png'

在第一行的末尾添加一个回车:

perl -i -p -e 's/$/$1\r/ if $. == 1;' *.png