No more undefined usage of rev{Start,End}Id warnings
[mediawiki.git] / includes / GitInfo.php
blobbc3f35e3d161952f6eb69701ada1acbd8130edc8
1 <?php
2 /**
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.
8 * @file
9 */
11 class GitInfo {
13 /**
14 * Singleton for the repo at $IP
16 protected static $repo = null;
18 /**
19 * Location of the .git directory
21 protected $basedir;
23 /**
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/";
30 /**
31 * Return a singleton for the repo at $IP
32 * @return GitInfo
34 public static function repo() {
35 global $IP;
36 if ( is_null( self::$repo ) ) {
37 self::$repo = new self( $IP );
39 return self::$repo;
42 /**
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 );
52 /**
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 ) ) {
60 return false;
63 $HEAD = file_get_contents( $HEADfile );
65 if ( preg_match( "/ref: (.*)/", $HEAD, $m ) ) {
66 return rtrim( $m[1] );
67 } else {
68 return $HEAD;
72 /**
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 ) ) {
81 return $HEAD;
84 // If not a SHA1 it may be a ref:
85 $REFfile = "{$this->basedir}{$HEAD}";
86 if ( !is_readable( $REFfile ) ) {
87 return false;
90 $sha1 = rtrim( file_get_contents( $REFfile ) );
92 return $sha1;
95 /**
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 ) ) {
102 return $m[1];
103 } else {
104 return $HEAD;
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();