如何在我的开发网站的页面顶部显示当前的 git 分支名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7447472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 06:00:55  来源:igfitidea点击:

How could I display the current git branch name at the top of the page, of my development website?

phpgit

提问by program247365

Here's my situation:

这是我的情况:

I develop locally on my Mac using MAMP (PHP). My sites are under Git version control, and I point my dev servers to the root of the site under version control on disk.

我使用 MAMP (PHP) 在我的 Mac 上进行本地开发。我的站点受 Git 版本控制,我将我的开发服务器指向磁盘上受版本控制的站点的根目录。

File structure:
--mysitehere/
---.git/ (.git folder is here versioning everything below)
---src/ (<-- web server root)
----index.php (need the codez here for displaying current git branch)

Anyone have example code that I could use that looks in the .git folder and sees what the current branch is, and output it on the index.php page (and a ruby solution for RoR dev)? This would be super useful when I switch branches, and in my browser when I refresh, I see that I would be on 'master' at the top of the page, or 'your-topic-branch-name-here'.

任何人都有我可以使用的示例代码,我可以使用它在 .git 文件夹中查找并查看当前分支是什么,并将其输出到 index.php 页面(以及用于 RoR 开发的 ruby​​ 解决方案)?这在我切换分支时非常有用,并且在我刷新时在浏览器中,我看到我将位于页面顶部的 'master' 或 'your-topic-branch-name-here' 上

I'm willing to use a third-party library that accesses git programmatically in PHP, or something that gets the right 'current-branch' variable from a file on disk from within .git.

我愿意使用在 PHP 中以编程方式访问 git 的第三方库,或者从 .git 中的磁盘文件中获取正确的“当前分支”变量的东西。

回答by program247365

This worked for me in PHP, including it in the top of my site:

这在 PHP 中对我有用,包括在我网站的顶部:

/**
 * @filename: currentgitbranch.php
 * @usage: Include this file after the '<body>' tag in your project
 * @author Kevin Ridgway 
 */
    $stringfromfile = file('.git/HEAD', FILE_USE_INCLUDE_PATH);

    $firstLine = $stringfromfile[0]; //get the string from the array

    $explodedstring = explode("/", $firstLine, 3); //seperate out by the "/" in the string

    $branchname = $explodedstring[2]; //get the one that is always the branch name

    echo "<div style='clear: both; width: 100%; font-size: 14px; font-family: Helvetica; color: #30121d; background: #bcbf77; padding: 20px; text-align: center;'>Current branch: <span style='color:#fff; font-weight: bold; text-transform: uppercase;'>" . $branchname . "</span></div>"; //show it on the page

回答by Ryan

I use this function:

我使用这个功能:

protected function getGitBranch()
{
    $shellOutput = [];
    exec('git branch | ' . "grep ' * '", $shellOutput);
    foreach ($shellOutput as $line) {
        if (strpos($line, '* ') !== false) {
            return trim(strtolower(str_replace('* ', '', $line)));
        }
    }
    return null;
}

回答by Kamil Kie?czewski

Branch, last commit date and hash

分支、上次提交日期和哈希

<?php 
    $gitBasePath = '.git'; // e.g in laravel: base_path().'/.git';

    $gitStr = file_get_contents($gitBasePath.'/HEAD');
    $gitBranchName = rtrim(preg_replace("/(.*?\/){2}/", '', $gitStr));                                                                                            
    $gitPathBranch = $gitBasePath.'/refs/heads/'.$gitBranchName;
    $gitHash = file_get_contents($gitPathBranch);
    $gitDate = date(DATE_ATOM, filemtime($gitPathBranch));

    echo "version date: ".$gitDate."<br>branch: ".$gitBranchName."<br> commit: ".$gitHash;                                                       
?>

Example Output:

示例输出:

version date: 2018-10-31T23:52:49+01:00

branch: dev

commit: 2a52054ef38ba4b76d2c14850fa81ceb25847bab

版本日期:2018-10-31T23:52:49+01:00

分支:开发

提交:2a52054ef38ba4b76d2c14850fa81ceb25847bab

Modification date of file refs/heads/your_branchis (acceptable) approximation of last commit date (especially fo testing/staging environment where we assume that we will deploy fresh commits (no old ones)).

文件的修改日期refs/heads/your_branch是(可接受的)上次提交日期的近似值(特别是对于我们假设我们将部署新提交(没有旧提交)的测试/暂存环境)。

回答by Sergio Rodrigues

Simple way in PHP:

PHP中的简单方法:

  • Short hash:$rev = exec('git rev-parse --short HEAD');
  • Full hash:$rev = exec('git rev-parse HEAD');
  • 短哈希:$rev = exec('git rev-parse --short HEAD');
  • 完整哈希:$rev = exec('git rev-parse HEAD');

回答by Adam Elsodaney

To extend on program247365's answer, I've written a helper class for this, which also useful for those using Git Flow.

为了扩展program247365 的回答,我为此编写了一个帮助类,这对使用 Git Flow 的人也很有用。

class GitBranch
{
    /**
     * @var string
     */
    private $branch;

    const MASTER = 'master';
    const DEVELOP = 'develop';

    const HOTFIX = 'hotfix';
    const FEATURE = 'feature';

    /**
     * @param \SplFileObject $gitHeadFile
     */
    public function __construct(\SplFileObject $gitHeadFile)
    {
        $ref = explode("/", $gitHeadFile->current(), 3);

        $this->branch = rtrim($ref[2]);
    }

    /**
     * @param string $dir
     *
     * @return static
     */
    public static function createFromGitRootDir($dir)
    {
        try {
            $gitHeadFile = new \SplFileObject($dir.'/.git/HEAD', 'r');
        } catch (\RuntimeException $e) {
            throw new \RuntimeException(sprintf('Directory "%s" is not a Git repository.', $dir));
        }

        return new static($gitHeadFile);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->branch;
    }

    /**
     * @return boolean
     */
    public function isBasedOnMaster()
    {
        return $this->getFlowType() === self::HOTFIX || $this->getFlowType() === self::MASTER;
    }

    /**
     * @return boolean
     */
    public function isBasedOnDevelop()
    {
        return $this->getFlowType() === self::FEATURE || $this->getFlowType() === self::DEVELOP;
    }

    /**
     * @return string
     */
    private function getFlowType()
    {
        $name = explode('/', $this->branch);

        return $name[0];
    }
}

You can use it like:

你可以像这样使用它:

echo GitBranch::createFromGitRootDir(__DIR__)->getName();

回答by Timothy Allyn Drake

Git Library in PHP (GLIP) is a PHP library for interacting with Git repositories. It does not require Git to be installed on your server and can be found on GitHub.

PHP 中的 Git 库(GLIP)是一个用于与 Git 存储库交互的 PHP 库。它不需要在您的服务器上安装 Git,可以在GitHub找到

回答by Pete B

Quick and dirty option if you're in any subdirectory of the repo:

如果您位于 repo 的任何子目录中,则使用快速和脏选项:

$dir = __DIR__;
exec( "cd '$dir'; git br", $lines );
$branch = '';
foreach ( $lines as $line ) {
    if ( strpos( $line, '*' ) === 0 ) {
        $branch = ltrim( $line, '* ' );
        break;
    }
}

回答by Reiaguilera

Gist: https://gist.github.com/reiaguilera/82d164c7211e299d63ac

要点:https: //gist.github.com/reiaguilera/82d164c7211e299d63ac

<?php
// forked from lukeoliff/QuickGit.php

class QuickGit {
  private $version;

  function __construct() {
    exec('git describe --always',$version_mini_hash);
    exec('git rev-list HEAD | wc -l',$version_number);
    exec('git log -1',$line);
    $this->version['short'] = "v1.".trim($version_number[0]).".".$version_mini_hash[0];
    $this->version['full'] = "v1.".trim($version_number[0]).".$version_mini_hash[0] (".str_replace('commit ','',$line[0]).")";
  }

  public function output() {
    return $this->version;
  }

  public function show() {
    echo $this->version;
  }
}