Skip to content

Instantly share code, notes, and snippets.

@latheesan-k
Created December 1, 2014 19:40
Show Gist options
  • Save latheesan-k/3490cb6ab522ca87f535 to your computer and use it in GitHub Desktop.
Save latheesan-k/3490cb6ab522ca87f535 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>";
?>
@gabiudrescu
Copy link

include some \n where you want a new line.

@mattbucci
Copy link

this breaks if a commit message contains the word "commit" instead of using !== false replace with === 0 for more strictness

@PF94
Copy link

PF94 commented Feb 22, 2021

include some \n where you want a new line.

but how?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment