VirtuosiMedia VirtuosiMedia - 1 year ago 176
Git Question

Reading a Git commit message from PHP

I'm looking for a way to read a Git commit message with PHP. I suspect I need to use a Git hook, but I've never worked with them before, so I need a push in the right direction. Specifically, I'd like to implement the following process:

  • A PHP script is executed automatically after every commit

  • The script captures the Git username, the time of the commit, and the commit content

If at all possible, I'd like to stick with pure PHP. If there are tutorials or references that you could point out, that would be a huge help.

Answer Source

To get the commit hash, you can use

git rev-parse --verify HEAD 2> /dev/null

From within php:

exec('git rev-parse --verify HEAD 2> /dev/null', $output);
$hash = $output[0];

You can get the commit message, author and time (though - the time will simply be "now" if it's run as part of a post-commit hook) with:

exec("git show $hash", $output);

If it's not obvious, whatever you do with php is simply going to be a wrapper around the things you'd do with git on the cli - I.e. any "how can I do x with git from php" is just exec('the git answer', $output)