Show list of affected files in commit view.
[viewgit.git] / inc / functions.php
blob809f6fa1f89645767ca473520fa6189f9cf2241a
1 <?php
2 /** @file
3 * Functions used by ViewGit.
4 */
6 function debug($msg)
8 global $conf;
10 if ($conf['debug']) {
11 file_put_contents('php://stderr', gmstrftime('%H:%M:%S') ." viewgit: $_SERVER[REMOTE_ADDR]:$_SERVER[REMOTE_PORT] $msg\n", FILE_APPEND);
15 /**
16 * Format author's name & wrap it to links etc.
18 function format_author($author)
20 global $page;
22 if (isset($page['project'])) {
23 // FIXME 'h' - use only if available
24 return '<a href="'. makelink(array('a' => 'search', 'p' => $page['project'], 'h' => 'HEAD', 'st' => 'author', 's' => $author)) .'">'. htmlentities_wrapper($author) .'</a>';
25 } else {
26 return htmlentities_wrapper($author);
30 /**
31 * Formats "git diff" output into xhtml.
32 * @return array(array of filenames, xhtml)
34 function format_diff($text)
36 $files = array();
38 // match every "^diff --git a/<path> b/<path>$" line
39 foreach (explode("\n", $text) as $line) {
40 if (preg_match('#^diff --git a/(.*) b/(.*)$#', $line, $matches) > 0) {
41 $files[$matches[1]] = urlencode($matches[1]);
45 $text = htmlentities_wrapper($text);
47 $text = preg_replace(
48 array(
49 '/^(\+.*)$/m',
50 '/^(-.*)$/m',
51 '/^(@.*)$/m',
52 '/^([^d\+-@].*)$/m',
54 array(
55 '<span class="add">$1</span>',
56 '<span class="del">$1</span>',
57 '<span class="pos">$1</span>',
58 '<span class="etc">$1</span>',
60 $text);
61 $text = preg_replace_callback('#^diff --git a/(.*) b/(.*)$#m',
62 create_function(
63 '$m',
64 'return "<span class=\"diffline\"><a name=\"". urlencode($m[1]) ."\">diff --git a/$m[1] b/$m[2]</a></span>";'
66 $text);
68 return array($files, $text);
71 /**
72 * Get project information from config and git, name/description and HEAD
73 * commit info are returned in an array.
75 function get_project_info($name)
77 global $conf;
79 $info = $conf['projects'][$name];
80 $info['name'] = $name;
82 // If description is not set, read it from the repository's description
83 if (!isset($info['description'])) {
84 $info['description'] = file_get_contents($info['repo'] .'/description');
87 $headinfo = git_get_commit_info($name, 'HEAD');
88 $info['head_stamp'] = $headinfo['author_utcstamp'];
89 $info['head_datetime'] = gmstrftime($conf['datetime'], $headinfo['author_utcstamp']);
90 $info['head_hash'] = $headinfo['h'];
91 $info['head_tree'] = $headinfo['tree'];
93 return $info;
96 /**
97 * Get diff between given revisions as text.
99 function git_diff($project, $from, $to)
101 return join("\n", run_git($project, "diff \"$from..$to\""));
104 function git_diffstat($project, $commit, $commit_base = null)
106 if (is_null($commit_base)) {
107 $commit_base = "$commit^";
109 return join("\n", run_git($project, "diff --stat $commit_base..$commit"));
113 * Get details of a commit: tree, parents, author/committer (name, mail, date), message
115 function git_get_commit_info($project, $hash = 'HEAD', $path = null)
117 global $conf;
119 $info = array();
120 $info['h_name'] = $hash;
121 $info['message_full'] = '';
122 $info['parents'] = array();
124 $extra = '';
125 if (isset($path)) {
126 $extra = '-- '. escapeshellarg($path);
129 $output = run_git($project, "rev-list --header --max-count=1 $hash $extra");
130 // tree <h>
131 // parent <h>
132 // author <name> "<"<mail>">" <stamp> <timezone>
133 // committer
134 // <empty>
135 // <message>
136 $pattern = '/^(author|committer) ([^<]+) <([^>]*)> ([0-9]+) (.*)$/';
137 foreach ($output as $line) {
138 if (substr($line, 0, 4) === 'tree') {
139 $info['tree'] = substr($line, 5);
141 // may be repeated multiple times for merge/octopus
142 elseif (substr($line, 0, 6) === 'parent') {
143 $info['parents'][] = substr($line, 7);
145 elseif (preg_match($pattern, $line, $matches) > 0) {
146 $info[$matches[1] .'_name'] = $matches[2];
147 $info[$matches[1] .'_mail'] = $matches[3];
148 $info[$matches[1] .'_stamp'] = $matches[4] + ((intval($matches[5]) / 100.0) * 3600);
149 $info[$matches[1] .'_timezone'] = $matches[5];
150 $info[$matches[1] .'_utcstamp'] = $matches[4];
152 if (isset($conf['mail_filter'])) {
153 $info[$matches[1] .'_mail'] = $conf['mail_filter']($info[$matches[1] .'_mail']);
156 // Lines starting with four spaces and empty lines after first such line are part of commit message
157 elseif (substr($line, 0, 4) === ' ' || (strlen($line) == 0 && isset($info['message']))) {
158 $info['message_full'] .= substr($line, 4) ."\n";
159 if (!isset($info['message'])) {
160 $info['message'] = substr($line, 4, $conf['commit_message_maxlen']);
161 $info['message_firstline'] = substr($line, 4);
164 elseif (preg_match('/^[0-9a-f]{40}$/', $line) > 0) {
165 $info['h'] = $line;
169 // This is a workaround for the unlikely situation where a commit does
170 // not have a message. Such a commit can be created with the following
171 // command:
172 // git commit --allow-empty -m '' --cleanup=verbatim
173 if (!array_key_exists('message', $info)) {
174 $info['message'] = '(no message)';
175 $info['message_firstline'] = '(no message)';
178 $info['author_datetime'] = gmstrftime($conf['datetime_full'], $info['author_utcstamp']);
179 $info['author_datetime_local'] = gmstrftime($conf['datetime_full'], $info['author_stamp']) .' '. $info['author_timezone'];
180 $info['committer_datetime'] = gmstrftime($conf['datetime_full'], $info['committer_utcstamp']);
181 $info['committer_datetime_local'] = gmstrftime($conf['datetime_full'], $info['committer_stamp']) .' '. $info['committer_timezone'];
183 $info['affected_files'] = array();
184 $affected_files = run_git($project, "show --pretty=\"format:\" --name-only $hash");
185 foreach ($affected_files as $file ) {
186 // The format above contains a blank line; Skip it.
187 if ($file == '') {
188 continue;
191 $output = run_git($project, "ls-tree $hash $file");
192 foreach ($output as $line) {
193 $parts = preg_split('/\s+/', $line, 4);
194 $info['affected_files'][] = array('name' => $parts[3], 'hash' => $parts[2]);
198 return $info;
202 * Get list of heads (branches) for a project.
204 function git_get_heads($project)
206 $heads = array();
208 $output = run_git($project, 'show-ref --heads');
209 foreach ($output as $line) {
210 $fullname = substr($line, 41);
211 $tmp = explode('/', $fullname);
212 $name = array_pop($tmp);
213 $heads[] = array('h' => substr($line, 0, 40), 'fullname' => "$fullname", 'name' => "$name");
216 return $heads;
220 * Get array containing path information for parts, starting from root_hash.
222 * @param root_hash commit/tree hash for the root tree
223 * @param path path
225 function git_get_path_info($project, $root_hash, $path)
227 if (strlen($path) > 0) {
228 $parts = explode('/', $path);
229 } else {
230 $parts = array();
233 $pathinfo = array();
235 $tid = $root_hash;
236 $pathinfo = array();
237 foreach ($parts as $p) {
238 $entry = git_ls_tree_part($project, $tid, $p);
239 if (is_null($entry)) {
240 die("Invalid path info: $path");
242 $pathinfo[] = $entry;
243 $tid = $entry['hash'];
246 return $pathinfo;
250 * Get revision list starting from given commit.
251 * @param skip how many hashes to skip from the beginning
252 * @param max_count number of commit hashes to return, or all if not given
253 * @param start revision to start from, or HEAD if not given
255 function git_get_rev_list($project, $skip = 0, $max_count = null, $start = 'HEAD')
257 $cmd = "rev-list ";
258 if ($skip != 0) {
259 $cmd .= "--skip=$skip ";
261 if (!is_null($max_count)) {
262 $cmd .= "--max-count=$max_count ";
264 $cmd .= $start;
266 return run_git($project, $cmd);
270 * Get list of tags for a project.
272 function git_get_tags($project)
274 $tags = array();
276 $output = run_git($project, 'show-ref --tags');
277 foreach ($output as $line) {
278 $fullname = substr($line, 41);
279 $tmp = explode('/', $fullname);
280 $name = array_pop($tmp);
281 $tags[] = array('h' => substr($line, 0, 40), 'fullname' => $fullname, 'name' => $name);
283 return $tags;
287 * Get information about objects in a tree.
288 * @param tree tree or commit hash
289 * @return list of arrays containing name, mode, type, hash
291 function git_ls_tree($project, $tree)
293 $entries = array();
294 $output = run_git($project, "ls-tree $tree");
295 // 100644 blob 493b7fc4296d64af45dac64bceac2d9a96c958c1 .gitignore
296 // 040000 tree 715c78b1011dc58106da2a1af2fe0aa4c829542f doc
297 foreach ($output as $line) {
298 $parts = preg_split('/\s+/', $line, 4);
299 $entries[] = array('name' => $parts[3], 'mode' => $parts[0], 'type' => $parts[1], 'hash' => $parts[2]);
302 return $entries;
306 * Get information about the given object in a tree, or null if not in the tree.
308 function git_ls_tree_part($project, $tree, $name)
310 $entries = git_ls_tree($project, $tree);
311 foreach ($entries as $entry) {
312 if ($entry['name'] === $name) {
313 return $entry;
316 return null;
320 * Get the ref list as dict: hash -> list of names.
321 * @param tags whether to show tags
322 * @param heads whether to show heads
323 * @param remotes whether to show remote heads, currently implies tags and heads too.
325 function git_ref_list($project, $tags = true, $heads = true, $remotes = true)
327 $cmd = "show-ref --dereference";
328 if (!$remotes) {
329 if ($tags) { $cmd .= " --tags"; }
330 if ($heads) { $cmd .= " --heads"; }
333 $result = array();
334 $output = run_git($project, $cmd);
335 foreach ($output as $line) {
336 // <hash> <ref>
337 $parts = explode(' ', $line, 2);
338 $name = str_replace(array('refs/', '^{}'), array('', ''), $parts[1]);
339 $result[$parts[0]][] = $name;
341 return $result;
345 * Find commits based on search type and string.
347 function git_search_commits($project, $branch, $type, $string)
349 // git log -sFOO
350 if ($type == 'change') {
351 $cmd = 'log -S'. escapeshellarg($string);
353 elseif ($type == 'commit') {
354 $cmd = 'log -i --grep='. escapeshellarg($string);
356 elseif ($type == 'author') {
357 $cmd = 'log -i --author='. escapeshellarg($string);
359 elseif ($type == 'committer') {
360 $cmd = 'log -i --committer='. escapeshellarg($string);
362 else {
363 die('Unsupported type');
365 $cmd .= ' '. $branch;
366 $lines = run_git($project, $cmd);
368 $result = array();
369 foreach ($lines as $line) {
370 if (preg_match('/^commit (.*?)$/', $line, $matches)) {
371 $result[] = $matches[1];
374 return $result;
378 * Get shortlog entries for the given project.
380 function handle_shortlog($project, $hash = 'HEAD', $page = 0)
382 global $conf;
384 $refs_by_hash = git_ref_list($project, true, true, $conf['shortlog_remote_labels']);
386 $result = array();
387 $revs = git_get_rev_list($project, $page * $conf['summary_shortlog'], $conf['summary_shortlog'], $hash);
388 foreach ($revs as $rev) {
389 $info = git_get_commit_info($project, $rev);
390 $refs = array();
391 if (in_array($rev, array_keys($refs_by_hash))) {
392 $refs = $refs_by_hash[$rev];
394 $result[] = array(
395 'author' => $info['author_name'],
396 'date' => gmstrftime($conf['datetime'], $info['author_utcstamp']),
397 'message' => $info['message'],
398 'commit_id' => $rev,
399 'tree' => $info['tree'],
400 'refs' => $refs,
403 #print_r($result);
404 #die();
406 return $result;
410 * Fetch tags data, newest first.
412 * @param limit maximum number of tags to return
414 function handle_tags($project, $limit = 0)
416 global $conf;
418 $tags = git_get_tags($project);
419 $result = array();
420 foreach ($tags as $tag) {
421 $info = git_get_commit_info($project, $tag['h']);
422 $result[] = array(
423 'stamp' => $info['author_utcstamp'],
424 'date' => gmstrftime($conf['datetime'], $info['author_utcstamp']),
425 'h' => $tag['h'],
426 'fullname' => $tag['fullname'],
427 'name' => $tag['name'],
431 // sort tags newest first
432 // aka. two more reasons to hate PHP (figuring those out is your homework:)
433 usort($result, create_function(
434 '$x, $y',
435 '$a = $x["stamp"]; $b = $y["stamp"]; return ($a == $b ? 0 : ($a > $b ? -1 : 1));'
438 // TODO optimize this some way, currently all tags are fetched when only a
439 // few are shown. The problem is that without fetching the commit info
440 // above, we can't sort using dates, only by tag name...
441 if ($limit > 0) {
442 $result = array_splice($result, 0, $limit);
445 return $result;
448 function htmlentities_wrapper($text)
450 return htmlentities(@iconv('UTF-8', 'UTF-8//IGNORE', $text), ENT_NOQUOTES, 'UTF-8');
453 function xmlentities_wrapper($text)
455 return str_replace(array('&', '<'), array('&#x26;', '&#x3C;'), @iconv('UTF-8', 'UTF-8//IGNORE', $text));
459 * Return a URL that contains the given parameters.
461 function makelink($dict)
463 $params = array();
464 foreach ($dict as $k => $v) {
465 $params[] = rawurlencode($k) .'='. str_replace('%2F', '/', rawurlencode($v));
467 if (count($params) > 0) {
468 return '?'. htmlentities_wrapper(join('&', $params));
470 return '';
474 * Obfuscate the e-mail address.
476 function obfuscate_mail($mail)
478 return str_replace(array('@', '.'), array(' at ', ' dot '), $mail);
482 * Used to format RSS item title and description.
484 * @param info commit info from git_get_commit_info()
486 function rss_item_format($format, $info)
488 return preg_replace(array(
489 '/{AUTHOR}/',
490 '/{AUTHOR_MAIL}/',
491 '/{SHORTLOG}/',
492 '/{LOG}/',
493 '/{COMMITTER}/',
494 '/{COMMITTER_MAIL}/',
495 '/{DIFFSTAT}/',
496 ), array(
497 htmlentities_wrapper($info['author_name']),
498 htmlentities_wrapper($info['author_mail']),
499 htmlentities_wrapper($info['message_firstline']),
500 htmlentities_wrapper($info['message_full']),
501 htmlentities_wrapper($info['committer_name']),
502 htmlentities_wrapper($info['committer_mail']),
503 htmlentities_wrapper(isset($info['diffstat']) ? $info['diffstat'] : ''),
504 ), $format);
507 function rss_pubdate($secs)
509 return gmdate('D, d M Y H:i:s O', $secs);
513 * Executes a git command in the project repo.
514 * @return array of output lines
516 function run_git($project, $command)
518 global $conf;
520 $output = array();
521 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
522 $ret = 0;
523 exec($cmd, $output, $ret);
524 if ($conf['debug_command_trace']) {
525 static $count = 0;
526 $count++;
527 trigger_error("[$count]\$ $cmd [exit $ret]");
529 //if ($ret != 0) { die('FATAL: exec() for git failed, is the path properly configured?'); }
530 return $output;
534 * Executes a git command in the project repo, sending output directly to the
535 * client.
537 function run_git_passthru($project, $command)
539 global $conf;
541 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
542 $result = 0;
543 passthru($cmd, $result);
544 return $result;
548 * Makes sure the given project is valid. If it's not, this function will
549 * die().
550 * @return the project
552 function validate_project($project)
554 global $conf;
556 if (!in_array($project, array_keys($conf['projects']))) {
557 die('Invalid project');
559 return $project;
563 * Makes sure the given hash is valid. If it's not, this function will die().
564 * @return the hash
566 function validate_hash($hash)
568 if (!preg_match('/^[0-9a-z]{40}$/', $hash) && !preg_match('!^refs/(heads|tags)/[-_.0-9a-zA-Z]+$!', $hash) && $hash !== 'HEAD') {
569 die('Invalid hash');
572 return $hash;
576 * Custom error handler for ViewGit. The errors are pushed to $page['notices']
577 * and displayed by templates/header.php.
579 function vg_error_handler($errno, $errstr, $errfile, $errline)
581 global $page;
583 $mask = ini_get('error_reporting');
585 $class = 'error';
587 // If mask for this error is not enabled, return silently
588 if (!($errno & $mask)) {
589 return true;
592 // Remove any preceding path until viewgit's directory
593 $file = $errfile;
594 $file = strstr($file, 'viewgit/');
596 $message = "$file:$errline $errstr [$errno]";
598 switch ($errno) {
599 case E_ERROR:
600 $class = 'error';
601 break;
602 case E_WARNING:
603 $class = 'warning';
604 break;
605 case E_NOTICE:
606 case E_STRICT:
607 default:
608 $class = 'info';
609 break;
612 $page['notices'][] = array(
613 'message' => $message,
614 'class' => $class,
617 return true;