MediaWiki 1.41.2
GitInfo.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Utils;
27
28use FormatJson;
35use Psr\Log\LoggerInterface;
36use RuntimeException;
37use Wikimedia\AtEase\AtEase;
38
44class GitInfo {
45
49 protected static $repo = null;
50
54 protected $basedir;
55
59 protected $repoDir;
60
64 protected $cacheFile;
65
69 protected $cache = [];
70
74 private static $viewers = false;
75
77 private const CONSTRUCTOR_OPTIONS = [
83 ];
84
86 private $logger;
87
89 private $options;
90
92 private $hookRunner;
93
100 public function __construct( $repoDir, $usePrecomputed = true ) {
101 $this->repoDir = $repoDir;
102 $services = MediaWikiServices::getInstance();
103 $this->options = new ServiceOptions(
104 self::CONSTRUCTOR_OPTIONS, $services->getMainConfig()
105 );
106 $this->options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
107 // $this->options must be set before using getCacheFilePath()
108 $this->cacheFile = $this->getCacheFilePath( $repoDir );
109 $this->logger = LoggerFactory::getInstance( 'gitinfo' );
110 $this->logger->debug(
111 "Candidate cacheFile={$this->cacheFile} for {$repoDir}"
112 );
113 $this->hookRunner = new HookRunner( $services->getHookContainer() );
114 if ( $usePrecomputed &&
115 $this->cacheFile !== null &&
116 is_readable( $this->cacheFile )
117 ) {
118 $this->cache = FormatJson::decode(
119 file_get_contents( $this->cacheFile ),
120 true
121 );
122 $this->logger->debug( "Loaded git data from cache for {$repoDir}" );
123 }
124
125 if ( !$this->cacheIsComplete() ) {
126 $this->logger->debug( "Cache incomplete for {$repoDir}" );
127 $this->basedir = $repoDir . DIRECTORY_SEPARATOR . '.git';
128 if ( is_readable( $this->basedir ) && !is_dir( $this->basedir ) ) {
129 $GITfile = file_get_contents( $this->basedir );
130 if ( strlen( $GITfile ) > 8 &&
131 substr( $GITfile, 0, 8 ) === 'gitdir: '
132 ) {
133 $path = rtrim( substr( $GITfile, 8 ), "\r\n" );
134 if ( $path[0] === '/' || substr( $path, 1, 1 ) === ':' ) {
135 // Path from GITfile is absolute
136 $this->basedir = $path;
137 } else {
138 $this->basedir = $repoDir . DIRECTORY_SEPARATOR . $path;
139 }
140 }
141 }
142 }
143 }
144
153 private function getCacheFilePath( $repoDir ) {
154 $gitInfoCacheDirectory = $this->options->get( MainConfigNames::GitInfoCacheDirectory );
155 if ( $gitInfoCacheDirectory === false ) {
156 $gitInfoCacheDirectory = $this->options->get( MainConfigNames::CacheDirectory ) . '/gitinfo';
157 }
158 $baseDir = $this->options->get( MainConfigNames::BaseDirectory );
159 if ( $gitInfoCacheDirectory ) {
160 // Convert both $IP and $repoDir to canonical paths to protect against
161 // $IP having changed between the settings files and runtime.
162 $realIP = realpath( $baseDir );
163 $repoName = realpath( $repoDir );
164 if ( $repoName === false ) {
165 // Unit tests use fake path names
166 $repoName = $repoDir;
167 }
168 if ( strpos( $repoName, $realIP ) === 0 ) {
169 // Strip $IP from path
170 $repoName = substr( $repoName, strlen( $realIP ) );
171 }
172 // Transform path to git repo to something we can safely embed in
173 // a filename
174 $repoName = strtr( $repoName, DIRECTORY_SEPARATOR, '-' );
175 $fileName = 'info' . $repoName . '.json';
176 $cachePath = "{$gitInfoCacheDirectory}/{$fileName}";
177 if ( is_readable( $cachePath ) ) {
178 return $cachePath;
179 }
180 }
181
182 return "$repoDir/gitinfo.json";
183 }
184
190 public static function repo() {
191 if ( self::$repo === null ) {
192 self::$repo = new self( MW_INSTALL_PATH );
193 }
194 return self::$repo;
195 }
196
203 public static function isSHA1( $str ) {
204 return (bool)preg_match( '/^[0-9A-F]{40}$/i', $str );
205 }
206
212 public function getHead() {
213 if ( !isset( $this->cache['head'] ) ) {
214 $headFile = "{$this->basedir}/HEAD";
215 $head = false;
216
217 if ( is_readable( $headFile ) ) {
218 $head = file_get_contents( $headFile );
219
220 if ( preg_match( "/ref: (.*)/", $head, $m ) ) {
221 $head = rtrim( $m[1] );
222 } else {
223 $head = rtrim( $head );
224 }
225 }
226 $this->cache['head'] = $head;
227 }
228 return $this->cache['head'];
229 }
230
236 public function getHeadSHA1() {
237 if ( !isset( $this->cache['headSHA1'] ) ) {
238 $head = $this->getHead();
239 $sha1 = false;
240
241 // If detached HEAD may be a SHA1
242 if ( self::isSHA1( $head ) ) {
243 $sha1 = $head;
244 } else {
245 // If not a SHA1 it may be a ref:
246 $refFile = "{$this->basedir}/{$head}";
247 $packedRefs = "{$this->basedir}/packed-refs";
248 $headRegex = preg_quote( $head, '/' );
249 if ( is_readable( $refFile ) ) {
250 $sha1 = rtrim( file_get_contents( $refFile ) );
251 } elseif ( is_readable( $packedRefs ) &&
252 preg_match( "/^([0-9A-Fa-f]{40}) $headRegex$/m", file_get_contents( $packedRefs ), $matches )
253 ) {
254 $sha1 = $matches[1];
255 }
256 }
257 $this->cache['headSHA1'] = $sha1;
258 }
259 return $this->cache['headSHA1'];
260 }
261
268 public function getHeadCommitDate() {
269 $gitBin = $this->options->get( MainConfigNames::GitBin );
270
271 if ( !isset( $this->cache['headCommitDate'] ) ) {
272 $date = false;
273
274 // Suppress warnings about any open_basedir restrictions affecting $wgGitBin (T74445).
275 $isFile = AtEase::quietCall( 'is_file', $gitBin );
276 if ( $isFile &&
277 is_executable( $gitBin ) &&
278 !Shell::isDisabled() &&
279 $this->getHead() !== false
280 ) {
281 $cmd = [
282 $gitBin,
283 'show',
284 '-s',
285 '--format=format:%ct',
286 'HEAD',
287 ];
288 $gitDir = realpath( $this->basedir );
289 $result = Shell::command( $cmd )
290 ->environment( [ 'GIT_DIR' => $gitDir ] )
291 ->restrict( Shell::RESTRICT_DEFAULT | Shell::NO_NETWORK )
292 ->allowPath( $gitDir, $this->repoDir )
293 ->execute();
294
295 if ( $result->getExitCode() === 0 ) {
296 $date = (int)$result->getStdout();
297 }
298 }
299 $this->cache['headCommitDate'] = $date;
300 }
301 return $this->cache['headCommitDate'];
302 }
303
309 public function getCurrentBranch() {
310 if ( !isset( $this->cache['branch'] ) ) {
311 $branch = $this->getHead();
312 if ( $branch &&
313 preg_match( "#^refs/heads/(.*)$#", $branch, $m )
314 ) {
315 $branch = $m[1];
316 }
317 $this->cache['branch'] = $branch;
318 }
319 return $this->cache['branch'];
320 }
321
327 public function getHeadViewUrl() {
328 $url = $this->getRemoteUrl();
329 if ( $url === false ) {
330 return false;
331 }
332 foreach ( $this->getViewers() as $repo => $viewer ) {
333 $pattern = '#^' . $repo . '$#';
334 if ( preg_match( $pattern, $url, $matches ) ) {
335 $viewerUrl = preg_replace( $pattern, $viewer, $url );
336 $headSHA1 = $this->getHeadSHA1();
337 $replacements = [
338 '%h' => substr( $headSHA1, 0, 7 ),
339 '%H' => $headSHA1,
340 '%r' => urlencode( $matches[1] ),
341 '%R' => $matches[1],
342 ];
343 return strtr( $viewerUrl, $replacements );
344 }
345 }
346 return false;
347 }
348
353 protected function getRemoteUrl() {
354 if ( !isset( $this->cache['remoteURL'] ) ) {
355 $config = "{$this->basedir}/config";
356 $url = false;
357 if ( is_readable( $config ) ) {
358 AtEase::suppressWarnings();
359 $configArray = parse_ini_file( $config, true );
360 AtEase::restoreWarnings();
361 $remote = false;
362
363 // Use the "origin" remote repo if available or any other repo if not.
364 if ( isset( $configArray['remote origin'] ) ) {
365 $remote = $configArray['remote origin'];
366 } elseif ( is_array( $configArray ) ) {
367 foreach ( $configArray as $sectionName => $sectionConf ) {
368 if ( substr( $sectionName, 0, 6 ) == 'remote' ) {
369 $remote = $sectionConf;
370 }
371 }
372 }
373
374 if ( $remote !== false && isset( $remote['url'] ) ) {
375 $url = $remote['url'];
376 }
377 }
378 $this->cache['remoteURL'] = $url;
379 }
380 return $this->cache['remoteURL'];
381 }
382
392 public function cacheIsComplete() {
393 return isset( $this->cache['head'] ) &&
394 isset( $this->cache['headSHA1'] ) &&
395 isset( $this->cache['headCommitDate'] ) &&
396 isset( $this->cache['branch'] ) &&
397 isset( $this->cache['remoteURL'] );
398 }
399
409 public function precomputeValues() {
410 if ( $this->cacheFile !== null ) {
411 // Try to completely populate the cache
412 $this->getHead();
413 $this->getHeadSHA1();
414 $this->getHeadCommitDate();
415 $this->getCurrentBranch();
416 $this->getRemoteUrl();
417
418 if ( !$this->cacheIsComplete() ) {
419 $this->logger->debug(
420 "Failed to compute GitInfo for \"{$this->basedir}\""
421 );
422 return;
423 }
424
425 $cacheDir = dirname( $this->cacheFile );
426 if ( !file_exists( $cacheDir ) &&
427 !wfMkdirParents( $cacheDir, null, __METHOD__ )
428 ) {
429 throw new RuntimeException( "Unable to create GitInfo cache \"{$cacheDir}\"" );
430 }
431
432 file_put_contents( $this->cacheFile, FormatJson::encode( $this->cache ) );
433 }
434 }
435
440 public static function headSHA1() {
441 return self::repo()->getHeadSHA1();
442 }
443
448 public static function currentBranch() {
449 return self::repo()->getCurrentBranch();
450 }
451
456 public static function headViewUrl() {
457 return self::repo()->getHeadViewUrl();
458 }
459
464 private function getViewers() {
465 if ( self::$viewers === false ) {
466 self::$viewers = $this->options->get( MainConfigNames::GitRepositoryViewers );
467 $this->hookRunner->onGitViewers( self::$viewers );
468 }
469
470 return self::$viewers;
471 }
472}
473
477class_alias( GitInfo::class, 'GitInfo' );
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
JSON formatter wrapper class.
A class for passing options to services.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
const CacheDirectory
Name constant for the CacheDirectory setting, for use with Config::get()
const BaseDirectory
Name constant for the BaseDirectory setting, for use with Config::get()
const GitRepositoryViewers
Name constant for the GitRepositoryViewers setting, for use with Config::get()
const GitBin
Name constant for the GitBin setting, for use with Config::get()
const GitInfoCacheDirectory
Name constant for the GitInfoCacheDirectory setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Executes shell commands.
Definition Shell.php:46
getHeadCommitDate()
Get the commit date of HEAD entry of the git code repository.
Definition GitInfo.php:268
getHeadViewUrl()
Get an URL to a web viewer link to the HEAD revision.
Definition GitInfo.php:327
static $repo
Singleton for the repo at $IP.
Definition GitInfo.php:49
$basedir
Location of the .git directory.
Definition GitInfo.php:54
$cache
Cached git information.
Definition GitInfo.php:69
cacheIsComplete()
Check to see if the current cache is fully populated.
Definition GitInfo.php:392
static repo()
Get the singleton for the repo at MW_INSTALL_PATH.
Definition GitInfo.php:190
getHeadSHA1()
Get the SHA1 for the current HEAD of the repo.
Definition GitInfo.php:236
precomputeValues()
Precompute and cache git information.
Definition GitInfo.php:409
getCurrentBranch()
Get the name of the current branch, or HEAD if not found.
Definition GitInfo.php:309
getRemoteUrl()
Get the URL of the remote origin.
Definition GitInfo.php:353
static isSHA1( $str)
Check if a string looks like a hex encoded SHA1 hash.
Definition GitInfo.php:203
$repoDir
Location of the repository.
Definition GitInfo.php:59
$cacheFile
Path to JSON cache file for pre-computed git information.
Definition GitInfo.php:64
__construct( $repoDir, $usePrecomputed=true)
Definition GitInfo.php:100
getHead()
Get the HEAD of the repo (without any opening "ref: ")
Definition GitInfo.php:212