Skip to content

Instantly share code, notes, and snippets.

@jellisii
Created November 8, 2018 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jellisii/2c2feaed0b9812c7f2667e383e1c1356 to your computer and use it in GitHub Desktop.
Save jellisii/2c2feaed0b9812c7f2667e383e1c1356 to your computer and use it in GitHub Desktop.
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