3 * A class to help return information about a git repo MediaWiki may be inside
4 * This is used by Special:Version and is also useful for the LocalSettings.php
5 * of anyone working on large branches in git to setup config that show up only
6 * when specific branches are currently checked out.
14 * Singleton for the repo at $IP
16 protected static $repo = null;
19 * Location of the .git directory
24 * @param $dir The root directory of the repo where the .git dir can be found
26 public function __construct( $dir ) {
27 $this->basedir
= "{$dir}/.git/";
31 * Return a singleton for the repo at $IP
34 public static function repo() {
36 if ( is_null( self
::$repo ) ) {
37 self
::$repo = new self( $IP );
43 * Check if a string looks like a hex encoded SHA1 hash
45 * @param $str The string to check
46 * @return bool Whether or not the string looks like a SHA1
48 public static function isSHA1( $str ) {
49 return !!preg_match( '/^[0-9A-Z]{40}$/i', $str );
53 * Return the HEAD of the repo (without any opening "ref: ")
54 * @return string The HEAD
56 public function getHead() {
57 $HEADfile = "{$this->basedir}/HEAD";
59 if ( !is_readable( $HEADfile ) ) {
63 $HEAD = file_get_contents( $HEADfile );
65 if ( preg_match( "/ref: (.*)/", $HEAD, $m ) ) {
66 return rtrim( $m[1] );
73 * Return the SHA1 for the current HEAD of the repo
74 * @return string A SHA1 or false
76 public function getHeadSHA1() {
77 $HEAD = $this->getHead();
79 // If detached HEAD may be a SHA1
80 if ( self
::isSHA1( $HEAD ) ) {
84 // If not a SHA1 it may be a ref:
85 $REFfile = "{$this->basedir}{$HEAD}";
86 if ( !is_readable( $REFfile ) ) {
90 $sha1 = rtrim( file_get_contents( $REFfile ) );
96 * Return the name of the current branch, or HEAD if not found
97 * @return string The branch name, HEAD, or false
99 public function getCurrentBranch() {
100 $HEAD = $this->getHead();
101 if ( $HEAD && preg_match( "#^refs/heads/(.*)$#", $HEAD, $m ) ) {
109 * @see self::getHeadSHA1
111 public static function headSHA1() {
112 return self
::repo()->getHeadSHA1();
116 * @see self::getCurrentBranch
118 public static function currentBranch() {
119 return self
::repo()->getCurrentBranch();