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
26 use MediaWiki\Shell\Shell
;
31 * Singleton for the repo at $IP
33 protected static $repo = null;
36 * Location of the .git directory
41 * Path to JSON cache file for pre-computed git information.
46 * Cached git information.
48 protected $cache = [];
51 * @var array|false Map of repo URLs to viewer URLs. Access via static method getViewers().
53 private static $viewers = false;
56 * @param string $repoDir The root directory of the repo where .git can be found
57 * @param bool $usePrecomputed Use precomputed information if available
58 * @see precomputeValues
60 public function __construct( $repoDir, $usePrecomputed = true ) {
61 $this->cacheFile
= self
::getCacheFilePath( $repoDir );
62 wfDebugLog( 'gitinfo',
63 "Computed cacheFile={$this->cacheFile} for {$repoDir}"
65 if ( $usePrecomputed &&
66 $this->cacheFile
!== null &&
67 is_readable( $this->cacheFile
)
69 $this->cache
= FormatJson
::decode(
70 file_get_contents( $this->cacheFile
),
73 wfDebugLog( 'gitinfo', "Loaded git data from cache for {$repoDir}" );
76 if ( !$this->cacheIsComplete() ) {
77 wfDebugLog( 'gitinfo', "Cache incomplete for {$repoDir}" );
78 $this->basedir
= $repoDir . DIRECTORY_SEPARATOR
. '.git';
79 if ( is_readable( $this->basedir
) && !is_dir( $this->basedir
) ) {
80 $GITfile = file_get_contents( $this->basedir
);
81 if ( strlen( $GITfile ) > 8 &&
82 substr( $GITfile, 0, 8 ) === 'gitdir: '
84 $path = rtrim( substr( $GITfile, 8 ), "\r\n" );
85 if ( $path[0] === '/' ||
substr( $path, 1, 1 ) === ':' ) {
86 // Path from GITfile is absolute
87 $this->basedir
= $path;
89 $this->basedir
= $repoDir . DIRECTORY_SEPARATOR
. $path;
97 * Compute the path to the cache file for a given directory.
99 * @param string $repoDir The root directory of the repo where .git can be found
100 * @return string Path to GitInfo cache file in $wgGitInfoCacheDirectory or
101 * fallback in the extension directory itself
104 protected static function getCacheFilePath( $repoDir ) {
105 global $IP, $wgGitInfoCacheDirectory;
107 if ( $wgGitInfoCacheDirectory ) {
108 // Convert both $IP and $repoDir to canonical paths to protect against
109 // $IP having changed between the settings files and runtime.
110 $realIP = realpath( $IP );
111 $repoName = realpath( $repoDir );
112 if ( $repoName === false ) {
113 // Unit tests use fake path names
114 $repoName = $repoDir;
116 if ( strpos( $repoName, $realIP ) === 0 ) {
117 // Strip $IP from path
118 $repoName = substr( $repoName, strlen( $realIP ) );
120 // Transform path to git repo to something we can safely embed in
122 $repoName = strtr( $repoName, DIRECTORY_SEPARATOR
, '-' );
123 $fileName = 'info' . $repoName . '.json';
124 $cachePath = "{$wgGitInfoCacheDirectory}/{$fileName}";
125 if ( is_readable( $cachePath ) ) {
130 return "$repoDir/gitinfo.json";
134 * Get the singleton for the repo at $IP
138 public static function repo() {
139 if ( is_null( self
::$repo ) ) {
141 self
::$repo = new self( $IP );
147 * Check if a string looks like a hex encoded SHA1 hash
149 * @param string $str The string to check
150 * @return bool Whether or not the string looks like a SHA1
152 public static function isSHA1( $str ) {
153 return !!preg_match( '/^[0-9A-F]{40}$/i', $str );
157 * Get the HEAD of the repo (without any opening "ref: ")
159 * @return string|bool The HEAD (git reference or SHA1) or false
161 public function getHead() {
162 if ( !isset( $this->cache
['head'] ) ) {
163 $headFile = "{$this->basedir}/HEAD";
166 if ( is_readable( $headFile ) ) {
167 $head = file_get_contents( $headFile );
169 if ( preg_match( "/ref: (.*)/", $head, $m ) ) {
170 $head = rtrim( $m[1] );
172 $head = rtrim( $head );
175 $this->cache
['head'] = $head;
177 return $this->cache
['head'];
181 * Get the SHA1 for the current HEAD of the repo
183 * @return string|bool A SHA1 or false
185 public function getHeadSHA1() {
186 if ( !isset( $this->cache
['headSHA1'] ) ) {
187 $head = $this->getHead();
190 // If detached HEAD may be a SHA1
191 if ( self
::isSHA1( $head ) ) {
194 // If not a SHA1 it may be a ref:
195 $refFile = "{$this->basedir}/{$head}";
196 $packedRefs = "{$this->basedir}/packed-refs";
197 $headRegex = preg_quote( $head, '/' );
198 if ( is_readable( $refFile ) ) {
199 $sha1 = rtrim( file_get_contents( $refFile ) );
200 } elseif ( is_readable( $packedRefs ) &&
201 preg_match( "/^([0-9A-Fa-f]{40}) $headRegex$/m", file_get_contents( $packedRefs ), $matches )
206 $this->cache
['headSHA1'] = $sha1;
208 return $this->cache
['headSHA1'];
212 * Get the commit date of HEAD entry of the git code repository
215 * @return int|bool Commit date (UNIX timestamp) or false
217 public function getHeadCommitDate() {
220 if ( !isset( $this->cache
['headCommitDate'] ) ) {
222 if ( is_file( $wgGitBin ) &&
223 is_executable( $wgGitBin ) &&
224 $this->getHead() !== false
230 '--format=format:%ct',
233 $result = Shell
::command( $cmd )
234 ->environment( [ 'GIT_DIR' => $this->basedir
] )
237 if ( $result->getExitCode() === 0 ) {
238 $date = (int)$result->getStdout();
241 $this->cache
['headCommitDate'] = $date;
243 return $this->cache
['headCommitDate'];
247 * Get the name of the current branch, or HEAD if not found
249 * @return string|bool The branch name, HEAD, or false
251 public function getCurrentBranch() {
252 if ( !isset( $this->cache
['branch'] ) ) {
253 $branch = $this->getHead();
255 preg_match( "#^refs/heads/(.*)$#", $branch, $m )
259 $this->cache
['branch'] = $branch;
261 return $this->cache
['branch'];
265 * Get an URL to a web viewer link to the HEAD revision.
267 * @return string|bool String if a URL is available or false otherwise
269 public function getHeadViewUrl() {
270 $url = $this->getRemoteUrl();
271 if ( $url === false ) {
274 foreach ( self
::getViewers() as $repo => $viewer ) {
275 $pattern = '#^' . $repo . '$#';
276 if ( preg_match( $pattern, $url, $matches ) ) {
277 $viewerUrl = preg_replace( $pattern, $viewer, $url );
278 $headSHA1 = $this->getHeadSHA1();
280 '%h' => substr( $headSHA1, 0, 7 ),
282 '%r' => urlencode( $matches[1] ),
285 return strtr( $viewerUrl, $replacements );
292 * Get the URL of the remote origin.
293 * @return string|bool String if a URL is available or false otherwise.
295 protected function getRemoteUrl() {
296 if ( !isset( $this->cache
['remoteURL'] ) ) {
297 $config = "{$this->basedir}/config";
299 if ( is_readable( $config ) ) {
300 MediaWiki\
suppressWarnings();
301 $configArray = parse_ini_file( $config, true );
302 MediaWiki\restoreWarnings
();
305 // Use the "origin" remote repo if available or any other repo if not.
306 if ( isset( $configArray['remote origin'] ) ) {
307 $remote = $configArray['remote origin'];
308 } elseif ( is_array( $configArray ) ) {
309 foreach ( $configArray as $sectionName => $sectionConf ) {
310 if ( substr( $sectionName, 0, 6 ) == 'remote' ) {
311 $remote = $sectionConf;
316 if ( $remote !== false && isset( $remote['url'] ) ) {
317 $url = $remote['url'];
320 $this->cache
['remoteURL'] = $url;
322 return $this->cache
['remoteURL'];
326 * Check to see if the current cache is fully populated.
328 * Note: This method is public only to make unit testing easier. There's
329 * really no strong reason that anything other than a test should want to
332 * @return bool True if all expected cache keys exist, false otherwise
334 public function cacheIsComplete() {
335 return isset( $this->cache
['head'] ) &&
336 isset( $this->cache
['headSHA1'] ) &&
337 isset( $this->cache
['headCommitDate'] ) &&
338 isset( $this->cache
['branch'] ) &&
339 isset( $this->cache
['remoteURL'] );
343 * Precompute and cache git information.
345 * Creates a JSON file in the cache directory associated with this
346 * GitInfo instance. This cache file will be used by subsequent GitInfo objects referencing
347 * the same directory to avoid needing to examine the .git directory again.
351 public function precomputeValues() {
352 if ( $this->cacheFile
!== null ) {
353 // Try to completely populate the cache
355 $this->getHeadSHA1();
356 $this->getHeadCommitDate();
357 $this->getCurrentBranch();
358 $this->getRemoteUrl();
360 if ( !$this->cacheIsComplete() ) {
361 wfDebugLog( 'gitinfo',
362 "Failed to compute GitInfo for \"{$this->basedir}\""
367 $cacheDir = dirname( $this->cacheFile
);
368 if ( !file_exists( $cacheDir ) &&
369 !wfMkdirParents( $cacheDir, null, __METHOD__
)
371 throw new MWException( "Unable to create GitInfo cache \"{$cacheDir}\"" );
374 file_put_contents( $this->cacheFile
, FormatJson
::encode( $this->cache
) );
379 * @see self::getHeadSHA1
382 public static function headSHA1() {
383 return self
::repo()->getHeadSHA1();
387 * @see self::getCurrentBranch
390 public static function currentBranch() {
391 return self
::repo()->getCurrentBranch();
395 * @see self::getHeadViewUrl()
396 * @return bool|string
398 public static function headViewUrl() {
399 return self
::repo()->getHeadViewUrl();
403 * Gets the list of repository viewers
406 protected static function getViewers() {
407 global $wgGitRepositoryViewers;
409 if ( self
::$viewers === false ) {
410 self
::$viewers = $wgGitRepositoryViewers;
411 Hooks
::run( 'GitViewers', [ &self
::$viewers ] );
414 return self
::$viewers;