1

I try to use CodeSniffer in combination with a pre-commit git hook. I can run phpcs --standard=PSR2 PhpFile.php so the installation of CodeSniffer seems to work fine.

I try to use this piece of code as premade git hook. However I'm pretty sure this code is not compatible with Windows and I don't know how much effort it takes to port it. So maybe it is better to write my own code for parsing the staged (PHP) files with CodeSniffer. I just could use some help how to do this.

Tried

Well I knew I had to start with getting the staged files like this:

git diff --cached --name-only

But I cannot use grep to only get the .php files. So I think we need an equivalent in Windows?

online Thomas
  • 8,864
  • 6
  • 44
  • 85

1 Answers1

0

I made this pre-commit hook that suits my needs

#!/bin/bash
echo "Running Code Sniffer. Code standard PSR2."
# php files that are staged in git but not deleted

PHP_FILES=$(git diff --diff-filter=d --cached --name-only | grep -E '\.php$')
JS_FILES=$(git diff --diff-filter=d --cached --name-only | grep -E '\.js$')
for file in $PHP_FILES
do
echo $file

 phpcs --standard=PSR2 --encoding=utf-8 -n -p $file
  if [ $? -ne 0 ]; then
    echo "Fix the error before commit please"
        echo "Run phpcbf --standard=PSR2 $file for automatic fix"
        echo "or fix it manually. (PHPStorm can help you)"
    exit 1 # exit with failure status
  fi
done

for file in $JS_FILES
do
echo $file
 eslint $file
  if [ $? -ne 0 ]; then
    echo "Fix the error before commit please"
    exit 1 # exit with failure status
  fi
done
online Thomas
  • 8,864
  • 6
  • 44
  • 85
  • it is giving .git/hooks/pre-commit: line 11: phpcs: command not found – Bhumi Shah Jul 29 '21 at 09:35
  • @BhumiShah make sure phpcs is installed and in your path (or use full path). just test by calling phpcs directly on your command line. – online Thomas Jul 29 '21 at 09:38
  • It is working if I run command under my laravel : "./vendor/bin/phpcs ./app"but when I try same command from pre-commit hook file, it is giving me error – Bhumi Shah Jul 29 '21 at 16:50