<?php
/**
* Read current Git branch from HEAD file and return it as a string.
*
* @param string $repoRoot Path the .git repo's parent directory. Defaults to working directory.
*
* @return boolean|string Returns FALSE if branch or HEAD file could not be found, otherwise returns branch name as string.
*/
function getGitBranch($repoRoot = null)
{
if (empty($repoRoot)) {
$repoRoot = __DIR__;
}
$headFile = $repoRoot . DIRECTORY_SEPARATOR . '.git' . DIRECTORY_SEPARATOR . 'HEAD';
if (!file_exists($headFile)) {
return false;
}
// This RegEx does not fully validate the branch names.
// See this StackOverflow post for improvements: http://stackoverflow.com/a/3651867
preg_match('/[^.\/][A-Za-z0-9\.\-_]+$/i', trim(file_get_contents($headFile)), $branch);
return (bool) $branch ? $branch[0] : false;
}
if ($theBranch = getGitBranch()) {
echo 'Current branch: ' . $theBranch;
}
You may find this useful during development. I like having the branch name printed in the footer of my dev sites. Pass your repository's parent directory path to fetch the current branch name from the HEAD file.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.