Doublequote git diff parameters ("from^..to").
[viewgit.git] / inc / functions.php
blobff7f0d4fb3fffe66986cb29ceb73bda25e069b7a
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 return $info;
187 * Get list of heads (branches) for a project.
189 function git_get_heads($project)
191 $heads = array();
193 $output = run_git($project, 'show-ref --heads');
194 foreach ($output as $line) {
195 $fullname = substr($line, 41);
196 $tmp = explode('/', $fullname);
197 $name = array_pop($tmp);
198 $heads[] = array('h' => substr($line, 0, 40), 'fullname' => "$fullname", 'name' => "$name");
201 return $heads;
205 * Get array containing path information for parts, starting from root_hash.
207 * @param root_hash commit/tree hash for the root tree
208 * @param path path
210 function git_get_path_info($project, $root_hash, $path)
212 if (strlen($path) > 0) {
213 $parts = explode('/', $path);
214 } else {
215 $parts = array();
218 $pathinfo = array();
220 $tid = $root_hash;
221 $pathinfo = array();
222 foreach ($parts as $p) {
223 $entry = git_ls_tree_part($project, $tid, $p);
224 if (is_null($entry)) {
225 die("Invalid path info: $path");
227 $pathinfo[] = $entry;
228 $tid = $entry['hash'];
231 return $pathinfo;
235 * Get revision list starting from given commit.
236 * @param skip how many hashes to skip from the beginning
237 * @param max_count number of commit hashes to return, or all if not given
238 * @param start revision to start from, or HEAD if not given
240 function git_get_rev_list($project, $skip = 0, $max_count = null, $start = 'HEAD')
242 $cmd = "rev-list ";
243 if ($skip != 0) {
244 $cmd .= "--skip=$skip ";
246 if (!is_null($max_count)) {
247 $cmd .= "--max-count=$max_count ";
249 $cmd .= $start;
251 return run_git($project, $cmd);
255 * Get list of tags for a project.
257 function git_get_tags($project)
259 $tags = array();
261 $output = run_git($project, 'show-ref --tags');
262 foreach ($output as $line) {
263 $fullname = substr($line, 41);
264 $tmp = explode('/', $fullname);
265 $name = array_pop($tmp);
266 $tags[] = array('h' => substr($line, 0, 40), 'fullname' => $fullname, 'name' => $name);
268 return $tags;
272 * Get information about objects in a tree.
273 * @param tree tree or commit hash
274 * @return list of arrays containing name, mode, type, hash
276 function git_ls_tree($project, $tree)
278 $entries = array();
279 $output = run_git($project, "ls-tree $tree");
280 // 100644 blob 493b7fc4296d64af45dac64bceac2d9a96c958c1 .gitignore
281 // 040000 tree 715c78b1011dc58106da2a1af2fe0aa4c829542f doc
282 foreach ($output as $line) {
283 $parts = preg_split('/\s+/', $line, 4);
284 $entries[] = array('name' => $parts[3], 'mode' => $parts[0], 'type' => $parts[1], 'hash' => $parts[2]);
287 return $entries;
291 * Get information about the given object in a tree, or null if not in the tree.
293 function git_ls_tree_part($project, $tree, $name)
295 $entries = git_ls_tree($project, $tree);
296 foreach ($entries as $entry) {
297 if ($entry['name'] === $name) {
298 return $entry;
301 return null;
305 * Get the ref list as dict: hash -> list of names.
306 * @param tags whether to show tags
307 * @param heads whether to show heads
308 * @param remotes whether to show remote heads, currently implies tags and heads too.
310 function git_ref_list($project, $tags = true, $heads = true, $remotes = true)
312 $cmd = "show-ref --dereference";
313 if (!$remotes) {
314 if ($tags) { $cmd .= " --tags"; }
315 if ($heads) { $cmd .= " --heads"; }
318 $result = array();
319 $output = run_git($project, $cmd);
320 foreach ($output as $line) {
321 // <hash> <ref>
322 $parts = explode(' ', $line, 2);
323 $name = str_replace(array('refs/', '^{}'), array('', ''), $parts[1]);
324 $result[$parts[0]][] = $name;
326 return $result;
330 * Find commits based on search type and string.
332 function git_search_commits($project, $branch, $type, $string)
334 // git log -sFOO
335 if ($type == 'change') {
336 $cmd = 'log -S'. escapeshellarg($string);
338 elseif ($type == 'commit') {
339 $cmd = 'log -i --grep='. escapeshellarg($string);
341 elseif ($type == 'author') {
342 $cmd = 'log -i --author='. escapeshellarg($string);
344 elseif ($type == 'committer') {
345 $cmd = 'log -i --committer='. escapeshellarg($string);
347 else {
348 die('Unsupported type');
350 $cmd .= ' '. $branch;
351 $lines = run_git($project, $cmd);
353 $result = array();
354 foreach ($lines as $line) {
355 if (preg_match('/^commit (.*?)$/', $line, $matches)) {
356 $result[] = $matches[1];
359 return $result;
363 * Get shortlog entries for the given project.
365 function handle_shortlog($project, $hash = 'HEAD', $page = 0)
367 global $conf;
369 $refs_by_hash = git_ref_list($project, true, true, $conf['shortlog_remote_labels']);
371 $result = array();
372 $revs = git_get_rev_list($project, $page * $conf['summary_shortlog'], $conf['summary_shortlog'], $hash);
373 foreach ($revs as $rev) {
374 $info = git_get_commit_info($project, $rev);
375 $refs = array();
376 if (in_array($rev, array_keys($refs_by_hash))) {
377 $refs = $refs_by_hash[$rev];
379 $result[] = array(
380 'author' => $info['author_name'],
381 'date' => gmstrftime($conf['datetime'], $info['author_utcstamp']),
382 'message' => $info['message'],
383 'commit_id' => $rev,
384 'tree' => $info['tree'],
385 'refs' => $refs,
388 #print_r($result);
389 #die();
391 return $result;
395 * Fetch tags data, newest first.
397 * @param limit maximum number of tags to return
399 function handle_tags($project, $limit = 0)
401 global $conf;
403 $tags = git_get_tags($project);
404 $result = array();
405 foreach ($tags as $tag) {
406 $info = git_get_commit_info($project, $tag['h']);
407 $result[] = array(
408 'stamp' => $info['author_utcstamp'],
409 'date' => gmstrftime($conf['datetime'], $info['author_utcstamp']),
410 'h' => $tag['h'],
411 'fullname' => $tag['fullname'],
412 'name' => $tag['name'],
416 // sort tags newest first
417 // aka. two more reasons to hate PHP (figuring those out is your homework:)
418 usort($result, create_function(
419 '$x, $y',
420 '$a = $x["stamp"]; $b = $y["stamp"]; return ($a == $b ? 0 : ($a > $b ? -1 : 1));'
423 // TODO optimize this some way, currently all tags are fetched when only a
424 // few are shown. The problem is that without fetching the commit info
425 // above, we can't sort using dates, only by tag name...
426 if ($limit > 0) {
427 $result = array_splice($result, 0, $limit);
430 return $result;
433 function htmlentities_wrapper($text)
435 return htmlentities(@iconv('UTF-8', 'UTF-8//IGNORE', $text), ENT_NOQUOTES, 'UTF-8');
438 function xmlentities_wrapper($text)
440 return str_replace(array('&', '<'), array('&#x26;', '&#x3C;'), @iconv('UTF-8', 'UTF-8//IGNORE', $text));
444 * Return a URL that contains the given parameters.
446 function makelink($dict)
448 $params = array();
449 foreach ($dict as $k => $v) {
450 $params[] = rawurlencode($k) .'='. str_replace('%2F', '/', rawurlencode($v));
452 if (count($params) > 0) {
453 return '?'. htmlentities_wrapper(join('&', $params));
455 return '';
459 * Obfuscate the e-mail address.
461 function obfuscate_mail($mail)
463 return str_replace(array('@', '.'), array(' at ', ' dot '), $mail);
467 * Used to format RSS item title and description.
469 * @param info commit info from git_get_commit_info()
471 function rss_item_format($format, $info)
473 return preg_replace(array(
474 '/{AUTHOR}/',
475 '/{AUTHOR_MAIL}/',
476 '/{SHORTLOG}/',
477 '/{LOG}/',
478 '/{COMMITTER}/',
479 '/{COMMITTER_MAIL}/',
480 '/{DIFFSTAT}/',
481 ), array(
482 htmlentities_wrapper($info['author_name']),
483 htmlentities_wrapper($info['author_mail']),
484 htmlentities_wrapper($info['message_firstline']),
485 htmlentities_wrapper($info['message_full']),
486 htmlentities_wrapper($info['committer_name']),
487 htmlentities_wrapper($info['committer_mail']),
488 htmlentities_wrapper(isset($info['diffstat']) ? $info['diffstat'] : ''),
489 ), $format);
492 function rss_pubdate($secs)
494 return gmdate('D, d M Y H:i:s O', $secs);
498 * Executes a git command in the project repo.
499 * @return array of output lines
501 function run_git($project, $command)
503 global $conf;
505 $output = array();
506 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
507 $ret = 0;
508 exec($cmd, $output, $ret);
509 if ($conf['debug_command_trace']) {
510 static $count = 0;
511 $count++;
512 trigger_error("[$count]\$ $cmd [exit $ret]");
514 //if ($ret != 0) { die('FATAL: exec() for git failed, is the path properly configured?'); }
515 return $output;
519 * Executes a git command in the project repo, sending output directly to the
520 * client.
522 function run_git_passthru($project, $command)
524 global $conf;
526 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
527 $result = 0;
528 passthru($cmd, $result);
529 return $result;
533 * Makes sure the given project is valid. If it's not, this function will
534 * die().
535 * @return the project
537 function validate_project($project)
539 global $conf;
541 if (!in_array($project, array_keys($conf['projects']))) {
542 die('Invalid project');
544 return $project;
548 * Makes sure the given hash is valid. If it's not, this function will die().
549 * @return the hash
551 function validate_hash($hash)
553 if (!preg_match('/^[0-9a-z]{40}$/', $hash) && !preg_match('!^refs/(heads|tags)/[-_.0-9a-zA-Z]+$!', $hash) && $hash !== 'HEAD') {
554 die('Invalid hash');
557 return $hash;
561 * Custom error handler for ViewGit. The errors are pushed to $page['notices']
562 * and displayed by templates/header.php.
564 function vg_error_handler($errno, $errstr, $errfile, $errline)
566 global $page;
568 $mask = ini_get('error_reporting');
570 $class = 'error';
572 // If mask for this error is not enabled, return silently
573 if (!($errno & $mask)) {
574 return true;
577 // Remove any preceding path until viewgit's directory
578 $file = $errfile;
579 $file = strstr($file, 'viewgit/');
581 $message = "$file:$errline $errstr [$errno]";
583 switch ($errno) {
584 case E_ERROR:
585 $class = 'error';
586 break;
587 case E_WARNING:
588 $class = 'warning';
589 break;
590 case E_NOTICE:
591 case E_STRICT:
592 default:
593 $class = 'info';
594 break;
597 $page['notices'][] = array(
598 'message' => $message,
599 'class' => $class,
602 return true;