英文:
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
,但它被接受了:
这是如何可能的?这是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
:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论