Make git automatically remove trailing whitespace before committing

mloughran picture mloughran · Feb 26, 2009 · Viewed 134.3k times · Source

I'm using git with my team and would like to remove whitespace changes from my diffs, logs, merges, etc. I'm assuming that the easiest way to do this would be for git to automatically remove trailing whitespace (and other whitespace errors) from all commits as they are applied.

I have tried to add the following to by ~/.gitconfig file but it doesn't do anything when I commit. Maybe it's designed for something different. What's the solution?

[core]
    whitespace = trailing-space,space-before-tab
[apply]
    whitespace = fix

I'm using ruby in case anyone has any ruby specific ideas. Automatic code formatting before committing would be the next step, but that's a hard problem and not really causing a big problem.

Answer

VonC picture VonC · Feb 26, 2009

Those settings (core.whitespace and apply.whitespace) are not there to remove trailing whitespace but to:

  • core.whitespace: detect them, and raise errors
  • apply.whitespace: and strip them, but only during patch, not "always automatically"

I believe the git hook pre-commit would do a better job for that (includes removing trailing whitespace)


Note that at any given time you can choose to not run the pre-commit hook:

  • temporarily: git commit --no-verify .
  • permanently: cd .git/hooks/ ; chmod -x pre-commit

Warning: by default, a pre-commit script (like this one), has not a "remove trailing" feature", but a "warning" feature like:

if (/\s$/) {
    bad_line("trailing whitespace", $_);
}

You could however build a better pre-commit hook, especially when you consider that:

Committing in Git with only some changes added to the staging area still results in an “atomic” revision that may never have existed as a working copy and may not work.


For instance, oldman proposes in another answer a pre-commit hook which detects and remove whitespace.
Since that hook get the file name of each file, I would recommend to be careful for certain type of files: you don't want to remove trailing whitespace in .md (markdown) files!