Formatting and whitespace issues are frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors “smartly” introduce them. And if your files ever touch a Windows system, their line endings might be replaced.
Git has a few configuration options to help with these issues:
git config --global core.autocrlf input # Configure Git on OS X or Linux to properly handle line endings git config --global core.autocrlf true # Configure Git on Windows to properly handle line endings
But what if the above is not enough? The answer is a one-liner:
git diff -U0 --ignore-space-at-eol --no-color | git apply --cached --ignore-whitespace --unidiff-zero -
A closer look at the above command:
git diffGenerate patch.
--unified=0Generate diffs with 0 lines of context.
This option averts context matching issues.
--ignore-space-at-eolIgnore changes in whitespace at EOL.
That is what we want. And there are other
--no-colorTurn off colored diff.
Since it is for pipeline, don’t bother for visual.
git applyApply a patch.
--cachedOnly apply to the index without touching the working tree.
Leave changes in whitespace at EOL unstaged.
--ignore-whitespaceIgnore changes in whitespace in context lines if necessary.
This option averts whitespace fixing.
--unidiff-zeroBypass unified diff checks.
We are sure about no breaks.
-Read the patch from the standard input.
And at the end. You may also make a git alias, so you can use
git addneol to save all the memorizing and typing in the future.
# e.g. What it looks like in the .gitconfig file. ... [alias] ... addneol = !sh -c 'git diff -U0 --ignore-space-at-eol --no-color "$@" | git apply --cached --ignore-whitespace --unidiff-zero -' ... ...