How to display the git version on your site

Here is a quick guide on how to automatically update the build version of your site directly from git.
This approach leverages the “hook” functionality to get the build hash after a commit.

Versioning files is a must for any developer and git version control system is one of the de facto choices for that job. It’s my personal favorite as well. You can learn more about git here.

Go into your projects .git folder, then hooks. You should see a list of sample hooks already there.
Create a new one called “post-commit” (note there is no file extension).

Add the following content:

#!/bin/sh
#
# Get the Git Revision and write make available to the application
# This will write the short commit hash to the version-commit.php file.
#
version=$(git rev-parse --short HEAD)
echo "" > version-commit.php

Once you “include” the version-commit.php file the VERSION_COMMIT constant will now be available to display anywhere in your site. For example:

require_once(version-commit.php);
$versionMajor = '1.0';
$version = $versionMajor.'.'.VERSION_COMMIT;
echo $version;

Now you are probably thinking that this would cause the project to show new changes because of version-commit.php file change.

For that we need to update “.gitignore” file in the project root folder:

# Don't version the version file
version-commit.php

One thing to note is that the version-commit.php file will not exist for a cloned (checked out) repository until a new change is committed, since that file is not committed with the code to avoid an endless loop of change/commit cycle.

I am yet to find a clean and simple way around that but this problem is a small price to pay for some useful automation.

Leave a Reply

Your email address will not be published. Required fields are marked *