Display the current Git 'version' in PHP
git, github, php, versioning
Solution
Firstly, some `git` commands to fetch version information:
- commit hash long
- `git log --pretty="%H" -n1 HEAD`
- commit hash short
- `git log --pretty="%h" -n1 HEAD`
- commit date
- `git log --pretty="%ci" -n1 HEAD`
- tag
- `git describe --tags --abbrev=0`
- tag long with hash
- `git describe --tags`
Secondly, use `exec()` combined with the git commands of your choice from above to build the version identifier:
class ApplicationVersion
{
const MAJOR = 1;
const MINOR = 2;
const PATCH = 3;
public static function get()
{
$commitHash = trim(exec('git log --pretty="%h" -n1 HEAD'));
$commitDate = new \DateTime(trim(exec('git log -n1 --pretty=%ci HEAD')));
$commitDate->setTimezone(new \DateTimeZone('UTC'));
return sprintf('v%s.%s.%s-dev.%s (%s)', self::MAJOR, self::MINOR, self::PATCH, $commitHash, $commitDate->format('Y-m-d H:i:s'));
}
}
// Usage: echo 'MyApplication ' . ApplicationVersion::get();
// MyApplication v1.2.3-dev.b576fd7 (2016-11-02 14:11:22)
Please note that on a production system, PHP's `exec` is often in the list of `disabled_functions`, and `git` may not be available. The code from above might then become part of your build scripts. This enables you to versionize the application during the build stage (e.g., on a development container with `git` and PHP's `exec`) and deploy it with static version strings to production.
Problem
I want to display the Git version on my site. How can I display a semantic version number from Git, that non-technical users of a site can easily reference when raising issues?