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

git current branch
git output current branch name
git show what branch i'm on
git bash current branch
find the current git branch
git describe current branch
how to check branch name
git which branch am i on

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.

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'.

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.

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

/**
 * @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

php, This worked for me in PHP, including it in the top of my site: the string $​branchname = $explodedstring[2]; //get the one that is always "</span></div>"; //show it on the page self::DEVELOP; } /** * @return string */ private function getFlowType() { $name = explode('/', $this->branch); return $name[0]; } }. 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.

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

git-show-branch Documentation, git show-branch [-a|--all] [-r|--remotes] [--topo-order | --date-order] [--current] [--​color[=<when>] A glob pattern that matches branch or tag names under refs/. Hi All. How do I do it like above ? Dont mind the emoji, I know its representing the user's machine name. It shows only the repository name, (not including its path if it were to go into a subfolder), git:(current branch), and some x.

git-branch Documentation, git branch [--track | --no-track] [-f] <branchname> [<start-point>] git branch If the <commit> argument is missing it defaults to HEAD (i.e. the tip of the current branch). When in list mode, show sha1 and commit subject line for each head, along git.git my.git $ cd my.git $ git branch -d -r origin/todo origin/html origin/​man (1)  The name of the branch to create or delete. The new branch name must pass all checks defined by git-check-ref-format[1]. Some of these checks may restrict the characters allowed in a branch name. <start-point> The new branch head will point to this commit. It may be given as a branch name, a commit-id, or a tag.

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

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

Terminal Cheat Sheet · GitHub, git branch [--set-upstream | --track | --no-track] [-l] [-f] <branchname> argument is missing it defaults to HEAD (i.e. the tip of the current branch). When in list mode, show sha1 and commit subject line for each head, along with git.git my.​git $ cd my.git $ git branch -d -r origin/todo origin/html origin/man (1) About this site Similar behavior could be achieved with git log branchA..branchB, e.g to see outgoing commits: git log origin/master..feature-branch. One day I used that command for the branch with really long name. I just typed a few fisrt letters, pressed tab and branch name was auto-completed (I personally prefer fish shell, but it should also work for all

To extend on program247365's answer, I've written a helper class for this, which also useful for those using 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();

git branch - Creating, deleting and showing branches, git push origin :<branchname> # deletes remote branch. git subtree push --prefix docs origin gh-pages # push docs as subtree to gh-pages git merge upstream/​development # Merge original with fork. git diff of the tip of the current branch git show master~3 # show great grand parent to tip of master (you get the idea). $ git branch --merged feature/login feature/newsletter $ git branch -d feature/login feature/newsletter. To create a new branch, simply specify a name - and possibly a starting point, in case you don't want it to start at your current HEAD branch's state: $ git branch feature/logout b84f02e

Development with Git, Our learn section helps you get started with various web and software skills. Listing your branches, by default, will only show your local branches' names. Returns all branches that have not been merged into your current HEAD branch. git branch -a -v * master 609d1ee New icons for “teams” page feature/login  This is the command to use if you want to permanently throw away all of the commits associated with a particular line of development. git branch -m <branch> Rename the current branch to <branch>. git branch -a. List all remote branches. Creating Branches. It's important to understand that branches are just pointers to commits. When you create a

Git for beginners: 12 commands you need to know, My Work. Notifications 0; Tasks If you have notes/hints/tips on DSpace development with Git/GitHub, please feel free on using Git: https://wiki.​duraspace.org/display/~cwilper/How+I+Use+Git git pull is the command that brings your current local branch up-to-date with and click the "Fork" button at the top of the page. The git_branch() is a function, that prints the name of the current Git branch in the round brackets. We set the PS1 variable and place the function git_branch() inside it to display the Git branch in the terminal prompt. The function inside the PS1 variable must be in the following format: \$(git_branch).

Manage branches in your Git repo, It shows you everything you need to know about your current branch. those changes to my staging index). 3. git diff. This will show you all the If you made a typo in your branch name, or otherwise just want to git pull , so you can develop on the most current version of master. Framer for Web is Here! I’m from a Subversion background and, when I had a branch, I knew what I was working on with “These working files point to this branch”. But with Git I’m not sure when I am editing a file in NetBeans or Notepad++, whether it’s tied to the master or another branch.

Comments
  • There is a related answer stackoverflow.com/questions/1593051/…
  • @Ruslan Kabalin - Yup! That confirms my solution below, which is to look at the HEAD file in the .git/ directory that always contains the current branch.
  • This doesn't quite work if the branch name includes a "/": most git flow features do. You're going to have to slice the array and then implode it again: $explodedstring = array_slice( $explodedstring , 2 ); $branchname = implode( "/", $explodedstring );
  • As onliner <?php echo implode('/', array_slice(explode('/', file_get_contents('.git/HEAD')), 2)); ?>
  • It breaks a lot of environments, where bug/foo or feature/bar is a convention, like Git Flow. The workaround is to limit the explode to 3 items or to manually take what comes after ref: refs/heads/ ...
  • If we're going to be kludgy, $gitCurrentBranch = trim(substr(file_get_contents('.git/HEAD'), 16)); as long as .git/HEAD keeps its current format.
  • I would suggest to make $branchname = trim($explodedstring[2]); the string may contain a newline code at the end
  • This works as long as the configuration on your local machine will allow you to execute git. I personally ran into problems with that and switched to program247365's answer to solve it.
  • This is pretty nice, but the branch names should not be assumed by the fixed constants. Some people use different branch names, and it would be better to be able to pass them into the constructor or use a static config method so the code doesn't need to be rewritten on a per-project or per-repo-structure basis.
  • @mopsyd true, but then they would be not be implementing the Git Flow standard. The code here assumes a strict implementation. Perhaps interfaces for these methods would solve the problem of those using their own conventions.
  • The git flow standard does not fit everyone's use case. I prefer it, but there are a number of projects where it is not appropriate, such as those being ported over from a single branch SVN repo. It is not appropriate to enforce opinion about other peoples code, unless they have some tight coupling between each other, which is usually undesirable except in very specific cases.
  • Seems like you must pass in a branch name before you have access to things for glip. Doesn't seem like it will work for what I want, since it has no way of displaying branches, it just expects you to access them directly knowing them by name. That being said I found that in any .git/ repo dir, there is a file called 'HEAD', that has the current branch name in it. I'll probably ending up parsing that directly and will post my answer here when finished.
  • I suppose git br is your alias for git branch?