Add the following to your .gitconfig
:
anw = !git diff -U0 -w --no-color -- \"$@\" | git apply --cached --ignore-whitespace --unidiff-zero "#"
Thanks to @Colin Herbert's answer for the inspiration.
Syntax Explanation
The final #
must be quoted so it's not treated it as a comment inside the .gitconfig
, but instead gets passed through and is treated as a comment inside the shell - it is inserted between the end of the git apply
and the user-supplied arguments that git
automatically places at the end of the command line. These arguments aren't wanted here - we don't want git apply
to consume them, hence the preceding comment character. You may want to run this command as GIT_TRACE=1 git anw
to see this in action.
The --
signals end of arguments and allows for the case that you have a file named -w
or something that would look like a switch to git diff
.
Escaped double-quotes around $@
are required to preserve any user-supplied quoted arguments. If the "
character is not escaped, it will be consumed by the .gitconfig
parser and not reach the shell.
Note: .gitconfig
alias parsing doesn't recognise single-quotes as anything special - its only special characters are "
, \
, \n
, and ;
(outside of a "
-quoted string). This is why a "
must always be escaped, even if it looks like it's inside a single-quoted string (which git is completely agnostic about).
This is important, eg. if you have a handy alias to execute a bash
command in the working tree's root. The incorrect formulation is:
sh = !bash -c '"$@"' -
While the correct one is:
sh = !bash -c '\"$@\"' -