Syntax checking PHP, JavaScript, Python automatically with Git

When reviewing code, a simple first step in checking that it doesn’t include any errors is to run a syntax check. In this post, I outline how to set up tools to scan all the code in a directory for syntax errors, and how to run this scan automatically when committing your code to git. For simplicity’s sake I am assuming that you are running Ubuntu, but the principles apply to any development environment.

PHP

The command line version of PHP (package php7.x-cli) allows you to syntax check a single file:

php -l /path/to/file.php

I use a wrapper script around this to scan a whole directory:

#!/bin/sh
if [ $# -eq 0 ]
	then
	DIR=.
elif [ -d "$1" ]
	then
	DIR="$1"
else
	echo Usage: "$0" \[directory\]
	exit 1
fi

find "$DIR" -type f -iname "*.php" | while read i
do
	php -l "$i" | grep -v No\ syntax\ errors\ detected\ in\ \.
done
exit 0

Save this script to a suitable location, e.g. /usr/local/bin/phplint and make it executable with chmod +x /usr/local/bin/phplint. You can now scan all PHP files in the current directory by running phplint, or all of the PHP files in another directory by running phplint /path/to/dir. If you don’t see any output, that means there are no errors.

JavaScript

Similarly to PHP, you can syntax check a single JavaScript file by installing package nodejs and then running:

node -c /path/to/file.js

You can use this wrapper script around this to scan a whole directory:

#!/bin/sh
if [ $# -eq 0 ]
	then
	DIR=.
elif [ -d "$1" ]
	then
	DIR="$1"
else
	echo Usage: "$0" \[directory\]
	exit 1
fi

find "$DIR" -type f -iname "*.js" | while read i
do
	node -c "$i"
done

Save this script to a suitable location, e.g. /usr/local/bin/jslint and make it executable with chmod +x /usr/local/bin/jslint. (Note: this name might conflict with other packages – try running jslint before you set up this script, to see if you already have another executable with the same name on your path.) As with the PHP script, if you don’t see any output, that means there are no errors.

Python

You can syntax check a single Python file by compiling it to bytecode:

python3 -m py_compile file.py

This will create a folder __pycache__ in the current directory containing the compiled version of the file. If there are any syntax errors in the file, it will warn about them on the command line. No output means no errors were found. It’s not necessary to write a wrapper script for this, as Python on Ubuntu ships with a handy tool to byte-compile all files in a directory:

py3compile /path/to/files

Integrating with Git hooks

If you want to automatically code for syntax errors before each git commit, simply add one or more of the above scans to the pre-commit hook in .git/hooks/pre-commit. Remember to include a shebang at the top and make the hook executable with chmod +x .git/hooks/pre-commit. For example:

#!/bin/sh
py3compile .
phplint
jslint

Add new comment

CAPTCHA