我想在我的网站上显示 Git 版本。
如何显示 Git 的语义版本号,以便网站的非技术用户在提出问题时可以轻松参考?
首先,一些获取版本信息的
git
命令:
git log --pretty="%H" -n1 HEAD
git log --pretty="%h" -n1 HEAD
git log --pretty="%ci" -n1 HEAD
git describe --tags --abbrev=0
git describe --tags
其次,使用
exec()
结合上面您选择的 git 命令来构建版本标识符:
class ApplicationVersion
{
const MAJOR = 1;
const MINOR = 2;
const PATCH = 3;
public static function get()
{
$commitHash = trim(exec('git log --pretty="%h" -n1 HEAD'));
$commitDate = new \DateTime(trim(exec('git log -n1 --pretty=%ci HEAD')));
$commitDate->setTimezone(new \DateTimeZone('UTC'));
return sprintf('v%s.%s.%s-dev.%s (%s)', self::MAJOR, self::MINOR, self::PATCH, $commitHash, $commitDate->format('Y-m-d H:i:s'));
}
}
// Usage: echo 'MyApplication ' . ApplicationVersion::get();
// MyApplication v1.2.3-dev.b576fd7 (2016-11-02 14:11:22)
请注意,在生产系统上,PHP 的
exec
通常位于 disabled_functions
列表中,而 git
可能不可用。上面的代码可能会成为构建脚本的一部分。这使您能够在开发或构建阶段对应用程序进行版本化(例如,在具有 git
和 PHP exec
的开发容器上),并使用静态版本字符串将其部署到生产环境。
如果您想在没有
exec()
的情况下执行此操作,并且您正在使用 git 轻量级(请参阅下面的评论)标记:
您可以从
.git/HEAD
或 .git/refs/heads/master
获取当前 HEAD 提交哈希。然后我们循环查找匹配。首先反转数组以提高速度,因为您更有可能获得更高的最近标签。
因此,如果当前 php 文件位于
public_html
或 www
文件夹中,比 .git
文件夹低一级...
<?php
$HEAD_hash = trim(file_get_contents('../.git/refs/heads/master')); // or branch x
$files = glob('../.git/refs/tags/*');
foreach(array_reverse($files) as $file) {
$contents = trim(file_get_contents($file));
if($HEAD_hash === $contents)
{
print 'Current tag is ' . basename($file);
exit;
}
}
print 'No matching tag';
要点:https://gist.github.com/lukeoliff/5501074
<?php
class QuickGit {
public static function version() {
exec('git describe --always',$version_mini_hash);
exec('git rev-list HEAD | wc -l',$version_number);
exec('git log -1',$line);
$version['short'] = "v1.".trim($version_number[0]).".".$version_mini_hash[0];
$version['full'] = "v1.".trim($version_number[0]).".$version_mini_hash[0] (".str_replace('commit ','',$line[0]).")";
return $version;
}
}
简单的方法:
$rev = exec('git rev-parse --short HEAD');
$rev = exec('git rev-parse HEAD');
我是这样做的:
substr(file_get_contents(GIT_DIR.'/refs/heads/master'),0,7)
资源友好,与我在 Eclipse 下显示的相同
在终端中运行
git tag
预览您的标签并说您得到了即:
v1.0.0
v1.1.0
v1.2.4
以下是如何获取最新版本
v1.2.4
function getVersion() {
$hash = exec("git rev-list --tags --max-count=1");
return exec("git describe --tags $hash");
}
echo getVersion(); // "v1.2.4"
巧合(如果您的标签已排序),因为
exec
仅返回最后一行,我们可以这样做:
function getVersion() {
return exec("git tag");
}
echo getVersion(); // "v1.2.4"
要获取所有行字符串,请使用
shell_exec
:
function getVersions() {
return shell_exec("git tag");
}
echo getVersions(); // "v1.0.0
// v1.1.0
// v1.2.4"
获取数组:
$tagsArray = explode(PHP_EOL, shell_exec("git tag"));
按日期对标签排序:
git tag --sort=committerdate
文档:git-for-each-ref#_field_names
出于排序目的,具有数值的字段按数字顺序排序(对象大小、作者日期、提交日期、创建者日期、标记者日期)。所有其他字段都用于按字节值顺序排序。
public function getTagVersion()
{
$files = glob($this->projectDir.'/.git/refs/tags/*');
return basename(end($files));
}