ParsoidParser: Record ParserOptions watcher on ParserOutput object
[mediawiki.git] / includes / GitInfo.php
blob06c8531d488598e9167b35f2a98305e655014d33
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 use MediaWiki\Config\ServiceOptions;
27 use MediaWiki\HookContainer\HookRunner;
28 use MediaWiki\Logger\LoggerFactory;
29 use MediaWiki\MainConfigNames;
30 use MediaWiki\MediaWikiServices;
31 use MediaWiki\Shell\Shell;
32 use Psr\Log\LoggerInterface;
33 use Wikimedia\AtEase\AtEase;
35 /**
36 * @newable
37 * @note marked as newable in 1.35 for lack of a better alternative,
38 * but should become a stateless service eventually.
40 class GitInfo {
42 /**
43 * Singleton for the repo at $IP
45 protected static $repo = null;
47 /**
48 * Location of the .git directory
50 protected $basedir;
52 /**
53 * Location of the repository
55 protected $repoDir;
57 /**
58 * Path to JSON cache file for pre-computed git information.
60 protected $cacheFile;
62 /**
63 * Cached git information.
65 protected $cache = [];
67 /**
68 * @var array|false Map of repo URLs to viewer URLs. Access via method getViewers().
70 private static $viewers = false;
72 /** Configuration options needed */
73 private const CONSTRUCTOR_OPTIONS = [
74 MainConfigNames::BaseDirectory,
75 MainConfigNames::CacheDirectory,
76 MainConfigNames::GitBin,
77 MainConfigNames::GitInfoCacheDirectory,
78 MainConfigNames::GitRepositoryViewers,
81 /** @var LoggerInterface */
82 private $logger;
84 /** @var ServiceOptions */
85 private $options;
87 /** @var HookRunner */
88 private $hookRunner;
90 /**
91 * @stable to call
92 * @param string $repoDir The root directory of the repo where .git can be found
93 * @param bool $usePrecomputed Use precomputed information if available
94 * @see precomputeValues
96 public function __construct( $repoDir, $usePrecomputed = true ) {
97 $this->repoDir = $repoDir;
98 $services = MediaWikiServices::getInstance();
99 $this->options = new ServiceOptions(
100 self::CONSTRUCTOR_OPTIONS,
101 $services->getMainConfig()
103 $this->options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
104 // $this->options must be set before using getCacheFilePath()
105 $this->cacheFile = $this->getCacheFilePath( $repoDir );
106 $this->logger = LoggerFactory::getInstance( 'gitinfo' );
107 $this->logger->debug(
108 "Candidate cacheFile={$this->cacheFile} for {$repoDir}"
110 $this->hookRunner = new HookRunner( $services->getHookContainer() );
111 if ( $usePrecomputed &&
112 $this->cacheFile !== null &&
113 is_readable( $this->cacheFile )
115 $this->cache = FormatJson::decode(
116 file_get_contents( $this->cacheFile ),
117 true
119 $this->logger->debug( "Loaded git data from cache for {$repoDir}" );
122 if ( !$this->cacheIsComplete() ) {
123 $this->logger->debug( "Cache incomplete for {$repoDir}" );
124 $this->basedir = $repoDir . DIRECTORY_SEPARATOR . '.git';
125 if ( is_readable( $this->basedir ) && !is_dir( $this->basedir ) ) {
126 $GITfile = file_get_contents( $this->basedir );
127 if ( strlen( $GITfile ) > 8 &&
128 substr( $GITfile, 0, 8 ) === 'gitdir: '
130 $path = rtrim( substr( $GITfile, 8 ), "\r\n" );
131 if ( $path[0] === '/' || substr( $path, 1, 1 ) === ':' ) {
132 // Path from GITfile is absolute
133 $this->basedir = $path;
134 } else {
135 $this->basedir = $repoDir . DIRECTORY_SEPARATOR . $path;
143 * Compute the path to the cache file for a given directory.
145 * @param string $repoDir The root directory of the repo where .git can be found
146 * @return string Path to GitInfo cache file in $wgGitInfoCacheDirectory or
147 * fallback in the extension directory itself
148 * @since 1.24
150 private function getCacheFilePath( $repoDir ) {
151 $gitInfoCacheDirectory = $this->options->get( MainConfigNames::GitInfoCacheDirectory );
152 if ( $gitInfoCacheDirectory === false ) {
153 $gitInfoCacheDirectory = $this->options->get( MainConfigNames::CacheDirectory ) . '/gitinfo';
155 $baseDir = $this->options->get( MainConfigNames::BaseDirectory );
156 if ( $gitInfoCacheDirectory ) {
157 // Convert both $IP and $repoDir to canonical paths to protect against
158 // $IP having changed between the settings files and runtime.
159 $realIP = realpath( $baseDir );
160 $repoName = realpath( $repoDir );
161 if ( $repoName === false ) {
162 // Unit tests use fake path names
163 $repoName = $repoDir;
165 if ( strpos( $repoName, $realIP ) === 0 ) {
166 // Strip $IP from path
167 $repoName = substr( $repoName, strlen( $realIP ) );
169 // Transform path to git repo to something we can safely embed in
170 // a filename
171 $repoName = strtr( $repoName, DIRECTORY_SEPARATOR, '-' );
172 $fileName = 'info' . $repoName . '.json';
173 $cachePath = "{$gitInfoCacheDirectory}/{$fileName}";
174 if ( is_readable( $cachePath ) ) {
175 return $cachePath;
179 return "$repoDir/gitinfo.json";
183 * Get the singleton for the repo at MW_INSTALL_PATH
185 * @return GitInfo
187 public static function repo() {
188 if ( self::$repo === null ) {
189 self::$repo = new self( MW_INSTALL_PATH );
191 return self::$repo;
195 * Check if a string looks like a hex encoded SHA1 hash
197 * @param string $str The string to check
198 * @return bool Whether or not the string looks like a SHA1
200 public static function isSHA1( $str ) {
201 return (bool)preg_match( '/^[0-9A-F]{40}$/i', $str );
205 * Get the HEAD of the repo (without any opening "ref: ")
207 * @return string|false The HEAD (git reference or SHA1) or false
209 public function getHead() {
210 if ( !isset( $this->cache['head'] ) ) {
211 $headFile = "{$this->basedir}/HEAD";
212 $head = false;
214 if ( is_readable( $headFile ) ) {
215 $head = file_get_contents( $headFile );
217 if ( preg_match( "/ref: (.*)/", $head, $m ) ) {
218 $head = rtrim( $m[1] );
219 } else {
220 $head = rtrim( $head );
223 $this->cache['head'] = $head;
225 return $this->cache['head'];
229 * Get the SHA1 for the current HEAD of the repo
231 * @return string|false A SHA1 or false
233 public function getHeadSHA1() {
234 if ( !isset( $this->cache['headSHA1'] ) ) {
235 $head = $this->getHead();
236 $sha1 = false;
238 // If detached HEAD may be a SHA1
239 if ( self::isSHA1( $head ) ) {
240 $sha1 = $head;
241 } else {
242 // If not a SHA1 it may be a ref:
243 $refFile = "{$this->basedir}/{$head}";
244 $packedRefs = "{$this->basedir}/packed-refs";
245 $headRegex = preg_quote( $head, '/' );
246 if ( is_readable( $refFile ) ) {
247 $sha1 = rtrim( file_get_contents( $refFile ) );
248 } elseif ( is_readable( $packedRefs ) &&
249 preg_match( "/^([0-9A-Fa-f]{40}) $headRegex$/m", file_get_contents( $packedRefs ), $matches )
251 $sha1 = $matches[1];
254 $this->cache['headSHA1'] = $sha1;
256 return $this->cache['headSHA1'];
260 * Get the commit date of HEAD entry of the git code repository
262 * @since 1.22
263 * @return int|false Commit date (UNIX timestamp) or false
265 public function getHeadCommitDate() {
266 $gitBin = $this->options->get( MainConfigNames::GitBin );
268 if ( !isset( $this->cache['headCommitDate'] ) ) {
269 $date = false;
271 // Suppress warnings about any open_basedir restrictions affecting $wgGitBin (T74445).
272 $isFile = AtEase::quietCall( 'is_file', $gitBin );
273 if ( $isFile &&
274 is_executable( $gitBin ) &&
275 !Shell::isDisabled() &&
276 $this->getHead() !== false
278 $cmd = [
279 $gitBin,
280 'show',
281 '-s',
282 '--format=format:%ct',
283 'HEAD',
285 $gitDir = realpath( $this->basedir );
286 $result = Shell::command( $cmd )
287 ->environment( [ 'GIT_DIR' => $gitDir ] )
288 ->restrict( Shell::RESTRICT_DEFAULT | Shell::NO_NETWORK )
289 ->allowPath( $gitDir, $this->repoDir )
290 ->execute();
292 if ( $result->getExitCode() === 0 ) {
293 $date = (int)$result->getStdout();
296 $this->cache['headCommitDate'] = $date;
298 return $this->cache['headCommitDate'];
302 * Get the name of the current branch, or HEAD if not found
304 * @return string|false The branch name, HEAD, or false
306 public function getCurrentBranch() {
307 if ( !isset( $this->cache['branch'] ) ) {
308 $branch = $this->getHead();
309 if ( $branch &&
310 preg_match( "#^refs/heads/(.*)$#", $branch, $m )
312 $branch = $m[1];
314 $this->cache['branch'] = $branch;
316 return $this->cache['branch'];
320 * Get an URL to a web viewer link to the HEAD revision.
322 * @return string|false String if a URL is available or false otherwise
324 public function getHeadViewUrl() {
325 $url = $this->getRemoteUrl();
326 if ( $url === false ) {
327 return false;
329 foreach ( $this->getViewers() as $repo => $viewer ) {
330 $pattern = '#^' . $repo . '$#';
331 if ( preg_match( $pattern, $url, $matches ) ) {
332 $viewerUrl = preg_replace( $pattern, $viewer, $url );
333 $headSHA1 = $this->getHeadSHA1();
334 $replacements = [
335 '%h' => substr( $headSHA1, 0, 7 ),
336 '%H' => $headSHA1,
337 '%r' => urlencode( $matches[1] ),
338 '%R' => $matches[1],
340 return strtr( $viewerUrl, $replacements );
343 return false;
347 * Get the URL of the remote origin.
348 * @return string|false String if a URL is available or false otherwise.
350 protected function getRemoteUrl() {
351 if ( !isset( $this->cache['remoteURL'] ) ) {
352 $config = "{$this->basedir}/config";
353 $url = false;
354 if ( is_readable( $config ) ) {
355 AtEase::suppressWarnings();
356 $configArray = parse_ini_file( $config, true );
357 AtEase::restoreWarnings();
358 $remote = false;
360 // Use the "origin" remote repo if available or any other repo if not.
361 if ( isset( $configArray['remote origin'] ) ) {
362 $remote = $configArray['remote origin'];
363 } elseif ( is_array( $configArray ) ) {
364 foreach ( $configArray as $sectionName => $sectionConf ) {
365 if ( substr( $sectionName, 0, 6 ) == 'remote' ) {
366 $remote = $sectionConf;
371 if ( $remote !== false && isset( $remote['url'] ) ) {
372 $url = $remote['url'];
375 $this->cache['remoteURL'] = $url;
377 return $this->cache['remoteURL'];
381 * Check to see if the current cache is fully populated.
383 * Note: This method is public only to make unit testing easier. There's
384 * really no strong reason that anything other than a test should want to
385 * call this method.
387 * @return bool True if all expected cache keys exist, false otherwise
389 public function cacheIsComplete() {
390 return isset( $this->cache['head'] ) &&
391 isset( $this->cache['headSHA1'] ) &&
392 isset( $this->cache['headCommitDate'] ) &&
393 isset( $this->cache['branch'] ) &&
394 isset( $this->cache['remoteURL'] );
398 * Precompute and cache git information.
400 * Creates a JSON file in the cache directory associated with this
401 * GitInfo instance. This cache file will be used by subsequent GitInfo objects referencing
402 * the same directory to avoid needing to examine the .git directory again.
404 * @since 1.24
406 public function precomputeValues() {
407 if ( $this->cacheFile !== null ) {
408 // Try to completely populate the cache
409 $this->getHead();
410 $this->getHeadSHA1();
411 $this->getHeadCommitDate();
412 $this->getCurrentBranch();
413 $this->getRemoteUrl();
415 if ( !$this->cacheIsComplete() ) {
416 $this->logger->debug(
417 "Failed to compute GitInfo for \"{$this->basedir}\""
419 return;
422 $cacheDir = dirname( $this->cacheFile );
423 if ( !file_exists( $cacheDir ) &&
424 !wfMkdirParents( $cacheDir, null, __METHOD__ )
426 throw new RuntimeException( "Unable to create GitInfo cache \"{$cacheDir}\"" );
429 file_put_contents( $this->cacheFile, FormatJson::encode( $this->cache ) );
434 * @see self::getHeadSHA1
435 * @return string
437 public static function headSHA1() {
438 return self::repo()->getHeadSHA1();
442 * @see self::getCurrentBranch
443 * @return string
445 public static function currentBranch() {
446 return self::repo()->getCurrentBranch();
450 * @see self::getHeadViewUrl()
451 * @return string|false
453 public static function headViewUrl() {
454 return self::repo()->getHeadViewUrl();
458 * Gets the list of repository viewers
459 * @return array
461 private function getViewers() {
462 if ( self::$viewers === false ) {
463 self::$viewers = $this->options->get( MainConfigNames::GitRepositoryViewers );
464 $this->hookRunner->onGitViewers( self::$viewers );
467 return self::$viewers;