pre-commit hook executes proper but doesn't commit the changes after

Viewed 25

I am using php-cs-fixer and decided to try to put the command in pre-commit hook. #!/bin/sh

echo "php-cs-fixer pre commit hook start"

SRC="src/Controller/Api/FlowsController.php"

exec tools/php-cs-fixer/vendor/bin/php-cs-fixer fix $SRC

echo "php-cs-fixer pre commit hook finish"

So the php-cs-fixer command works fine, but the changes are not commited after it. I also don't see the final echo statement when the hook is done. What I see on committing is:

toma.tomov@MBP-TOMA myproject % git commit -m "test"
php-cs-fixer pre commit hook start
Loaded config default from "/Users/toma.tomov/Desktop/projects/myproject/.php-cs-fixer.dist.php".
Using cache file ".php-cs-fixer.cache".
Paths from configuration file have been overridden by paths provided as command arguments.
   1) src/Controller/Api/FlowsController.php

Fixed all files in 2.028 seconds, 26.000 MB memory used
[PHP-CS-FIXER 9550f90a22] test
 1 file changed, 2 insertions(+)
1 Answers

Pre-commit hooks in general should not try to change what will be committed. Depending on how you invoke Git, they maybe unable to change what will be committed. A pre-commit hook should therefore only verify that what you plan to commit is correct (according to whatever correctness rules you'd like to enforce).

There are some exceptions to the above rules, but you must know a great deal about Git's internal operation before you break these rules. If you'd like to, e.g., reformat or otherwise fix up files before committing, you should do this as a separate step.

Hint: don't run git commit at all. Run your own program, which runs the file-fixing step, then runs git add, then runs git commit. You can retain the checking hooks (which verify that what's to be committed looks right, then allows or denies the commit) and since the file-fixing step has run before the git add step, everything should always pass.

Related