Have you ever reviewed code that contained parse errors and wasn’t even proper PHP? I have and that’s why I have finally decided to stop that. Well, I have not decided to stop reviewing code, I have decided to prevent people committing PHP code which contain parse errors. With git hooks it’s fairly easy.
One way to do it would be with pre-commit hook. Travis Swicegood explained it very well in his blog post. One problem with that is that every developer would have to deploy that hook locally in every repository. So that was really not an option for us.
To get it installed simply copy pre-receive hook into hooks subdirectory of a repository on a git server and make the file executable.
So how does it work? It’s actually pretty simple. If the hook exists with a non zero error code the push will fail, otherwise it will succeed. So all we have to do is to get a list of files changed in a given changeset and run php linter against them.
Running git diff with –name-only option will give us list of changed files. But we cannot simply run php linter at this point as you have to remember that on git server there is just bare repository, without working directory tree. So we have to fetch the files straight from git context. We can fetch an object contents from index using git cat-file command, but it requires a unique object identifier to return file contents, so first we need to get this first. git ls-tree command is just what we need. Running it with new revision id and file name, we will get all the information we need!
Writing objects: 100% (9/9), 857 bytes, done.
otherwise we just stop the script with a zero code!
Writing objects: 100% (6/6), 658 bytes, done.
No more parse errors! FTW!
Thanks for your great script.
We’ve found a little glitch, when there are deletes php files in git diff.
Really helped me in my task.
I edited your code abit to also test code with PHPCodeSniffer.