Skip to content

Instantly share code, notes, and snippets.

@jsteemann
Created March 11, 2015 11:41
Show Gist options
  • Save jsteemann/65ef221646449713b2c5 to your computer and use it in GitHub Desktop.
Save jsteemann/65ef221646449713b2c5 to your computer and use it in GitHub Desktop.
script to convert local git commit log into JSON
<?php
// script to convert local git commit log history into JSON format
// usage: cd git-repository && php git-log-to-json.php > commits.json
// script might take a while to execute
$tags = [ ];
$lines = shell_exec('git show-ref --tags');
foreach (array_filter(explode("\n", $lines)) as $line) {
list($commit, $ref) = explode(" ", $line, 2);
$tags[$commit] = preg_replace("/^refs\/tags\//", "", $ref);
}
$ids = [ ];
$lines = shell_exec('git log --full-history --pretty="format:%H"');
foreach (explode("\n", $lines) as $line) {
$ids[] = $line;
}
$commits = [ ];
foreach ($ids as $id) {
$output = shell_exec('git log -1 --name-only --pretty="format:%H xxxxPARENTSxxxx %P xxxxDATExxxx %ai xxxxAUTHOR-NAMExxxx %an xxxxAUTHOR-EMAILxxxx %ae xxxxMSGxxxx %s xxxxFILESxxxx" ' . $id);
if (! preg_match("/^([a-f0-9]+)\sxxxxPARENTSxxxx\s(([a-f0-9]+\s)*\s?)xxxxDATExxxx\s(\d+-\d+-\d+\s\d+:\d+:\d+\s[^\s]+)\sxxxxAUTHOR-NAMExxxx\s(.*)?\sxxxxAUTHOR-EMAILxxxx\s(.*?)\sxxxxMSGxxxx\s(.*?)\sxxxxFILESxxxx\s*/", $output, $matches)) {
die("oops, unexpected input: " . $output . PHP_EOL);
}
$commits[$id] = [
"_key" => $id,
"date" => $matches[4],
"author" => [
"name" => $matches[5],
"email" => str_replace("@", " (at) ", $matches[6]) . ".nospam",
],
"message" => $matches[7]
];
if ($matches[2] !== "") {
$commits[$id]["parents"] = explode(" ", trim($matches[2]));
}
$files = trim(substr($output, strlen($matches[0])));
if ($files !== "") {
$commits[$id]["files"] = explode("\n", $files);
}
if (isset($tags[$id])) {
$commits[$id]["tag"] = $tags[$id];
}
}
echo json_encode(array_values($commits), false) . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment