Automatically convert line endings on commit in git (and save yourself when you've already made a mistake!)
Wed, 27 September 2017
We've all been there. Used a piece of code and discovered some funky line endings. You should really always use \n for a new line. Unfortunately, this isn't as widespread as we'd all like, and furthermore isn't enforced.
So you go to do a git diff and you see something like this:
Rogers-MacBook-Pro:code roger$ git diff
diff --git a/index.js b/index.js
index b770c39..760947a 100644
--- a/index.js
+++ b/index.js
@@ -1,6 +1,6 @@
'use strict';
-process.env.DEBUG = 'some-package:*';
+process.env.ERROR = 'some-package:*';^M
What's happened is you've added a line ending that shouldn't be there. Thankfully, Git has a simple solution:
git config --global core.autocrlf false
Simply run that in your terminal and from then on it'll convert the line endings automatically. If you've already committed some incorrect line endings you can run this in your terminal:
git rm --cached -r .
Once you've run that, fire in this command:
git diff --cached --name-only -z | xargs -0 git add
You should get a load of warning lines out into the console. You can go ahead and commit this now:
git commit -m "Convert line endings"