Как я могу отобразить текущее имя ветки git в верхней части страницы моего веб-сайта разработки?
Вот моя ситуация:
Я разрабатываю локально на своем Mac с помощью MAMP (PHP). Мои сайты находятся под управлением Git, и я указываю свои серверы dev на корень сайта под управлением версии на диске.
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 dev)? Это было бы очень полезно, когда я переключаю ветки, и в моем браузере, когда я обновляюсь, я вижу, что я буду на "хозяине" в верхней части страницы или "your-topic-branch-name-here" здесь,.
Я хочу использовать стороннюю библиотеку, которая обращается к Git программно в PHP, или что-то, что получает правильную переменную current-branch из файла на диске изнутри .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
Ответ 2
Я использую эту функцию:
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;
}
Ответ 3
Простой способ в PHP:
- Короткий хеш:
$rev = exec('git rev-parse --short HEAD');
- Полный хеш:
$rev = exec('git rev-parse HEAD');
Ответ 4
Git Библиотека в PHP (GLIP) - это библиотека PHP для взаимодействия с репозиториями Git. Он не требует установки Git на ваш сервер и может быть найден на GitHub.
Ответ 5
Чтобы продолжить на program247365 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();
Ответ 6
Быстрая и грязная опция, если вы находитесь в любом подкаталоге репо:
$dir = __DIR__;
exec( "cd '$dir'; git br", $lines );
$branch = '';
foreach ( $lines as $line ) {
if ( strpos( $line, '*' ) === 0 ) {
$branch = ltrim( $line, '* ' );
break;
}
}
Ответ 7
Gist: 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;
}
}