Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add only non-whitespace changes

Tags:

git

whitespace

I have my text editor to automatically trim trailing whitespace upon saving a file, and I am contributing to an open source project that has severe problems with trailing whitespace.

Every time I try to submit a patch I must first ignore all whitespace-only changes by hand, to choose only the relevant information. Not only that, but when I run git rebase I usually run into several problems because of them.

As such I would like to be able to add to index only non-whitespace changes, in a way similar that git add -p does, but without having to pick all the changes myself.

Does anyone know how to do this?

EDIT: I cannot change the way the project works, and they have decided, after discussing it on the mailing list, to ignore this.

like image 470
Edu Felipe Avatar asked Aug 18 '10 18:08

Edu Felipe


2 Answers

@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.

like image 156
Colin Hebert Avatar answered Oct 21 '22 17:10

Colin Hebert


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

like image 42
Steve Pitchers Avatar answered Oct 21 '22 16:10

Steve Pitchers