Add only non-whitespace changes

This works for me:

If you want to keep a stash around, this works

git stash && git stash apply && git diff -w > foo.patch && git checkout . && git apply foo.patch && rm foo.patch

I don't like the stashes, but I have run into a bug in git + cygwin where I lose changes, so to make sure that stuff went to the reflog at least I set up the following:

git add . && git commit -am 'tmp' && git reset HEAD^ && git diff -w > foo.patch && git checkout . && git apply foo.patch && rm foo.patch

Basically we create a diff that doesn't include the space changes, revert all of our changes, and then apply the diff.


Create a patch file containing only the real changes (excluding lines with only whitespace changes), then clean your workspace and apply that patch file:

git diff > backup
git diff -w > changes
git reset --hard
patch < changes

Review the remaining differences, then add and commit as normal.

The equivalent for Mercurial is to do this:

hg diff > backup
hg diff -w > changes
hg revert --all
hg import --no-commit changes


@Frew solution wasn't quite what I needed, so this is the alias I made for the exact same problem:

alias.addnw=!sh -c 'git diff -U0 -w --no-color "$@" | git apply --cached --ignore-whitespace --unidiff-zero -'

Or you can simply run:

git diff -U0 -w --no-color | git apply --cached --ignore-whitespace --unidiff-zero -

Update

Added options -U0, and --unidiff-zero respectively to workaround context matching issues, according to this comment.

Basically it applies the patch which would be applied with add without whitespace changes. You will notice that after a git addnw your/file there will still be unstaged changes, it's the whitespaces left.

The --no-color isn't required but as I have colors set to always, I have to use it. Anyway, better safe than sorry.

Warning

While this trick works as-is, if you try to use it to drop blank line changes with --ignore-blank-lines then things get complicated. With this option, git diff will just drop some chunks, making the resulting patch bogus since the line numbers in the destination file are going to be off.

Tags:

Git

Whitespace