Skip to content

Instantly share code, notes, and snippets.

@joelhy
Forked from paunin/pre-recieve.sh
Last active August 17, 2017 11:07
Show Gist options
  • Save joelhy/c6b6b3ba5b0e0c3065c4571505129876 to your computer and use it in GitHub Desktop.
Save joelhy/c6b6b3ba5b0e0c3065c4571505129876 to your computer and use it in GitHub Desktop.
pre-receive Code Sniffer
#!/bin/sh
# PHP CodeSniffer pre-receive hook for git
PHPCS_BIN="/usr/local/bin/phpcs"
PHPCS_CODING_STANDARD="PSR2"
# use coding standard dir from local repo
PHPCS_DIR_LOCAL=0
TMP_DIR=$(mktemp -d --tmpdir phpcs-pre-receive-hook.XXXXXXXX)
mkdir "$TMP_DIR/source"
# parse config
CONFIG_FILE=$(dirname $0)/config
if [ -e $CONFIG_FILE ]; then
. $CONFIG_FILE
fi
# simple check if code sniffer is set up correctly
if [ ! -x $PHPCS_BIN ]; then
echo "PHP CodeSniffer bin not found or executable -> $PHPCS_BIN"
exit 1
fi
# prepare our standard rules
if [ $PHPCS_DIR_LOCAL = 1 ]; then
mkdir "$TMP_DIR/standard"
git archive HEAD $PHPCS_CODING_STANDARD | tar -x -C "$TMP_DIR/standard"
PHPCS_CODING_STANDARD="$TMP_DIR/standard/$PHPCS_CODING_STANDARD"
fi
# gathers all errors and sent to output at end
ERRORS=""
RETVAL=0
EMPTY_REV="0000000000000000000000000000000000000000"
# <oldrev> <newrev> <refname>
i=0
while read oldrev newrev ref;
do
if [ "$oldrev" = "$EMPTY_REV" ]; then # create new branch
oldrev="HEAD"
fi
if [ "$newrev" = "$EMPTY_REV" ]; then # delete branch
break
fi
list=$(git diff-tree --name-only -r $oldrev..$newrev | grep -e '.php')
for file in ${list}; do
# dirty hack for create dir tree
mkdir -p $(dirname "$TMP_DIR/source/$file")
git show ${newrev}:${file} 1>"$TMP_DIR/source/$file" 2>/dev/null || continue #skip deleted files
OUTPUT=$($PHPCS_BIN --standard=$PHPCS_CODING_STANDARD -q -n --ignore=vendor,database,_ide_helper.php "$TMP_DIR/source/$file")
if [ "$?" -ne "0" ]; then
ERRORS="${ERRORS}${OUTPUT}"
RETVAL=1
((i++));
if (( i > 3 )); then # only show errors of 3 files at most for performance
break
fi
fi
done
done
# cleanup
rm -rf $TMP_DIR
echo "$ERRORS"
exit $RETVAL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment