The point in removing trailing whitespace is that if everyone does it always then you end up with a diff that is minimal, ie. it consists only of code changes and not whitespace
I'd been using a script based on @GregBacon's answer for years, but at some point git changed the output of git diff -b
so that the whitespace changes it didn't show as changes were included in the patch context lines in the after state rather than the before state.
I found if I reversed the clean diff and the corresponding apply, the script would work again.
So my complete script used to look like this:
#!/bin/bash
clean=`git diff --cached -b`
git apply --cached <(git diff --cached -R)
echo "$clean" | git apply --cached -
clean=
And now looks like:
#!/bin/bash
clean=`git diff --cached -b -R`
git apply --cached <(git diff --cached -R)
echo "$clean" | git apply --cached -R -
clean=
I also have a script to leave only whitespace changes in a commit. This is useful if while you fix something you make some whitespace fixes elsewhere in the file, and you want to commit the whitespace fixes first in a separate commit. It is just:
git apply --cached -R <(git diff --cached -w)