Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git add -patch... but ignore whitespace changes

I can't seem to find a good way to use git add -p but tell git to ignore all whitespace changes. I don't want to reset my local changes.

The situation: I had all my changes locally, and was grouping them into separate commits. Then I experimented with a minifyer, and overwrote all my css files with their minified version. I tried "un-minifying" everything, but it still messed up the git diff - because there were so many whitespace changes - and I can't seem to get my repo back to a place where I can see the actual changes.

Thank you for your help!

like image 267
Jillian Hoenig Avatar asked Jun 07 '17 22:06

Jillian Hoenig


1 Answers

Resetting and readding (recommended)

This is the simplest method. There's no one-line-straight-forward way if you don't want to reset and readd in your working directory. You should do exactly that, here's a good way explained step-by-step:

git diff -w --no-color | git apply --cached --ignore-whitespace && git checkout -- . && git reset && git add -p

git diff -w --no-color creates a diff without terminal formatting and colors

git apply --cached --ignore-whitespace applies the diff ignoring whitepace, and indexes it

git checkout -- . removes the unindexed “whitespace” changes

git reset resets the index to just the non-whitespace changes

git add -p adds the non-whitespace changes in patch mode

(source here)


Without resetting

This partially answers your problem, without stashing or resetting. You can "diff and apply" only non-whitespace changes, in a way like this:

git diff -w --no-color | git apply --cached --ignore-whitespace

This is another way, but please notice that patching here is a bit of a mess, you need to buffer and manually change diff removing whitespaces. If you use VIM, here's quick step-by-step commands you can use to bufferize, quickly find, remove and finally apply clean diffs:

:r !git diff -w --no-color this creates a new buffer with your diff

:set ft=diff (optional) use this if you want syntax highlighting

now you need to manually remove what you don't want to stage, then

:w !git apply --cached --ignore-whitespace to apply current fixed diff

and eventually commit this diff with :!git commit -m "your fixed commit"

Here's the first iteration. You need to clear the buffer, read the unstaged changes and repeat:

:bd! | set ft=diff | r !git diff -w --no-color

keep going and, eventually, you'll be left with only whitespace changes to commit.

If you don't want to use VIM:

  • dump git diff into a file
  • edit the file with your favourite IDE/text editor
  • feed the edited file into git apply.
  • commit
  • repeat until done.

It may not be the fastest way, but it's functional and does the trick if you don't like the first method.

(source and similar question here)

like image 114
Defrag Avatar answered Sep 28 '22 22:09

Defrag