Search code examples
phpgitjenkinslintphplint

How to lint or static analysis for only changed files in a branch?


I am using Jenkins and doing PHPMD, PHPCS and PHP lint checks for Pull Requests. What we have is basically a separate branch for each feature and it supposed to merge into the master branch again if it passes checks and tests.

We are checking all php files in the project with this command:

echo "php syntax checks are started"
find ./ -type f -name \*.php -exec php -l '{}' \; | grep -v "No syntax errors detected" && echo "PHP Syntax error(s) detected" && exit 1;

Using "php -l" for all php files takes around minute.

I was wondering if there is a way to speed up for this and came up with a solution. Please check my answer below.


Solution

  • Considering only few php files are going to change this takes only few seconds.

    echo "php syntax checks for only changed files"
    ( ( (git diff --name-only origin/master $GIT_COMMIT ) | grep .php$ ) | xargs -n1 echo php -l | bash ) | grep -v "No syntax errors detected" && echo "PHP Syntax error(s) detected" && exit 1;
    

    If you are using git plugin with Jenkins you can keep $GIT_COMMIT otherwise change it with commit number or branch name.

    This can be used also for css and js lints as well. Change "php -l" part depends on what you need.