我正在寻找一种用PHP读取Git提交消息的方法.我怀疑我需要使用Git钩子,但我以前从未使用它们,所以我需要向正确的方向推进.具体来说,我想实现以下过程:
如果可能的话,我想坚持使用纯PHP.如果有可以指出的教程或参考资料,那将是一个巨大的帮助.
AD7*_*six 23
要获取提交哈希,您可以使用
git rev-parse --verify HEAD 2> /dev/null
Run Code Online (Sandbox Code Playgroud)
从PHP内:
exec('git rev-parse --verify HEAD 2> /dev/null', $output);
$hash = $output[0];
Run Code Online (Sandbox Code Playgroud)
您可以获取提交消息,作者和时间(但是 - 如果它作为提交后挂钩的一部分运行,时间将只是"现在"):
exec("git show $hash", $output);
Run Code Online (Sandbox Code Playgroud)
如果不是很明显,那么无论你用php做什么都只是围绕你在cli上用git做的事情的包装 - 也就是说"我怎么能用php从git做x"只是 exec('the git answer', $output)
至于使用PHP来提取正确的提交:
有一个名为Indefero的项目是一个PHP forge工具,它有一个用于git的SCM连接器.您可以轻松地将他们的git类用作自己的API.你可以抓住git类和SCM类.
例如,我从下面的课程中提取了两种方法,我认为这些方法与您最相关,因此您可以看到它们的工作原理.
getChangeLog()
/**
* Get latest changes.
*
* @param string Commit ('HEAD').
* @param int Number of changes (10).
* @return array Changes.
*/
public function getChangeLog($commit='HEAD', $n=10)
{
if ($n === null) $n = '';
else $n = ' -'.$n;
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' log%s --date=iso --pretty=format:\'%s\' %s',
escapeshellarg($this->repo), $n, $this->mediumtree_fmt,
escapeshellarg($commit));
$out = array();
$cmd = Pluf::f('idf_exec_cmd_prefix', '').$cmd;
self::exec('IDF_Scm_Git::getChangeLog', $cmd, $out);
return self::parseLog($out);
}
Run Code Online (Sandbox Code Playgroud)
getCommit()
/**
* Get commit details.
*
* @param string Commit
* @param bool Get commit diff (false)
* @return array Changes
*/
public function getCommit($commit, $getdiff=false)
{
if ($getdiff) {
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' show --date=iso --pretty=format:%s %s',
escapeshellarg($this->repo),
"'".$this->mediumtree_fmt."'",
escapeshellarg($commit));
} else {
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' log -1 --date=iso --pretty=format:%s %s',
escapeshellarg($this->repo),
"'".$this->mediumtree_fmt."'",
escapeshellarg($commit));
}
$out = array();
$cmd = Pluf::f('idf_exec_cmd_prefix', '').$cmd;
self::exec('IDF_Scm_Git::getCommit', $cmd, $out, $ret);
if ($ret != 0 or count($out) == 0) {
return false;
}
if ($getdiff) {
$log = array();
$change = array();
$inchange = false;
foreach ($out as $line) {
if (!$inchange and 0 === strpos($line, 'diff --git a')) {
$inchange = true;
}
if ($inchange) {
$change[] = $line;
} else {
$log[] = $line;
}
}
$out = self::parseLog($log);
$out[0]->diff = implode("\n", $change);
} else {
$out = self::parseLog($out);
$out[0]->diff = '';
}
$out[0]->branch = implode(', ', $this->inBranches($commit, null));
return $out[0];
}
Run Code Online (Sandbox Code Playgroud)
PEAR中还有一个名为VersionControl_Git的库,可以在这种情况下提供帮助并记录在案.