silvamerica
silvamerica

Reputation: 994

How can I remove trailing whitespace only on changed lines in a pre-commit git hook?

I've seen a number of solutions suggested, but nearly all of them strip whitespace from the entire file if it's been changed, which is not an option. I have also tried:

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

but it doesn't seem to work either. I am using git version 1.6.3.1 and cannot update it.

Upvotes: 12

Views: 890

Answers (3)

ashays
ashays

Reputation: 1154

This question is a bit old, but I've got git ws aliased to git rebase --whitespace=fix

You can set up a similar alias by running

git config --global alias.ws 'rebase --whitespace=fix'

That will take any any commits that you haven't pushed yet and reapply them after having fixed the whitespace on only the lines that you've changed.

Upvotes: 0

silvamerica
silvamerica

Reputation: 994

Found the answer:

git diff --cached --no-color > stage.diff && git apply --index -R stage.diff && git apply --index --whitespace=fix stage.diff && rm -f stage.diff

Upvotes: 9

Uwe Kleine-König
Uwe Kleine-König

Reputation: 3575

I don't have such a script handy, but I guess a good starting point is the sample pre-commit hook that ships with git (before it was converted to diff --check). At least it only warns about added lines.

gitweb view of pre-commit script

Upvotes: 1

Related Questions