Merge "http->https"
[lhc/web/wiklou.git] / includes / GitInfo.php
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.
7 *
8 * @file
9 */
10
11 class GitInfo {
12
13 /**
14 * Singleton for the repo at $IP
15 */
16 protected static $repo = null;
17
18 /**
19 * Location of the .git directory
20 */
21 protected $basedir;
22
23 /**
24 * @param $dir The root directory of the repo where the .git dir can be found
25 */
26 public function __construct( $dir ) {
27 $this->basedir = "{$dir}/.git/";
28 }
29
30 /**
31 * Return a singleton for the repo at $IP
32 * @return GitInfo
33 */
34 public static function repo() {
35 global $IP;
36 if ( is_null( self::$repo ) ) {
37 self::$repo = new self( $IP );
38 }
39 return self::$repo;
40 }
41
42 /**
43 * Check if a string looks like a hex encoded SHA1 hash
44 *
45 * @param $str The string to check
46 * @return bool Whether or not the string looks like a SHA1
47 */
48 public static function isSHA1( $str ) {
49 return !!preg_match( '/^[0-9A-Z]{40}$/i', $str );
50 }
51
52 /**
53 * Return the HEAD of the repo (without any opening "ref: ")
54 * @return string The HEAD
55 */
56 public function getHead() {
57 $HEADfile = "{$this->basedir}/HEAD";
58
59 if ( !is_readable( $HEADfile ) ) {
60 return false;
61 }
62
63 $HEAD = file_get_contents( $HEADfile );
64
65 if ( preg_match( "/ref: (.*)/", $HEAD, $m ) ) {
66 return rtrim( $m[1] );
67 } else {
68 return $HEAD;
69 }
70 }
71
72 /**
73 * Return the SHA1 for the current HEAD of the repo
74 * @return string A SHA1 or false
75 */
76 public function getHeadSHA1() {
77 $HEAD = $this->getHead();
78
79 // If detached HEAD may be a SHA1
80 if ( self::isSHA1( $HEAD ) ) {
81 return $HEAD;
82 }
83
84 // If not a SHA1 it may be a ref:
85 $REFfile = "{$this->basedir}{$HEAD}";
86 if ( !is_readable( $REFfile ) ) {
87 return false;
88 }
89
90 $sha1 = rtrim( file_get_contents( $REFfile ) );
91
92 return $sha1;
93 }
94
95 /**
96 * Return the name of the current branch, or HEAD if not found
97 * @return string The branch name, HEAD, or false
98 */
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;
105 }
106 }
107
108 /**
109 * @see self::getHeadSHA1
110 */
111 public static function headSHA1() {
112 return self::repo()->getHeadSHA1();
113 }
114
115 /**
116 * @see self::getCurrentBranch
117 */
118 public static function currentBranch() {
119 return self::repo()->getCurrentBranch();
120 }
121
122 }