Git newline problem

Posted Jun 16, 20202 min read

problem

Change the system platform development, from Windows to Linux development, use the IDE to open the previous project under Windows and find out how all the code must be submitted again, and problems are found.

the reason

First of all, the line breaks used in the text files of different systems are different. UNIX/Linux uses 0x0A(LF), and the old Mac OS uses 0x0D(CR). Later OS X kept the same with UNIX after changing the kernel . However, DOS/Windows uses 0x0D0A(CRLF).

solve

Git provides an "automatic conversion of line breaks" feature, and it is enabled by default in Windows, that is, when you check out a file, it tries to replace UNIX line breaks(LF) with Windows line breaks(CRLF); when you When submitting the file, it tried to replace CRLF with LF again. Under Linux, it is off, so development under Linux does not need to be turned on. However, the code under Windows is available locally, so it needs to be converted to LF when it is submitted. Git provides an autocrlf configuration item:

  • true:Convert to LF on submission, CRLF on detection

  • false:no checkups are submitted for conversion

  • input:converted to LF when submitted, not converted when detected

    Convert to LF on submission, CRLF on detection

    git config --global core.autocrlf true

    Convert to LF when submitting, not convert when detecting

    git config --global core.autocrlf input

    Submit and checkout are not converted

    git config --global core.autocrlf false

However, if autocrlf is set to false, then another configuration item safecrlf is best set to ture. This option is used to check whether the file contains mixed line breaks. It has three options:

  • true:Refuse to submit files containing mixed line breaks

  • false:Allows files containing mixed newlines to be submitted

  • warn:Warn when submitting files containing mixed newlines

    Refuse to submit files containing mixed line breaks

    git config --global core.safecrlf true

    Allow submission of files containing mixed line breaks

    git config --global core.safecrlf false

    Warn when submitting files containing mixed newlines

    git config --global core.safecrlf warn

If both are set to false, the file in the project may contain line breaks in two formats. The file is considered to be modified as a whole and cannot be diffed. It involves working on multiple system platforms. You can configure git as follows :

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