[英]How to display current working copy version of an hg repository on a PHP page
[英]Display the current Git 'version' in PHP
我想在我的網站上顯示 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)
要點: 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;
}
}
如果您想在沒有exec()
情況下exec()
並且您正在使用 git 輕量級(請參閱下面的評論)標記:
您可以從.git/HEAD
或.git/refs/heads/master
獲取當前的 HEAD 提交哈希。 然后我們循環查找匹配項。 首先反轉數組以提高速度,因為您更有可能使用更高的最近標簽。
因此,如果當前的 php 文件位於.git
文件夾下一級的public_html
或www
文件夾中......
<?php
$HEAD_hash = file_get_contents('../.git/refs/heads/master'); // or branch x
$files = glob('../.git/refs/tags/*');
foreach(array_reverse($files) as $file) {
$contents = file_get_contents($file);
if($HEAD_hash === $contents)
{
print 'Current tag is ' . basename($file);
exit;
}
}
print 'No matching tag';
簡單的方法:
$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
來預覽你的標簽並說你得到了 ie:
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
出於排序目的,具有數值的字段按數字順序排序(對象大小、作者日期、提交者日期、創建者日期、標記日期)。 所有其他字段都用於按其字節值順序進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.