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
*.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
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”:
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.