Since I’ve switched back to Windows 10 as my primary OS for web development, I’ve need to think about how to effectively work with developers on *nix-based system.
One thing that hit me recently is the differences in line feeds in source files. Windows will add a carriage return + line-feed (CRLF) to the end every line of code which becomes troublesome for OSes such as macOS & Linux which simply expect a line-feed (LF). The result is really borked looking files when opened in your favorite editor. Thankfully Git has solutions for this and they’re fairly straightforward.
At the Developer Level
If you just want to update your development environment, then it’s a simple process of adding the following to your git global config:
git config --global core.autocrlf true
This command has the effect of preserving the CRLF until your changes are actually committed. As they’re committed, Git will convert them to LFs and you’ll see warnings telling you so. From the Git docs:
“Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code.”
This is really easy but it only tackles an individual developer and not the whole team.
At the Repo Level
IMO, doing it at the repo level is the best choice because you shouldn’t have to worry about this issue as you add more members to your team. This is done by creating a file called .gitattributes which manages all of the rules for how files will be evaluated in your repo including LF management. I found a great article with a solid example of a file with rules. For example, a rule to ensure JavaScript files are converted to LF can be seen here:
*.js text eol=lf
To get this file setup, do the following:
- Create a file called .gitattributes in your project directory
- Add the appropriate rules you’ll need for your project
- Commit the new file to your Git repo
- Done!
Once you’ve committed it it should begin working from there converting files based on the rules you’ve defined.
What if We Already Have Mixed Files?
Thankfully, if you’re already in a situation where files are mixed, Github has outlined a way to solve that once you’ve either updated your local git config file or added the .gitattributes file to your repo. You can read that here.
I hope this tip saves you some pain for you and your team.
Update: I used Visual Studio Code as my editor and you can set it to default to line-feeds for your files by adding the following to your user settings under “Preferences”:
"files.eol": "\n"
That will force new files to be set to LF instead of CRLF. It won’t change existing files and if they were created using CRLFs, you’ll have to look down at the lower right and set that manually.