geeknam's blog

A young inspired developer.

Using PHP to Parse Git History

Here is how you can store git command output in a good manner after which you will be able to easily retrieve necessary information. This snippet belongs to the project I’m currently working on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
// Author: Ngo Minh Nam

$dir = "/path/to/your/repo/";
$output = array();
chdir($dir);
exec("git log",$output);
$history = array();
foreach($output as $line){
    if(strpos($line, 'commit')===0){
        if(!empty($commit)){
            array_push($history, $commit);
            unset($commit);
        }
        $commit['hash']   = substr($line, strlen('commit'));
    }
    else if(strpos($line, 'Author')===0){
        $commit['author'] = substr($line, strlen('Author:'));
    }
    else if(strpos($line, 'Date')===0){
        $commit['date']   = substr($line, strlen('Date:'));
    }
    else{
        $commit['message']  .= $line;
    }
}

print_r($history);

?>

Comments