当在Git中提交文本文件时,为什么会违反`.gitattribute`文件?

huangapple go评论58阅读模式
英文:

When committing a text file in git, why could it be violating `.gitattribute` file?

问题

在我的一个Git存储库中,我添加了以下的.gitattribute文件来规范LF/CRLF字符:

*.bat text eol=crlf
*.cmd text eol=crlf
*.java text eol=lf
*.scala text eol=lf
*.xml text eol=lf
*.py text eol=lf
*.R text eol=lf

# 模仿Apache Spark

为了测试其效果,我手动将一个bat文件的行分隔符从CRLF更改为LF,不幸的是,当在Git中提交并推送此更改时,尽管明显违反了新的.gitattribute,但它被接受了:

https://github.com/tek/splain/commit/9344551a1b61f0bf725cc2d9b8aecdced1e71c8b#diff-33fbd7a182c496726227993443a3cfea58670618db831c51c273dcd8962c861a

这是如何可能的?这是Git的一个错误吗?

英文:

In one of my git repository, I have added the following .gitattribute file to regulate LF/CRLF characters:

*.bat text eol=crlf
*.cmd text eol=crlf
*.java text eol=lf
*.scala text eol=lf
*.xml text eol=lf
*.py text eol=lf
*.R text eol=lf

# mimicking apache spark

To test its effect, I manually change the line separator of one bat file from CRLF to LF, unfortunately, when committing & pushing this change in git, it is accepted despite obviously violating the new .gitattribute:

https://github.com/tek/splain/commit/9344551a1b61f0bf725cc2d9b8aecdced1e71c8b#diff-33fbd7a182c496726227993443a3cfea58670618db831c51c273dcd8962c861a

How could it be possible? Is it a bug in git?

答案1

得分: 2

这是 Git 的意图。它本身在将文件保存到其索引时永远不会将换行符转换为 CRLF。一旦告诉 Git 与 text 关联的文件扩展名,它将利用一切机会在你暂存具有该扩展名的内容以提交时将换行符转换为 LF

这可以解释为 Git 最初是为 Unix 开发的,Unix 使用 LF。对于 Git 在处理文本时内部保持一致的方式来说,这也是一种一致性的问题,特别是涉及到换行符时。

通常情况下,这并不是一个问题,因为在存储库中使用代码时,应该始终从正确的 git clone 开始,它会根据 .gitattributes 执行转换,以便在工作目录中正确指定换行符。

但在一些特殊情况下,如果你确实需要让 Git 将换行符保存为 CRLF,你可以参考 这个答案

英文:

This is intentional from Git. By itself, it will never convert line endings to CRLF when saving a file to its index. As soon as Git is told that a file extension is associated with text, it will take every oportunity to convert the line endings to LF when you stage something to be committed with that extension.

This can be explained by the fact that git was initilally developed for Unix which uses LF. It's also a matter of consistency for git to deal with text in a uniform way internally when it comes to line endings.

This is usually not a problem since any use of the code in a repository should start with a proper git clone which performs the conversion according to the .gitattributes, so that line endings are correctly specified in the working directory.

But in some special case where you really need to make git save line endings as CRLF, you can have a look at this answer.

huangapple
  • 本文由 发表于 2023年6月6日 05:33:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定