Writing a git hook to automatically change code during local commits

I would like to write a git hook that automatically does some code cleaning, such as removing trailing spaces. It is easy to write a script to reject some commits, but I would rather just fix the problems transparently when possible. Although I understand that git has built-in support for such things (automatic translation of translation strings, etc.), But I would like something more flexible. Is it possible to do this with a pre-commit hook? Can you change the index directly (or is there a better way to do this)?

I also understand that in the end I will need a server hook that rejects bad commits for developers who do not use a local hook, but I would like to help those who prefer to use it. (If you can change the code on the server, that would be even better, but I don't think you can.)

+3
source share
1 answer

Here is an example of using a filter driver to remove trailing spaces. Please note that after committing, spaces remain in the working copy until you check. Also note that the spaces in parentheses in the sed command below are the tab and the space.

$ 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$

0

Source: https://habr.com/ru/post/1733995/


All Articles