Git:git diff发现windows下会出现"^M"符号

原帖收藏于IT老兵驿站,传递一个IT老兵凋零前的光和氧。

Git:git diff发现windows下会出现”^M”符号。

前言

在不同操作系统上编译Git仓库的文件,经常在git diff 时发现很多文件的变化是尾部多了一个^M 的符号。这给工作带来很多困扰,研究一下这个问题。

正题

翻到这个帖子

GitHub suggests that you should make sure to only use \n as a newline character in git-handled repos. There’s an option to auto-convert:

1
$ git config --global core.autocrlf true

大体翻译:GitHub建议你应该只用\n 来做为新行的开始,用上面那样的设置就可以做到自动的转换,这样也就解决了问题,Git不会再报告差异。

那这是为什么呢?

阅读一下这里所介绍的这个帖子。

If you’re using Git to collaborate with others on GitHub, ensure that Git is properly configured to handle line endings.

Every time you press return on your keyboard you’re actually inserting an invisible character called a line ending. Historically, different operating systems have handled line endings differently.

When you view changes in a file, Git handles line endings in its own way. Since you’re collaborating on projects with Git and GitHub, Git might produce unexpected results if, for example, you’re working on a Windows machine, and your collaborator has made a change in OS X.

这里大概是说每个操作系统有自己的换行符(就是当你按下”回车”后,系统会自动插入一些不可见的符号来表示一行的结束),LinuxMac都是使用LFWindows 则是CRLF ,这样就造成了差异。

Git会对此进行一些处理,但是做什么处理呢?这里没有说清楚,只是说要用

1
git config core.autocrlf

来控制,和上面说的是一样的,但是原理还是没有搞明白。

只好来看官网

core.autocrlf
Setting this variable to “true” is the same as setting the text attribute to “auto” on all files and core.eol to “crlf”. Set to true if you want to have CRLF line endings in your working directory and the repository has LF line endings. This variable can be set to input, in which case no output conversion is performed.

这个变量设置为true 等同于在所有文件上设置text attributeauto 并且把core.eol 设置为crlf。设成true , 如果你的工作空间用的是CRLF 作为行结束符,同时仓库用的是LF 行结束符。这个变量也可以设置成input,这样在输出时就不做转换了。

对上面说的core.eol 又不明白了,继续查看:

core.eol
Sets the line ending type to use in the working directory for files that have the text property set when core.autocrlf is false. Alternatives are lf, crlf and native, which uses the platform’s native line ending. The default value is native. See gitattributes[5] for more information on end-of-line conversion.

这个变量是用来设置行结束符的,在core.autocrlffalse的时候。可以设置成lfcrlfnativenative是说使用当前平台自己的行结束符。

到这里,大体就明白了,还留有一个问题,就是attribute的问题,留在下一次来研究。