Git: Dealing with line endings – solution

If you are developing on one platform and not sharing your code, you will not have a problem with the line endings. But on multiplatform developed project you can have a problem with different line endings – Windows, Linux and Mac. As a solution Git has option to make the line endings consistent.

To setup your environment, set you global Git settings first:

$ git config --global core.autocrlf input
# Set this setting on OSX or Linux
$ git config --global core.autocrlf true
# Set this setting on Windows

Every repo can have different requirement for the line endings, so for each repo you can specify the line endings. In the repository folder run:

$ git config --global core.autocrlf input

To be more consistent and be able to specify the line ending for different files by the extension, you can use .gitattributes file. The file is committed to the repository and will override the developers setting. The .gitattributes file should be created in the root of the repository and committed into the repo like any other file.

# Set behaviour for all files, in case developers don't have core.autocrlf set.
* text=auto

# Explicitly declare text files we want to always be normalized and converted to native line endings on checkout.
*.txt text

# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf

# Denote all files that are truly binary and should not be modified.
*.zip binary

After you’ve set the core.autocrlf option and created a .gitattributes file, you may find that git wants to commit files that you’ve not modified. This is because git wants to normalize the line endings for you. Make sure you’ve committed any work before you do this, or it will be lost.

$ git rm --cached -r .
# Remove everything from the index.
$ git reset --hard
# Write both the index and working directory from git's database.
$ git add .
# Prepare to make a commit by staging all the files that will get normalized. This is your chance to inspect which files were never normalized. You should get lots of messages like: "warning: CRLF will be replaced by LF in file."
$ git commit -m "Normalize line endings"

Source: Github

Leave a Reply

Your email address will not be published. Required fields are marked *