Skip to content

Instantly share code, notes, and snippets.

@klatys
Created November 21, 2016 13:05
Show Gist options
  • Save klatys/85767c45f03bdb6e780a4800c6f2a78a to your computer and use it in GitHub Desktop.
Save klatys/85767c45f03bdb6e780a4800c6f2a78a to your computer and use it in GitHub Desktop.
pre-comit-check (by @mzstic)
#!/bin/bash
# Installation
# ------------
# Use following command
# cp pre-commit.sh .git/hooks/pre-commit
# It is done automatically after composer install / update
PHPCS_BIN=vendor/bin/phpcs
TMP_STAGING=".tmp_staging"
# comma-separated list of file patterns being ignored
PHPCS_IGNORE="gen-src/*"
# egrep compatible pattern of files to be checked
PHPCS_FILE_PATTERN="\.(php|phtml)$"
# Check if CS bin exists
if [ ! -x $PHPCS_BIN ]; then
echo "PHP CodeSniffer bin not found or executable -> $PHPCS_BIN"
exit 1
fi
# retrieve all files in staging area that are added, modified or renamed
# but no deletions etc
FILES=$(git diff-index --name-only --cached --diff-filter=ACMR HEAD -- )
if [ "$FILES" == "" ]; then
exit 0
fi
# match files against whitelist
FILES_TO_CHECK=""
for FILE in $FILES
do
echo "$FILE" | egrep -q "$PHPCS_FILE_PATTERN"
RETVAL=$?
if [ "$RETVAL" -eq "0" ]
then
FILES_TO_CHECK="$FILES_TO_CHECK $FILE"
fi
done
if [ "$FILES_TO_CHECK" == "" ]; then
exit 0
fi
if [ "$PHPCS_IGNORE" != "" ]; then
IGNORE="--ignore=$PHPCS_IGNORE"
else
IGNORE=""
fi
# Copy contents of staged version of files to temporary staging area
# because we only want the staged version that will be commited and not
# the version in the working directory
STAGED_FILES=""
for FILE in $FILES_TO_CHECK
do
ID=$(git diff-index --cached HEAD $FILE | cut -d " " -f4)
# create staged version of file in temporary staging area with the same
# path as the original file so that the phpcs ignore filters can be applied
mkdir -p "$TMP_STAGING/$(dirname $FILE)"
git cat-file blob $ID > "$TMP_STAGING/$FILE"
STAGED_FILES="$STAGED_FILES $TMP_STAGING/$FILE"
done
# execute the code sniffer
OUTPUT=$($PHPCS_BIN -s -n --standard=phpcs-pre-commit.xml --encoding=utf8 $IGNORE $STAGED_FILES)
RETVAL=$?
# delete temporary copy of staging area
rm -rf $TMP_STAGING
if [ $RETVAL -ne 0 ]; then
echo "$OUTPUT" | less
fi
exit $RETVAL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment