且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有exec/shell_exec的情况下使用php显示活动的git标记

更新时间:2022-05-30 21:49:48

您可以从.git/HEAD获取当前HEAD提交哈希.然后,您可以循环所有标记引用以查找匹配的提交哈希.我们首先将阵列反转,因为您比以前的旧标签更有可能使用最新标签.

You can get the current HEAD commit hash from .git/HEAD. You can then loop all tag refs to find a matching commit hash. We reverse the array first as you're more likely to be on a recent tag than an old one.

显然,用变量替换exit并将其吐到页面上会带来更好的结果.

Obviously replacing the exits with variabled and spitting it to the page will give you a better result.

因此,如果您的php文件位于.git文件夹下一级的public_htmlwww文件夹中...

So if your php file sits in a public_html or www folder one level down from the .git folder...

<?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)
    {
        exit('Current tag is ' . basename($file));
    }
}

exit('No matching tag');