Make Git automatically remove trailing white space before committing
git, githooks, whitespace
Solution
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!
Another approach, suggested by hakre in the comments:
You can have two spaces at end of line in markdown and not have it as trailing whitespace by adding "`\`" before `\n`.
Then a content filter driver:
git config --global filter.space-removal-at-eol.clean 'sed -e "s/ \+$//"'
# register in .gitattributes
*.md filter=space-removal-at-eol
Problem
I'm using Git with my team and would like to remove white space 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 white space (and other white space errors) from all commits as they are applied. I have tried to add the following to the `~/.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 is not really causing a big problem.
Related problems
- What's the difference between `git add .` and `git add -u`?
- How to know if there is a git rebase in progress?
- Is git's semi-secret empty tree object reliable, and why is there not a symbolic name for it?
- How can I replace each newline (\n) with a space using sed?
- Applying a git post-commit hook to all current and future repositories
- git remove trailing whitespace in new files before commit
- How to turn removing whitespaces off for some files in Sublime Text 2?