【问题标题】:How could I display the current git branch name at the top of the page, of my development website?如何在我的开发网站的页面顶部显示当前的 git 分支名称?
【发布时间】:2011-11-18 20:01:55
【问题描述】:

这是我的情况:

我使用 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)

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

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

【问题讨论】:

标签: php git


【解决方案1】:

这在 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

【讨论】:

  • 如果分支名称包含“/”,这将不起作用:大多数 git 流功能都可以。您将不得不对数组进行切片,然后再次将其内爆: $explodedstring = array_slice( $explodedstring , 2 ); $branchname = implode("/", $explodedstring);
  • 在线&lt;?php echo implode('/', array_slice(explode('/', file_get_contents('.git/HEAD')), 2)); ?&gt;
  • 它打破了很多环境,其中 bug/foo 或 feature/bar 是一种约定,例如 Git Flow。解决方法是将爆炸限制为 3 个项目或手动获取 ref 之后的内容:refs/heads/ ...
  • 如果我们要变得笨拙,$gitCurrentBranch = trim(substr(file_get_contents('.git/HEAD'), 16));只要 .git/HEAD 保持其当前格式。
  • 我建议让$branchname = trim($explodedstring[2]); 字符串末尾可能包含换行符
【解决方案2】:

分支、最后提交日期和哈希

<?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;                                                       
?>

示例输出:

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

分支:开发

提交:2a52054ef38ba4b76d2c14850fa81ceb25847bab

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

【讨论】:

    【解决方案3】:

    我使用这个功能:

    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;
    }
    

    【讨论】:

      【解决方案4】:

      PHP 中的简单方法:

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

      【讨论】:

      • 只要本地机器上的配置允许您执行 git,它就可以工作。我个人遇到了问题并切换到program247365的答案来解决它。
      【解决方案5】:

      为了在 program247365's answer 上进行扩展,我为此编写了一个帮助类,它对使用 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];
          }
      }
      

      你可以像这样使用它:

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

      【讨论】:

      • 这很好,但分支名称不应该由固定常量假定。有些人使用不同的分支名称,最好能够将它们传递给构造函数或使用静态配置方法,这样就不需要在每个项目或每个 repo 结构的基础上重写代码。
      • @mopsyd 是的,但是他们不会实施 Git Flow 标准。这里的代码假定一个严格的实现。也许这些方法的接口可以解决那些使用自己的约定的问题。
      • git flow 标准并不适合每个人的用例。我更喜欢它,但有许多项目不合适,例如从单个分支 SVN 存储库移植过来的项目。对其他人的代码强制执行意见是不合适的,除非他们彼此之间有一些紧密的耦合,这通常是不可取的,除非在非常特殊的情况下。
      【解决方案6】:

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

      【讨论】:

      • 似乎你必须先传入一个分支名称,然后才能访问 glip 的东西。它似乎不适用于我想要的东西,因为它无法显示分支,它只是希望您通过名称直接访问它们。话虽如此,我发现在任何 .git/ repo 目录中,都有一个名为“HEAD”的文件,其中包含当前分支名称。我可能会直接解析它,并在完成后在这里发布我的答案。
      【解决方案7】:

      如果您在 repo 的任何子目录中,则选择快速而肮脏的选项:

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

      【讨论】:

      • 我想git br 是你的别名git branch
      【解决方案8】:

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

      【讨论】:

        【解决方案9】:

        读取.git/HEAD 文件的给定解决方案导致我的管道失败。

        受到这个问题的启发:How to programmatically determine the current checked out Git branch

        您可以使用 :

        获取 git 分支名称

        $gitBranchName = trim(shell_exec("git rev-parse --abbrev-ref HEAD"));

        【讨论】:

          猜你喜欢
          • 2010-11-20
          • 2017-07-31
          • 2010-12-22
          • 2015-05-26
          • 2011-09-08
          • 2019-08-09
          • 2011-12-25
          • 2012-10-05
          相关资源
          最近更新 更多