MediaWiki master
GitInfo.php
Go to the documentation of this file.
1<?php
6
7namespace MediaWiki\Utils;
8
9use MediaWiki\Config\ServiceOptions;
10use MediaWiki\HookContainer\HookRunner;
11use MediaWiki\Json\FormatJson;
12use MediaWiki\Logger\LoggerFactory;
13use MediaWiki\MainConfigNames;
14use MediaWiki\MediaWikiServices;
15use MediaWiki\Shell\Shell;
16use Psr\Log\LoggerInterface;
17use RuntimeException;
18
33class GitInfo {
34
36 protected static $repo = null;
37
39 protected $basedir;
40
42 protected $repoDir;
43
45 protected $cacheFile;
46
48 protected $cache = [];
49
53 private static $viewers = false;
54
56 private const CONSTRUCTOR_OPTIONS = [
61 ];
62
63 private LoggerInterface $logger;
64 private ServiceOptions $options;
65 private HookRunner $hookRunner;
66
73 public function __construct( $repoDir, $usePrecomputed = true ) {
74 $this->repoDir = $repoDir;
76 $this->options = new ServiceOptions(
77 self::CONSTRUCTOR_OPTIONS, $services->getMainConfig()
78 );
79 $this->options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
80 // $this->options must be set before using getCacheFilePath()
81 $this->cacheFile = $this->getCacheFilePath( $repoDir );
82 $this->logger = LoggerFactory::getInstance( 'gitinfo' );
83 $this->logger->debug(
84 "Candidate cacheFile={$this->cacheFile} for {$repoDir}"
85 );
86 $this->hookRunner = new HookRunner( $services->getHookContainer() );
87 if ( $usePrecomputed &&
88 $this->cacheFile !== null &&
89 is_readable( $this->cacheFile )
90 ) {
91 $this->cache = FormatJson::decode(
92 file_get_contents( $this->cacheFile ),
93 true
94 );
95 $this->logger->debug( "Loaded git data from cache for {$repoDir}" );
96 }
97
98 if ( !$this->cacheIsComplete() ) {
99 $this->logger->debug( "Cache incomplete for {$repoDir}" );
100 $this->basedir = $repoDir . DIRECTORY_SEPARATOR . '.git';
101 if ( is_readable( $this->basedir ) && !is_dir( $this->basedir ) ) {
102 $GITfile = file_get_contents( $this->basedir );
103 if ( strlen( $GITfile ) > 8 &&
104 substr( $GITfile, 0, 8 ) === 'gitdir: '
105 ) {
106 $path = rtrim( substr( $GITfile, 8 ), "\r\n" );
107 if ( $path[0] === '/' || substr( $path, 1, 1 ) === ':' ) {
108 // Path from GITfile is absolute
109 $this->basedir = $path;
110 } else {
111 $this->basedir = $repoDir . DIRECTORY_SEPARATOR . $path;
112 }
113 }
114 }
115 }
116 }
117
126 private function getCacheFilePath( $repoDir ) {
127 $gitInfoCacheDirectory = $this->options->get( MainConfigNames::GitInfoCacheDirectory );
128 if ( $gitInfoCacheDirectory === false ) {
129 $gitInfoCacheDirectory = $this->options->get( MainConfigNames::CacheDirectory ) . '/gitinfo';
130 }
131 if ( $gitInfoCacheDirectory ) {
132 // Convert both MW_INSTALL_PATH and $repoDir to canonical paths
133 $repoName = realpath( $repoDir );
134 if ( $repoName === false ) {
135 // Unit tests use fake path names
136 $repoName = $repoDir;
137 }
138 $realIP = realpath( MW_INSTALL_PATH );
139 if ( str_starts_with( $repoName, $realIP ) ) {
140 // Strip MW_INSTALL_PATH from path
141 $repoName = substr( $repoName, strlen( $realIP ) );
142 }
143 // Transform git repo path to something we can safely embed in a filename
144 // Windows supports both backslash and forward slash, ensure both are substituted.
145 $repoName = strtr( $repoName, [ '/' => '-' ] );
146 $repoName = strtr( $repoName, [ DIRECTORY_SEPARATOR => '-' ] );
147 $fileName = 'info' . $repoName . '.json';
148 $cachePath = "{$gitInfoCacheDirectory}/{$fileName}";
149 if ( is_readable( $cachePath ) ) {
150 return $cachePath;
151 }
152 }
153
154 return "$repoDir/gitinfo.json";
155 }
156
160 public static function repo(): self {
161 self::$repo ??= new self( MW_INSTALL_PATH );
162 return self::$repo;
163 }
164
171 public static function isSHA1( $str ) {
172 return (bool)preg_match( '/^[0-9A-F]{40}$/i', $str );
173 }
174
180 public function getHead() {
181 if ( !isset( $this->cache['head'] ) ) {
182 $headFile = "{$this->basedir}/HEAD";
183 $head = false;
184
185 if ( is_readable( $headFile ) ) {
186 $head = file_get_contents( $headFile );
187
188 if ( preg_match( "/ref: (.*)/", $head, $m ) ) {
189 $head = rtrim( $m[1] );
190 } else {
191 $head = rtrim( $head );
192 }
193 }
194 $this->cache['head'] = $head;
195 }
196 return $this->cache['head'];
197 }
198
204 public function getHeadSHA1() {
205 if ( !isset( $this->cache['headSHA1'] ) ) {
206 $head = $this->getHead();
207 $sha1 = false;
208
209 // If detached HEAD may be a SHA1
210 if ( self::isSHA1( $head ) ) {
211 $sha1 = $head;
212 } else {
213 // If not a SHA1 it may be a ref:
214 $refFile = "{$this->basedir}/{$head}";
215 $packedRefs = "{$this->basedir}/packed-refs";
216 $headRegex = preg_quote( $head, '/' );
217 if ( is_readable( $refFile ) ) {
218 $sha1 = rtrim( file_get_contents( $refFile ) );
219 } elseif ( is_readable( $packedRefs ) &&
220 preg_match( "/^([0-9A-Fa-f]{40}) $headRegex$/m", file_get_contents( $packedRefs ), $matches )
221 ) {
222 $sha1 = $matches[1];
223 }
224 }
225 $this->cache['headSHA1'] = $sha1;
226 }
227 return $this->cache['headSHA1'];
228 }
229
236 public function getHeadCommitDate() {
237 $gitBin = $this->options->get( MainConfigNames::GitBin );
238
239 if ( !isset( $this->cache['headCommitDate'] ) ) {
240 $date = false;
241
242 // Suppress warnings about any open_basedir restrictions affecting $wgGitBin (T74445).
243 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
244 $isFile = @is_file( $gitBin );
245 if ( $isFile &&
246 is_executable( $gitBin ) &&
248 $this->getHead() !== false
249 ) {
250 $cmd = [
251 $gitBin,
252 'show',
253 '-s',
254 '--format=format:%ct',
255 'HEAD',
256 ];
257 $gitDir = realpath( $this->basedir );
258 $result = Shell::command( $cmd )
259 ->environment( [ 'GIT_DIR' => $gitDir ] )
260 ->restrict( Shell::RESTRICT_DEFAULT | Shell::NO_NETWORK )
261 ->allowPath( $gitDir, $this->repoDir )
262 ->execute();
263
264 if ( $result->getExitCode() === 0 ) {
265 $date = (int)$result->getStdout();
266 }
267 }
268 $this->cache['headCommitDate'] = $date;
269 }
270 return $this->cache['headCommitDate'];
271 }
272
278 public function getCurrentBranch() {
279 if ( !isset( $this->cache['branch'] ) ) {
280 $branch = $this->getHead();
281 if ( $branch &&
282 preg_match( "#^refs/heads/(.*)$#", $branch, $m )
283 ) {
284 $branch = $m[1];
285 }
286 $this->cache['branch'] = $branch;
287 }
288 return $this->cache['branch'];
289 }
290
296 public function getHeadViewUrl() {
297 $url = $this->getRemoteUrl();
298 if ( $url === false ) {
299 return false;
300 }
301 foreach ( $this->getViewers() as $repo => $viewer ) {
302 $pattern = '#^' . $repo . '$#';
303 if ( preg_match( $pattern, $url, $matches ) ) {
304 $viewerUrl = preg_replace( $pattern, $viewer, $url );
305 $headSHA1 = $this->getHeadSHA1();
306 $replacements = [
307 '%h' => substr( $headSHA1, 0, 7 ),
308 '%H' => $headSHA1,
309 '%r' => urlencode( $matches[1] ),
310 '%R' => $matches[1],
311 ];
312 return strtr( $viewerUrl, $replacements );
313 }
314 }
315 return false;
316 }
317
322 protected function getRemoteUrl() {
323 if ( !isset( $this->cache['remoteURL'] ) ) {
324 $config = "{$this->basedir}/config";
325 $url = false;
326 if ( is_readable( $config ) ) {
327 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
328 $configArray = @parse_ini_file( $config, true );
329 $remote = false;
330
331 // Use the "origin" remote repo if available or any other repo if not.
332 if ( isset( $configArray['remote origin'] ) ) {
333 $remote = $configArray['remote origin'];
334 } elseif ( is_array( $configArray ) ) {
335 foreach ( $configArray as $sectionName => $sectionConf ) {
336 if ( str_starts_with( $sectionName, 'remote' ) ) {
337 $remote = $sectionConf;
338 }
339 }
340 }
341
342 if ( $remote !== false && isset( $remote['url'] ) ) {
343 $url = $remote['url'];
344 }
345 }
346 $this->cache['remoteURL'] = $url;
347 }
348 return $this->cache['remoteURL'];
349 }
350
360 public function cacheIsComplete() {
361 return isset( $this->cache['head'] ) &&
362 isset( $this->cache['headSHA1'] ) &&
363 isset( $this->cache['headCommitDate'] ) &&
364 isset( $this->cache['branch'] ) &&
365 isset( $this->cache['remoteURL'] );
366 }
367
377 public function precomputeValues() {
378 if ( $this->cacheFile !== null ) {
379 // Try to completely populate the cache
380 $this->getHead();
381 $this->getHeadSHA1();
382 $this->getHeadCommitDate();
383 $this->getCurrentBranch();
384 $this->getRemoteUrl();
385
386 if ( !$this->cacheIsComplete() ) {
387 $this->logger->debug(
388 "Failed to compute GitInfo for \"{$this->basedir}\""
389 );
390 return;
391 }
392
393 $cacheDir = dirname( $this->cacheFile );
394 if ( !file_exists( $cacheDir ) &&
395 !wfMkdirParents( $cacheDir, null, __METHOD__ )
396 ) {
397 throw new RuntimeException( "Unable to create GitInfo cache \"{$cacheDir}\"" );
398 }
399
400 file_put_contents( $this->cacheFile, FormatJson::encode( $this->cache ) );
401 }
402 }
403
408 public static function headSHA1() {
409 return self::repo()->getHeadSHA1();
410 }
411
416 public static function currentBranch() {
417 return self::repo()->getCurrentBranch();
418 }
419
424 public static function headViewUrl() {
425 return self::repo()->getHeadViewUrl();
426 }
427
432 private function getViewers() {
433 if ( self::$viewers === false ) {
434 self::$viewers = $this->options->get( MainConfigNames::GitRepositoryViewers );
435 $this->hookRunner->onGitViewers( self::$viewers );
436 }
437
438 return self::$viewers;
439 }
440}
441
443class_alias( GitInfo::class, 'GitInfo' );
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
A class for passing options to services.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
const CacheDirectory
Name constant for the CacheDirectory 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().
static getInstance()
Returns the global default instance of the top level service locator.
isDisabled()
Check whether a message does not exist, is an empty string, or is "-".
Definition Message.php:1210
Fetch status information from a local git repository.
Definition GitInfo.php:33
string null $basedir
Location of the .git directory.
Definition GitInfo.php:39
getHeadCommitDate()
Get the commit date of HEAD entry of the git code repository.
Definition GitInfo.php:236
string null $cacheFile
Path to JSON cache file for pre-computed git information.
Definition GitInfo.php:45
getHeadViewUrl()
Get an URL to a web viewer link to the HEAD revision.
Definition GitInfo.php:296
cacheIsComplete()
Check to see if the current cache is fully populated.
Definition GitInfo.php:360
static repo()
Get the singleton for the repo at MW_INSTALL_PATH.
Definition GitInfo.php:160
getHeadSHA1()
Get the SHA1 for the current HEAD of the repo.
Definition GitInfo.php:204
precomputeValues()
Precompute and cache git information.
Definition GitInfo.php:377
array $cache
Cached git information.
Definition GitInfo.php:48
getCurrentBranch()
Get the name of the current branch, or HEAD if not found.
Definition GitInfo.php:278
getRemoteUrl()
Get the URL of the remote origin.
Definition GitInfo.php:322
static isSHA1( $str)
Check if a string looks like a hex encoded SHA1 hash.
Definition GitInfo.php:171
static self null $repo
Singleton for the repo at $IP.
Definition GitInfo.php:36
__construct( $repoDir, $usePrecomputed=true)
Definition GitInfo.php:73
getHead()
Get the HEAD of the repo (without any opening "ref: ").
Definition GitInfo.php:180
string $repoDir
Location of the repository.
Definition GitInfo.php:42