This script has the goal of improving the development of custom code for themes, modules oriented to drupal and general code. It validates Drupal coding standards on files before commit them and returns a message to fix each line of code on the files having errors.
Follow next steps to set up pre commit git hook with Drupal coding standards:
- composer require drupal/coder dealerdirect/phpcodesniffer-composer-installer
- Create hooks directory on root project.
- Create pre-commit file into hooks directory.
- Add pre-commit code to hooks/pre-commit file.
- Add phpcs.xml code to phpcs.xml file.
- Add PHP commands on scripts section of composer.json file.
composer require drupal/coder dealerdirect/phpcodesniffer-composer-installer
Add composer changes, commit them and push to repository, so that other developers in the team can install the 'pre-commit' git hook, pulling changes from repository and running composer install.
git pull <remote_name> <branch_name>
composer install
git commit -m "The commit message."
- This is going to execute Drupal Coder on each file and returns messages on terminal in case of finding errors on files.
Command
git commit -m "Testing Drupal Coder."
Terminal output
Drupal Coder pre-commit hook – commit with the --no-verify option to skip the hook
Running Drupal Coder.
E 1 / 1 (100%)
FILE: ...js/scripts.js
----------------------------------------------------------------------
FOUND 5 ERRORS AFFECTING 5 LINES
----------------------------------------------------------------------
16 | ERROR | [x] Expected 1 space after FUNCTION keyword; 0 found
23 | ERROR | [x] Whitespace found at end of line
38 | ERROR | [x] Whitespace found at end of line
45 | ERROR | [x] Whitespace found at end of line
79 | ERROR | [x] Expected 1 newline at end of file; 0 found
----------------------------------------------------------------------
PHPCBF CAN FIX THE 5 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------
Time: 384ms; Memory: 30MB
[develop 5e53248] Testing Drupal Coder.
1 file changed, 1 insertion(+)
Just add --ignore flag to PHPCS command and speficy the files you want to be ignored by PHP CodeSniffer.
"--ignore=*/style.css, */sq-payment-form.cs
The complete command will be as shown below.
PHPCS=("$BIN/phpcs" "--standard=$STANDARD" "--ignore=*/style.css, */sq-payment-form.css" "--filter=gitstaged" "--encoding=utf-8" "-p" ".")
"${PHPCS[@]}"