Skip to content

Instantly share code, notes, and snippets.

@nfreear
Last active December 11, 2015 13:29
Show Gist options
  • Select an option

  • Save nfreear/4608017 to your computer and use it in GitHub Desktop.

Select an option

Save nfreear/4608017 to your computer and use it in GitHub Desktop.
Git prepare-commit-msg hook to append an issue tracker URL to commit messages (PHP).
#!/C/xampp/php/php
<?php
#!/usr/bin/env php
/**
* Git prepare-commit-msg hook to append an issue tracker URL to commit messages.
*
* Git hooks on Windows: Ensure that the path to PHP is added to the %PATH% variable, and run `git commit` via the Bash shell.
*
* Usage: `git commit -em "Bug #123" <FILE>`
*
* @copyright 2013-01-23 N.D.Freear.
* @license MIT
* @link http://progit.org/book/ch7-3.html
* @link https://github.com/github/github-services/blob/master/services/bugzilla.rb
*/
define('BUG_REGEX', '/^[\n]*(Ticket|Bug|Issue|Closes|Fixes| ?#){1,2} ?(\d+)[^\n]*/i');
define('BUG_URL', "http://iet-it-bugs.open.ac.uk/node/\\2\n#* https://iet.teamworkpm.net/tasks/\\2");
define('BUG_MSG_PREFIX', "#\\0\n\n#* ");
$commit_editmsg_file = $argv[1];
$template = @file_get_contents($commit_editmsg_file);
if (! $template) {
_hook_status(1, 'Read error, empty `.git/COMMIT_EDITMSG` template');
}
if (preg_match('/^(\.|-a|--all|-.+)/', $template, $matches_a)) {
_hook_status(1, "Error, unexpected `$matches_a[1]` in `.git/COMMIT_EDITMSG` template");
}
if (! isset($argv[2]) || 'message' !== $argv[2]) {
_hook_status(1, 'Expecting `git commit -em "Bug #123" <FILE>` or `git cm "Bug #123 <FILE>`');
}
if (! preg_match(BUG_REGEX, $template, $matches)) {
_hook_status(1, 'Expecting `git commit -em "Bug #123" <FILE>` or `git cm "Bug #123 <FILE>`');
}
$new_template = preg_replace(BUG_REGEX, BUG_MSG_PREFIX . BUG_URL, $template);
$bytes = @file_put_contents($commit_editmsg_file, $new_template);
if (! $bytes) {
_hook_status(1, 'Write error, `.git/COMMIT_EDITMSG` template');
}
_hook_status(0);
function _hook_status($exit = 1, $message = NULL) {
switch ($exit) {
case 0:
// Success.. exit
echo '> Hook OK: prepare-commit-msg' .PHP_EOL;
exit (0);
case -1:
// Intermediate status message
echo '> Hook OK: '. $message .PHP_EOL;
break;
case 1:
default:
// ERROR.. abort
echo '> Hook aborting commit: prepare-commit-msg.'. PHP_EOL .'> '. $message .PHP_EOL;
exit($exit);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment