git 解决换行符 ^M 导致整个文件被改


#Git#


问题

在 linux 下提交一个项目到 github 中,然后在 windows 中 clone 下来,发现所有的文件都发生了变化。diff 一看,发现很多 ^M 。

为什么?

原因是 linux/mac 使用 0x0A(LF) 作为换行符,Windows 使用 0x0D0A(CRLF)。而git diff 展示的 ^M 其实就是 CR 回车符。

解决方案 1:修改 git 配置

1、Windows 下禁止 git 将 LF 自动转换为 CRLF :

执行下面的命令:

git config --global core.autocrlf false
git config --global core.safecrlf true

参数介绍见 https://git-scm.com/docs/git-config

2、IDEA、编辑器统一换行符为 LF 。

解决方案2:修改 git 项目 .gitattributes

.gitattributes 文件放在 git 项目中,配置如下。

* text=auto
*.java text eol=lf
*.png binary
*.jpg binary

提交项目和拉取项目时会将 java 文件换行符都转换为 LF

注意,这种配置可能会对只支持 CRLF 换行符的应用有影响。

如何统一整个 git 项目的换行符?

参考 Configuring Git to handle line endings

1、保存现有的更改

$ git add . -u
$ git commit -m "Saving files before refreshing line endings"

2、修改所有文件的换行符,并 add

$ git add --renormalize .

3、查看效果

$ git status

4、提交

$ git commit -m "Normalize all the line endings"

相关资料


( 本文完 )