Setting up PHPCS in GitLab only on changed files

I wanted to save some time on our runners in GitLab and decided to only run phpcs on changed files for that merge request. I also wanted it to run as a git commit hook to try and prevent bad code from even getting pushed up.

What I came up with was to add two shell scripts to the repo under the folder bin. (chmod u+x)


git fetch origin master
git diff --name-status origin/master | grep '\.php$' | grep -v "^[RD]" | awk '{ print $2 }'

Add the follow to your .gitlab-ci.yml

  stage: testing
  needs: ["composer"]
  image: lorisleiva/laravel-docker
    - files=`sh bin/`
    - phpcs --config-set ignore_warnings_on_exit 1
    - if [ ! -z "$files" ]; then echo $files | xargs phpcs; fi could just go inside the yml file, but I like using it before deploys.

Thanks, for reading, please let me know if you found this helpful or have questions over on Twitter: