mediawiki.toc: Clean up left overs
[mediawiki.git] / includes / GitInfo.php
blob304c1bce301732779957387b76087b7f62163caf
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 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
26 class GitInfo {
28 /**
29 * Singleton for the repo at $IP
31 protected static $repo = null;
33 /**
34 * Location of the .git directory
36 protected $basedir;
38 /**
39 * Path to JSON cache file for pre-computed git information.
41 protected $cacheFile;
43 /**
44 * Cached git information.
46 protected $cache = array();
48 /**
49 * Map of repo URLs to viewer URLs. Access via static method getViewers().
51 private static $viewers = false;
53 /**
54 * @param string $repoDir The root directory of the repo where .git can be found
55 * @param bool $usePrecomputed Use precomputed information if available
56 * @see precomputeValues
58 public function __construct( $repoDir, $usePrecomputed = true ) {
59 $this->cacheFile = self::getCacheFilePath( $repoDir );
60 if ( $usePrecomputed &&
61 $this->cacheFile !== null &&
62 is_readable( $this->cacheFile )
63 ) {
64 $this->cache = FormatJson::decode(
65 file_get_contents( $this->cacheFile ),
66 true
70 if ( !$this->cacheIsComplete() ) {
71 $this->basedir = $repoDir . DIRECTORY_SEPARATOR . '.git';
72 if ( is_readable( $this->basedir ) && !is_dir( $this->basedir ) ) {
73 $GITfile = file_get_contents( $this->basedir );
74 if ( strlen( $GITfile ) > 8 &&
75 substr( $GITfile, 0, 8 ) === 'gitdir: '
76 ) {
77 $path = rtrim( substr( $GITfile, 8 ), "\r\n" );
78 if ( $path[0] === '/' || substr( $path, 1, 1 ) === ':' ) {
79 // Path from GITfile is absolute
80 $this->basedir = $path;
81 } else {
82 $this->basedir = $repoDir . DIRECTORY_SEPARATOR . $path;
89 /**
90 * Compute the path to the cache file for a given directory.
92 * @param string $repoDir The root directory of the repo where .git can be found
93 * @return string Path to GitInfo cache file in $wgCacheDirectory or null if
94 * $wgCacheDirectory is false (cache disabled).
96 protected static function getCacheFilePath( $repoDir ) {
97 global $IP, $wgCacheDirectory;
98 if ( $wgCacheDirectory ) {
99 // Transform path to git repo to something we can safely embed in a filename
100 $repoName = $repoDir;
101 if ( strpos( $repoName, $IP ) === 0 ) {
102 // Strip $IP from path
103 $repoName = substr( $repoName, strlen( $IP ) );
105 $repoName = strtr( $repoName, DIRECTORY_SEPARATOR, '-' );
106 $fileName = 'info' . $repoName . '.json';
107 return implode(
108 DIRECTORY_SEPARATOR,
109 array( $wgCacheDirectory, 'gitinfo', $fileName )
112 return null;
116 * Get the singleton for the repo at $IP
118 * @return GitInfo
120 public static function repo() {
121 if ( is_null( self::$repo ) ) {
122 global $IP;
123 self::$repo = new self( $IP );
125 return self::$repo;
129 * Check if a string looks like a hex encoded SHA1 hash
131 * @param string $str The string to check
132 * @return bool Whether or not the string looks like a SHA1
134 public static function isSHA1( $str ) {
135 return !!preg_match( '/^[0-9A-F]{40}$/i', $str );
139 * Get the HEAD of the repo (without any opening "ref: ")
141 * @return string|bool The HEAD (git reference or SHA1) or false
143 public function getHead() {
144 if ( !isset( $this->cache['head'] ) ) {
145 $headFile = "{$this->basedir}/HEAD";
146 $head = false;
148 if ( is_readable( $headFile ) ) {
149 $head = file_get_contents( $headFile );
151 if ( preg_match( "/ref: (.*)/", $head, $m ) ) {
152 $head = rtrim( $m[1] );
153 } else {
154 $head = rtrim( $head );
157 $this->cache['head'] = $head;
159 return $this->cache['head'];
163 * Get the SHA1 for the current HEAD of the repo
165 * @return string|bool A SHA1 or false
167 public function getHeadSHA1() {
168 if ( !isset( $this->cache['headSHA1'] ) ) {
169 $head = $this->getHead();
170 $sha1 = false;
172 // If detached HEAD may be a SHA1
173 if ( self::isSHA1( $head ) ) {
174 $sha1 = $head;
175 } else {
176 // If not a SHA1 it may be a ref:
177 $refFile = "{$this->basedir}/{$head}";
178 if ( is_readable( $refFile ) ) {
179 $sha1 = rtrim( file_get_contents( $refFile ) );
182 $this->cache['headSHA1'] = $sha1;
184 return $this->cache['headSHA1'];
188 * Get the commit date of HEAD entry of the git code repository
190 * @since 1.22
191 * @return int|bool Commit date (UNIX timestamp) or false
193 public function getHeadCommitDate() {
194 global $wgGitBin;
196 if ( !isset( $this->cache['headCommitDate'] ) ) {
197 $date = false;
198 if ( is_file( $wgGitBin ) &&
199 is_executable( $wgGitBin ) &&
200 $this->getHead() !== false
202 $environment = array( "GIT_DIR" => $this->basedir );
203 $cmd = wfEscapeShellArg( $wgGitBin ) .
204 " show -s --format=format:%ct HEAD";
205 $retc = false;
206 $commitDate = wfShellExec( $cmd, $retc, $environment );
207 if ( $retc === 0 ) {
208 $date = (int)$commitDate;
211 $this->cache['headCommitDate'] = $date;
213 return $this->cache['headCommitDate'];
217 * Get the name of the current branch, or HEAD if not found
219 * @return string|bool The branch name, HEAD, or false
221 public function getCurrentBranch() {
222 if ( !isset( $this->cache['branch'] ) ) {
223 $branch = $this->getHead();
224 if ( $branch &&
225 preg_match( "#^refs/heads/(.*)$#", $branch, $m )
227 $branch = $m[1];
229 $this->cache['branch'] = $branch;
231 return $this->cache['branch'];
235 * Get an URL to a web viewer link to the HEAD revision.
237 * @return string|bool String if a URL is available or false otherwise
239 public function getHeadViewUrl() {
240 $url = $this->getRemoteUrl();
241 if ( $url === false ) {
242 return false;
244 if ( substr( $url, -4 ) !== '.git' ) {
245 $url .= '.git';
247 foreach ( self::getViewers() as $repo => $viewer ) {
248 $pattern = '#^' . $repo . '$#';
249 if ( preg_match( $pattern, $url, $matches ) ) {
250 $viewerUrl = preg_replace( $pattern, $viewer, $url );
251 $headSHA1 = $this->getHeadSHA1();
252 $replacements = array(
253 '%h' => substr( $headSHA1, 0, 7 ),
254 '%H' => $headSHA1,
255 '%r' => urlencode( $matches[1] ),
257 return strtr( $viewerUrl, $replacements );
260 return false;
264 * Get the URL of the remote origin.
265 * @return string|bool string if a URL is available or false otherwise.
267 protected function getRemoteUrl() {
268 if ( !isset( $this->cache['remoteURL'] ) ) {
269 $config = "{$this->basedir}/config";
270 $url = false;
271 if ( is_readable( $config ) ) {
272 wfSuppressWarnings();
273 $configArray = parse_ini_file( $config, true );
274 wfRestoreWarnings();
275 $remote = false;
277 // Use the "origin" remote repo if available or any other repo if not.
278 if ( isset( $configArray['remote origin'] ) ) {
279 $remote = $configArray['remote origin'];
280 } elseif ( is_array( $configArray ) ) {
281 foreach ( $configArray as $sectionName => $sectionConf ) {
282 if ( substr( $sectionName, 0, 6 ) == 'remote' ) {
283 $remote = $sectionConf;
288 if ( $remote !== false && isset( $remote['url'] ) ) {
289 $url = $remote['url'];
292 $this->cache['remoteURL'] = $url;
294 return $this->cache['remoteURL'];
298 * Check to see if the current cache is fully populated.
300 * Note: This method is public only to make unit testing easier. There's
301 * really no strong reason that anything other than a test should want to
302 * call this method.
304 * @return bool True if all expected cache keys exist, false otherwise
306 public function cacheIsComplete() {
307 return isset( $this->cache['head'] ) &&
308 isset( $this->cache['headSHA1'] ) &&
309 isset( $this->cache['headCommitDate'] ) &&
310 isset( $this->cache['branch'] ) &&
311 isset( $this->cache['remoteURL'] );
315 * Precompute and cache git information.
317 * Creates a JSON file in the cache directory associated with this
318 * GitInfo instance. This cache file will be used by subsequent GitInfo objects referencing
319 * the same directory to avoid needing to examine the .git directory again.
321 * @since 1.24
323 public function precomputeValues() {
324 if ( $this->cacheFile !== null ) {
325 // Try to completely populate the cache
326 $this->getHead();
327 $this->getHeadSHA1();
328 $this->getHeadCommitDate();
329 $this->getCurrentBranch();
330 $this->getRemoteUrl();
332 if ( !$this->cacheIsComplete() ) {
333 wfDebugLog( "Failed to compute GitInfo for \"{$this->basedir}\"" );
334 return;
337 $cacheDir = dirname( $this->cacheFile );
338 if ( !file_exists( $cacheDir ) &&
339 !wfMkdirParents( $cacheDir, null, __METHOD__ )
341 throw new MWException( "Unable to create GitInfo cache \"{$cacheDir}\"" );
344 file_put_contents( $this->cacheFile, FormatJson::encode( $this->cache ) );
349 * @see self::getHeadSHA1
350 * @return string
352 public static function headSHA1() {
353 return self::repo()->getHeadSHA1();
357 * @see self::getCurrentBranch
358 * @return string
360 public static function currentBranch() {
361 return self::repo()->getCurrentBranch();
365 * @see self::getHeadViewUrl()
366 * @return bool|string
368 public static function headViewUrl() {
369 return self::repo()->getHeadViewUrl();
373 * Gets the list of repository viewers
374 * @return array
376 protected static function getViewers() {
377 global $wgGitRepositoryViewers;
379 if ( self::$viewers === false ) {
380 self::$viewers = $wgGitRepositoryViewers;
381 wfRunHooks( 'GitViewers', array( &self::$viewers ) );
384 return self::$viewers;