Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the current Git 'version' in PHP

Tags:

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?

like image 547
lukeocodes Avatar asked May 02 '13 09:05

lukeocodes


People also ask

How do I find my current git version?

Check your version of Git You can check your current version of Git by running the git --version command in a terminal (Linux, macOS) or command prompt (Windows).

What is git version number?

GitVersion is a tool that generates a Semantic Version number based on your Git history. The version number generated from GitVersion can then be used for various different purposes, such as: Stamping a version number on artifacts (packages) produced during build.


2 Answers

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) 
like image 146
Jens A. Koch Avatar answered Oct 10 '22 21:10

Jens A. Koch


Gist: https://gist.github.com/lukeoliff/5501074

<?php  class QuickGit {    public static function version() {     exec('git describe --always',$version_mini_hash);     exec('git rev-list HEAD | wc -l',$version_number);     exec('git log -1',$line);     $version['short'] = "v1.".trim($version_number[0]).".".$version_mini_hash[0];     $version['full'] = "v1.".trim($version_number[0]).".$version_mini_hash[0] (".str_replace('commit ','',$line[0]).")";     return $version;   }  } 
like image 45
lukeocodes Avatar answered Oct 10 '22 22:10

lukeocodes