program247365 program247365 - 2 months ago 15
PHP Question

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

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