Display the current Git 'version' in PHP

前端 未结 6 700
醉话见心
醉话见心 2021-01-30 11:37

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

6条回答
  •  [愿得一人]
    2021-01-30 12:07

    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)
    

提交回复
热议问题