Skip to content

Instantly share code, notes, and snippets.

@glensc
Last active May 13, 2017 08:58
Show Gist options
  • Save glensc/cf03265205b67f3735b6fb19ccd4ab2a to your computer and use it in GitHub Desktop.
Save glensc/cf03265205b67f3735b6fb19ccd4ab2a to your computer and use it in GitHub Desktop.
php-cs-fixer git pre commit hook
#!/bin/sh
# A git pre-commit hook to run php-cs-fixer on all changed php files.
#
# Inspired from https://gist.github.com/jwage/b1614c96ea22ccaf68b7
#
# Author: Elan Ruusamäe <glen@pld-linux.org>
# Date: 2017-05-03
# URL: https://gist.github.com/glensc/cf03265205b67f3735b6fb19ccd4ab2a
set -e
PROJECT_DIR=$(git rev-parse --show-toplevel)
PHP_CS_FIXER="$PROJECT_DIR/php-cs-fixer.phar"
CONFIG_KEY=hooks.php-cs-fixer
AUTOFIX=$(git config $CONFIG_KEY || echo true)
CS_OPTIONS=
msg() {
if [ -n "$1" ]; then
echo >&2 "php-cs-fixer: $*"
else
sed >&2 -e 's/^/php-cs-fixer: /'
fi
}
if [ ! -x "$PHP_CS_FIXER" ]; then
msg <<-EOF
Please download php-cs-fixer to project root.
See https://github.com/FriendsOfPHP/PHP-CS-Fixer#installation
EOF
exit 1
fi
# list files modified in a commit
# for diff filter: http://stackoverflow.com/a/3068990
git_precommit_changed_files() {
git diff --cached --name-only --diff-filter=ACM
}
# list modified files in current workspace
git_changed_files() {
git ls-files -m
}
# accept php files only
php_name_filter() {
local file
while read file; do
case "$file" in
*.php)
echo "$file"
;;
esac
done
}
# if ran directly, assume user wants just to fix modified files
if [ -z "$GIT_DIR" ]; then
# take arguments if specified
if [ -n "$1" ]; then
changed_files="$@"
else
changed_files=$(git_changed_files | php_name_filter)
fi
AUTOFIX=true
else
changed_files=$(git_precommit_changed_files | php_name_filter)
fi
changed_files=$(echo "$changed_files" | php_name_filter)
if [ -z "$changed_files" ]; then
exit 0
fi
if [ "$AUTOFIX" = "true" ]; then
msg "Autofix enabled, to disable: run: git config $CONFIG_KEY false"
else
CS_OPTIONS="--diff --dry-run"
msg "Autofix disabled, to enable, run: git config $CONFIG_KEY true"
fi
"$PHP_CS_FIXER" fix --config=$PROJECT_DIR/.php_cs --verbose $CS_OPTIONS $changed_files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment