Search code examples
gitgithookspre-commit-hookphpcodesniffer

git pre-commit hook under Windows run PHP_CodeSniffer against staged files


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?


Solution

  • 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