Skip to content

Instantly share code, notes, and snippets.

@jellisii

jellisii/pre-commit

Created Nov 8, 2018
Embed
What would you like to do?
PHPUnit for git pre-commit hook
#!/usr/bin/php
<?php
// output a little introduction
echo '>>>>>>>> Starting unit tests' . PHP_EOL;
// execute unit tests (it is assumed that a phpunit.xml configuration is present
// in the root of the project)
exec('vendor/bin/phpunit', $output, $returnCode); // cwd is assumed here
$yellow = false;
foreach ($output as $line) {
// lines ending in "%)" are individual test result displays.
if (strpos($line, "%)") !== false) {
foreach (str_split($line) as $chr) {
switch ($chr) {
case 'F':
$chr = "\033[41m\033[1m$chr\033[0m";
break;
case 'E':
$chr = "\033[91m\033[1m$chr\033[0m";
break;
case 'R':
case 'I':
case 'W':
$yellow = true;
$chr = "\033[93m\033[1m$chr\033[0m";
}
echo ($chr);
}
echo PHP_EOL;
continue;
}
if ($returnCode !== 0) {
if (strpos($line, 'Tests:') !== false) {
$line = "\033[41m\033[1m$line\033[0m";
}
} else {
if ($yellow) {
$color_string = "\033[103m\033[30m"; // yellow
if ($line === "OK, but incomplete, skipped, or risky tests!") {
$line = "$color_string$line\033[0m";
}
if (strpos($line, 'Tests:') !== false) {
$line = "$color_string$line\033[0m";
}
} else {
if (strpos($line, 'OK (') !== false) {
$line = "\033[42m\033[30m$line\033[0m";
}
}
}
echo ($line . PHP_EOL);
}
echo PHP_EOL;
if ($returnCode !== 0 || $yellow) {
$returnCode = 255;
echo '>>>>>>>> Aborting commit.' . PHP_EOL; // disable colors and add a line break
}
exit($returnCode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.