Search code examples
phpgitcoding-stylephpcodesniffer

Git: pre-receive hook with PHP_CodeSniffer


Since switching from SVN to Git, we lost the ability to enforce our coding standards through a pre-commit hook on the subversion server.

With Git, you only have pre-commit hooks on the client which cannot be enforced in any way. What makes it worse is that we have developers working with all three main operating systems, thus a pre-commit hook that works on Linux or OS X does not automatically work on Windows.

The way to go is implementing a pre-receive hook on the server, but the solution is not as easy as it seems:

Imagine the developer did 20 commits and wants to push them. All pre-commit and pre-receive hooks I know of (1, 2) just check the single commits, which will ultimately fail and prevent the push. Now the developer fixes the issues and does another commit, and tries to push again. Since the hooks check the single commits, it will fail again.

So we need a pre-receive hook that generates a list of all changed files in all commits that are going to be pushed and runs phpcs on the current state only.

Does such a hook script exist already? Where?

Edit: There seems to be a script that creates that list of files - unfortunately in Python, but that can be ported. I'm still interested in pre-made solutions with PHPCS :)


Solution

  • We do now employ pre-commit hooks that both check the code and the commit message.

    Developers can skip them with -n, but they rarely do and we always have another developer doing QA so things get noticed.

    The hook is important because it notices when files are broken, so that broken PHP or JS doesn't get committed at all.

    Find them hook code at https://github.com/netresearch/git-client-hooks

    We use a central server for development, and our git hooks get automatically installed because we provide a central git repository template that gets used automatically when you git clone or git init.