tags:

views:

209

answers:

1

I'd like to write a git hook that automatically does some code cleaning, such as removing trailing whitespace. It's easy to write a script to reject certain commits, but I'd rather just fix the problems transparently when possible. While I realize git has some built-in support for stuff like this (automatically converting newlines, etc.), but I'd like something more flexible. Is it possible for a pre-commit hook to do this? Can you modify the index directly (or is there a better way of doing this)?

I also realize that ultimately I'll need a server hook that rejects bad commits for developers who don't use the local hook, but I'd like to help those that opt to use it. (If it is possible to modify the code on the server that would be even better, but I don't believe you can.)

A: 

Here's an example of using a filter driver to remove trailing whitespace. Notice that after you make a commit, the whitespace will remain in the working copy until you do a checkout. Also note that the whitespace in the brackets in the sed command below is a tab and a blank.

$ rm -rf .git
$ git init
Initialized empty Git repository in /private/tmp/foo/.git/
$ echo 'trailing white    ' > file
$ echo 'file filter=white' > .git/info/attributes
$ cat << EOF >> .git/config 
> [filter "white"]
>         clean = sed 's/[      ]*$//'
> EOF
$ git add file
$ git ci -m"Sample commit"
[master (root-commit) 654fa8d] Sample commit
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 file
$ git checkout -f master file
$ cat -tve file
trailing white$

William Pursell