Skip to content

Instantly share code, notes, and snippets.

@lolandese
Forked from skwashd/README.md
Last active October 16, 2019 09:00
Show Gist options
  • Select an option

  • Save lolandese/84173dbcfbcde534e7cd84a2f4a0b7b2 to your computer and use it in GitHub Desktop.

Select an option

Save lolandese/84173dbcfbcde534e7cd84a2f4a0b7b2 to your computer and use it in GitHub Desktop.
Drupal git pre-commit hook

Referrer: https://www.drupal.org/docs/develop/local-server-setup/linux-development-environments/set-up-a-local-development-drupal#githooks

This pre-commit hook is designed to be used for Drupal 7 and 8 sites.

Download the pre-commit file. Save it as .git/hook/pre-commit in your git repo. You need to ensure that the file is executable.

If you want this to be added to all new projects automatically, add it to your git init templates.

To install and PHP CodeSniffer for Drupal, please read the official documentation.

To see this working checking out this short YouTube video.

@TODO: Extend with a Drupal best practices check and PHP Mess Detector.

@TODO: Skip check if only files have been deleted.

#!/bin/sh
#
# Git pre-commit hook that prevents code that is not Drupal coding standard compliant of being committed.
#
# Fork of https://git.io/fNXBi by Dave Hall http://davehall.com.au
#
# Fetch the list of files that have changed.
FILES="$(git diff --staged --name-only HEAD --diff-filter=ACMRUXB)"
echo "Running PHP lint check" >&2
LINT_FAIL=0
for filename in $FILES; do
if ! php -l $filename; then
LINT_FAIL=1
fi
done;
# There is no point in running PHP Code Sniffer on broken files.
if [ $LINT_FAIL -gt 0 ]; then
echo "Commit aborted. Fix your code. Then 'git add' and 'git commit' again."
exit 1
fi
echo "Running PHP Code Sniffer Checks" >&2
echo $FILES | xargs phpcs --standard=Drupal --extensions=php,module,inc,install,test,profile,theme,css,info,txt --ignore=node_modules,bower_components,vendor,*.md
if [ $? -eq 0 ]; then
# Exit executing the git commit.
exit 0
else
# Ask what to do, not executing the commit. Source: https://unix.stackexchange.com/a/121255/139407
read -p "Fix the marked Sniff violations automatically [Y/n]?" line </dev/tty
case "$line" in
y|Y) echo $FILES | xargs phpcbf --standard=Drupal --extensions=php,module,inc,install,test,profile,theme,css,info,txt --ignore=node_modules,bower_components,vendor,*.md
;;
*) echo "No automatic corrections made."
;;
esac
echo "Commit aborted. Make remaining manual code fixes if necessary. Then 'git add' and 'git commit' again."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment