Last active
September 5, 2024 00:20
-
-
Save jwage/b1614c96ea22ccaf68b7 to your computer and use it in GitHub Desktop.
php-cs-fixer git pre commit hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
return Symfony\CS\Config\Config::create() | |
->level(Symfony\CS\FixerInterface::SYMFONY_LEVEL) | |
->fixers([ | |
'short_array_syntax', | |
'ordered_use', | |
]) | |
; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
ROOT="/path/to/your/code" | |
echo "php-cs-fixer pre commit hook start" | |
PHP_CS_FIXER="vendor/bin/php-cs-fixer" | |
HAS_PHP_CS_FIXER=false | |
if [ -x vendor/bin/php-cs-fixer ]; then | |
HAS_PHP_CS_FIXER=true | |
fi | |
if $HAS_PHP_CS_FIXER; then | |
git status --porcelain | grep -e '^[AM]\(.*\).php$' | cut -c 3- | while read line; do | |
$PHP_CS_FIXER fix --config-file=$ROOT/.php_cs --verbose "$line"; | |
git add "$line"; | |
done | |
else | |
echo "" | |
echo "Please install php-cs-fixer, e.g.:" | |
echo "" | |
echo " composer require --dev fabpot/php-cs-fixer:dev-master" | |
echo "" | |
fi | |
echo "php-cs-fixer pre commit hook finish" |
We also found that merge commits could end up linting tons of files. We elected to skip merge commits:
if git rev-parse -q --verify MERGE_HEAD; then
echo "This is a merge commit. Skipping linting just in case it's a big one!"
exit 0
fi
Grep pattern is missing heading whitespace:
# instead of
grep -e '^[AM]\(.*\).php$'
# do
grep -e '^\s*[AM]\(.*\).php$'
Actually, ls-files does a better job:
git ls-files -m | grep -e '.php$' | xargs vendor/bin/php-cs-fixer fix
use lint staged is also a nice solution https://sebastiandedeyne.com/running-php-cs-fixer-on-every-commit-with-husky-and-lint-staged/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script has worked well for us. However, I did run into one odd behavior. This script will lint and commit all the PHP files that have changed, even if those files are not staged for commit. This tweak lints only staged files: