Skip to content

Instantly share code, notes, and snippets.

@andrewmackrodt
Last active August 29, 2015 14:03
Show Gist options
  • Save andrewmackrodt/065c0fdb6aed7bd90210 to your computer and use it in GitHub Desktop.
Save andrewmackrodt/065c0fdb6aed7bd90210 to your computer and use it in GitHub Desktop.
Produces a coloured git diff with options to exclude paths and output to html
#!/usr/bin/env php
<?php
function ansi2html($text) {
return preg_replace('/\x1B\[m/', '', preg_replace_callback('/\x1B\[(\d+)m(.*?)\x1B\[m/m', function ($match) {
switch ($match[1]) {
case 31: $rgb = array(170, 0, 0); break;
case 32: $rgb = array(0, 170, 0); break;
case 36: $rgb = array(0, 170, 170); break;
default: $rgb = array(0, 0, 0);
}
$rgb = implode(',', $rgb);
$s = "<span style='color:rgb($rgb);'>{$match[2]}</span>";
if ($match[1] == 1) {
$s = "<b>$s</b>";
}
return $s;
}, htmlspecialchars($text)));
}
function arg($k = '', $default = null) {
if (empty($GLOBALS['argv'])) {
return $default;
}
$args = implode("\0", array_slice($GLOBALS['argv'], 1));
if ($k) {
$keyRegex = preg_quote("-$k");
if (preg_match("/(?:^|\\0)$keyRegex(?:=|\\0)?([^\\0]+)/", $args, $match)) {
return $match[1];
}
} else {
if (preg_match("/(?:^|\\0)([^\\0]+)$/", $args, $match)) {
return $match[1];
}
}
return $default;
}
function bash_exec($cmd, $_ = null) {
$cmd = call_user_func_array('escapecmd', func_get_args());
$cmd = call_user_func_array('escapecmd', array('bash -c %s', $cmd));
return shell_exec($cmd);
}
function escapecmd($cmd, $_ = null) {
$args = array($cmd);
foreach (array_slice(func_get_args(), 1) as $arg) {
if ($arg !== null && $arg !== false) {
$arg = escapeshellarg($arg);
}
$args[] = $arg;
}
return call_user_func_array('sprintf', $args);
}
function line_numbers($html) {
$i = 1;
$buffer = "<table>\n";
foreach (explode("\n", $html) as $line) {
$buffer .= "<tr><td>$i</td><td>$line</td></tr>\n";
$i++;
}
$buffer .= "</table>";
return $buffer;
}
$folder = realpath(arg(null, __DIR__));
$base = arg('b', 'master');
$compare = arg('c', 'develop');
$isHtml = arg('H') !== null;
if ($exclude = arg('e')) {
$grep = '| grep -Ev %s';
} else {
$grep = '%s';
$exclude = null;
}
chdir($folder);
$diff = bash_exec(
"git diff %s %s --name-only $grep | xargs git diff --color=always %s %s --",
$base,
$compare,
$exclude,
$base,
$compare
);
if ($isHtml): ?>
<!doctype html><pre><?= line_numbers(ansi2html($diff)); ?></pre>
<?php else:
echo $diff;
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment