Using Git Hooks


If you want to make sure to run tests on every commit or push, git hooks are a great and easy tool to use. Git hooks are a mechanism that allows arbitrary code to be run before, or after, certain Git lifecycle events occur. The hooks can be any executable code, including shell, PowerShell, Python, or any other scripts. Alternatively, they may be a binary executable. Anything goes!

The hooks are found in the .git/hooks directory.

Run open /your-project/.git/hooks in your terminal to see all available hooks.

Git hooks

These are the available hooks. Here is a detailed description of each hook

Git hooks

To activate a hook to run before a commit rename pre-push.sample to pre-push.

#!/usr/bin/env php
<?php
echo "Running tests.. ";

// Maybe phpunit or some others tests you want to run
exec('vendor/bin/phpunit', $output, $returnCode);
if ($returnCode !== 0) {
    // Show full output
    echo PHP_EOL . implode($output, PHP_EOL) . PHP_EOL;
    echo "Aborting commit.." . PHP_EOL;
    exit(1);
}
// Show summary (last line)
echo array_pop($output) . PHP_EOL;
exit(0);


Done! Now this script will be performed on every push, but you’ll notice that the hook has a side effect: commits take some time to complete and here lies the critical point. You don’t want your commits to take too long.

NOTE: These hooks are local on your machine and is not committed to the git repository. By default, hooks are stored in .git/hooks outside of the working tree and are thus not shared between users of the repository. There are ways to include this into your repository or set up global git hooks.

Need a simple way to do smarter deployments? Take a look at GitFTP-Deploy. Try free for 7 days.