我想在我的网站上显示git版本

MrO*_*MrO 18 php versioning git github

我想在我的网站上显示git版本号.

我发现它是一个提交哈希,这不适合非技术用户参考.

我创建了这个类来显示这个脚本当前git本地的版本'number'.

Jen*_*och 45

首先,一些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)
Run Code Online (Sandbox Code Playgroud)


MrO*_*MrO 14

要点: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;
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 所以你的版本号只是计算提交.如果您从未使用任何分支和合并,这将正常工作.如果存在任何分支,则该数字不一定唯一地标识单个提交.人们可以尝试用点符号解决问题.例如4.1.5表示从根提交4次后,取第一个分支并提前5次提交.这将要求例如通过提交时间来对分支进行排序.Git不保证较新的提交有较新的提交时间,您需要通过您的进程保证.编码这样的编号方案需要更多的工作. (5认同)

Har*_*y B 8

如果你不想这样做exec()而且你正在使用git标记:

您可以从.git/HEAD或获取当前的HEAD提交哈希.git/refs/heads/master.然后我们循环找到匹配.首先反转数组以获得速度,因为您更有可能使用更高的最新标记.

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

<?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';
Run Code Online (Sandbox Code Playgroud)

  • 我也是,但是对我没用。阅读 `.git/HEAD` 给了我 `ref: .git/refs/heads/master`。当我读到 `.git/refs/heads/master` 时,我得到了提交哈希值。所以我编辑了你的答案!(并为您投了赞成票,而其他人则对使用 exec 投了反对票) (2认同)

小智 5

我这样做就像:

substr(file_get_contents(GIT_DIR.'/refs/heads/master'),0,7)

资源友好,与我在 Eclipse 下显示的相同