Skip to content

Instantly share code, notes, and snippets.

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 seb86/1baa022ffa01be1d8f88 to your computer and use it in GitHub Desktop.
Save seb86/1baa022ffa01be1d8f88 to your computer and use it in GitHub Desktop.
Parse git logs into array in PHP
<?php
// Change To Repo Directory
chdir("/full/path/to/repo");
// Load Last 10 Git Logs
$git_history = [];
$git_logs = [];
exec("git log -10", $git_logs);
// Parse Logs
$last_hash = null;
foreach ($git_logs as $line)
{
// Clean Line
$line = trim($line);
// Proceed If There Are Any Lines
if (!empty($line))
{
// Commit
if (strpos($line, 'commit') !== false)
{
$hash = explode(' ', $line);
$hash = trim(end($hash));
$git_history[$hash] = [
'message' => ''
];
$last_hash = $hash;
}
// Author
else if (strpos($line, 'Author') !== false) {
$author = explode(':', $line);
$author = trim(end($author));
$git_history[$last_hash]['author'] = $author;
}
// Date
else if (strpos($line, 'Date') !== false) {
$date = explode(':', $line, 2);
$date = trim(end($date));
$git_history[$last_hash]['date'] = date('d/m/Y H:i:s A', strtotime($date));
}
// Message
else {
$git_history[$last_hash]['message'] .= $line ." ";
}
}
}
echo "<pre>";
print_r($git_history);
echo "</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment