Remove unused variables from SpecialAllpages::showToplevel()
[lhc/web/wiklou.git] / includes / GitInfo.php
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.
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 */
25
26 class GitInfo {
27
28 /**
29 * Singleton for the repo at $IP
30 */
31 protected static $repo = null;
32
33 /**
34 * Location of the .git directory
35 */
36 protected $basedir;
37
38 /**
39 * Path to JSON cache file for pre-computed git information.
40 */
41 protected $cacheFile;
42
43 /**
44 * Cached git information.
45 */
46 protected $cache = array();
47
48 /**
49 * Map of repo URLs to viewer URLs. Access via static method getViewers().
50 */
51 private static $viewers = false;
52
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
57 */
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
67 );
68 }
69
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;
83 }
84 }
85 }
86 }
87 }
88
89 /**
90 * Compute the path to the cache file for a given directory.
91 *
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).
95 */
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 ) );
104 }
105 $repoName = strtr( $repoName, DIRECTORY_SEPARATOR, '-' );
106 $fileName = 'info' . $repoName . '.json';
107 return implode(
108 DIRECTORY_SEPARATOR,
109 array( $wgCacheDirectory, 'gitinfo', $fileName )
110 );
111 }
112 return null;
113 }
114
115 /**
116 * Get the singleton for the repo at $IP
117 *
118 * @return GitInfo
119 */
120 public static function repo() {
121 if ( is_null( self::$repo ) ) {
122 global $IP;
123 self::$repo = new self( $IP );
124 }
125 return self::$repo;
126 }
127
128 /**
129 * Check if a string looks like a hex encoded SHA1 hash
130 *
131 * @param string $str The string to check
132 * @return bool Whether or not the string looks like a SHA1
133 */
134 public static function isSHA1( $str ) {
135 return !!preg_match( '/^[0-9A-F]{40}$/i', $str );
136 }
137
138 /**
139 * Get the HEAD of the repo (without any opening "ref: ")
140 *
141 * @return string|bool The HEAD (git reference or SHA1) or false
142 */
143 public function getHead() {
144 if ( !isset( $this->cache['head'] ) ) {
145 $headFile = "{$this->basedir}/HEAD";
146 $head = false;
147
148 if ( is_readable( $headFile ) ) {
149 $head = file_get_contents( $headFile );
150
151 if ( preg_match( "/ref: (.*)/", $head, $m ) ) {
152 $head = rtrim( $m[1] );
153 } else {
154 $head = rtrim( $head );
155 }
156 }
157 $this->cache['head'] = $head;
158 }
159 return $this->cache['head'];
160 }
161
162 /**
163 * Get the SHA1 for the current HEAD of the repo
164 *
165 * @return string|bool A SHA1 or false
166 */
167 public function getHeadSHA1() {
168 if ( !isset( $this->cache['headSHA1'] ) ) {
169 $head = $this->getHead();
170 $sha1 = false;
171
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 ) );
180 }
181 }
182 $this->cache['headSHA1'] = $sha1;
183 }
184 return $this->cache['headSHA1'];
185 }
186
187 /**
188 * Get the commit date of HEAD entry of the git code repository
189 *
190 * @since 1.22
191 * @return int|bool Commit date (UNIX timestamp) or false
192 */
193 public function getHeadCommitDate() {
194 global $wgGitBin;
195
196 if ( !isset( $this->cache['headCommitDate'] ) ) {
197 $date = false;
198 if ( is_file( $wgGitBin ) &&
199 is_executable( $wgGitBin ) &&
200 $this->getHead() !== false
201 ) {
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;
209 }
210 }
211 $this->cache['headCommitDate'] = $date;
212 }
213 return $this->cache['headCommitDate'];
214 }
215
216 /**
217 * Get the name of the current branch, or HEAD if not found
218 *
219 * @return string|bool The branch name, HEAD, or false
220 */
221 public function getCurrentBranch() {
222 if ( !isset( $this->cache['branch'] ) ) {
223 $branch = $this->getHead();
224 if ( $branch &&
225 preg_match( "#^refs/heads/(.*)$#", $branch, $m )
226 ) {
227 $branch = $m[1];
228 }
229 $this->cache['branch'] = $branch;
230 }
231 return $this->cache['branch'];
232 }
233
234 /**
235 * Get an URL to a web viewer link to the HEAD revision.
236 *
237 * @return string|bool String if a URL is available or false otherwise
238 */
239 public function getHeadViewUrl() {
240 $url = $this->getRemoteUrl();
241 if ( $url === false ) {
242 return false;
243 }
244 if ( substr( $url, -4 ) !== '.git' ) {
245 $url .= '.git';
246 }
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] ),
256 );
257 return strtr( $viewerUrl, $replacements );
258 }
259 }
260 return false;
261 }
262
263 /**
264 * Get the URL of the remote origin.
265 * @return string|bool string if a URL is available or false otherwise.
266 */
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;
276
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;
284 }
285 }
286 }
287
288 if ( $remote !== false && isset( $remote['url'] ) ) {
289 $url = $remote['url'];
290 }
291 }
292 $this->cache['remoteURL'] = $url;
293 }
294 return $this->cache['remoteURL'];
295 }
296
297 /**
298 * Check to see if the current cache is fully populated.
299 *
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.
303 *
304 * @return bool True if all expected cache keys exist, false otherwise
305 */
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'] );
312 }
313
314 /**
315 * Precompute and cache git information.
316 *
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.
320 *
321 * @since 1.24
322 */
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();
331
332 if ( !$this->cacheIsComplete() ) {
333 wfDebugLog( "Failed to compute GitInfo for \"{$this->basedir}\"" );
334 return;
335 }
336
337 $cacheDir = dirname( $this->cacheFile );
338 if ( !file_exists( $cacheDir ) &&
339 !wfMkdirParents( $cacheDir, null, __METHOD__ )
340 ) {
341 throw new MWException( "Unable to create GitInfo cache \"{$cacheDir}\"" );
342 }
343
344 file_put_contents( $this->cacheFile, FormatJson::encode( $this->cache ) );
345 }
346 }
347
348 /**
349 * @see self::getHeadSHA1
350 * @return string
351 */
352 public static function headSHA1() {
353 return self::repo()->getHeadSHA1();
354 }
355
356 /**
357 * @see self::getCurrentBranch
358 * @return string
359 */
360 public static function currentBranch() {
361 return self::repo()->getCurrentBranch();
362 }
363
364 /**
365 * @see self::getHeadViewUrl()
366 * @return bool|string
367 */
368 public static function headViewUrl() {
369 return self::repo()->getHeadViewUrl();
370 }
371
372 /**
373 * Gets the list of repository viewers
374 * @return array
375 */
376 protected static function getViewers() {
377 global $wgGitRepositoryViewers;
378
379 if ( self::$viewers === false ) {
380 self::$viewers = $wgGitRepositoryViewers;
381 wfRunHooks( 'GitViewers', array( &self::$viewers ) );
382 }
383
384 return self::$viewers;
385 }
386 }