Add last commit message to index page.
[viewgit.git] / inc / functions.php
blob40a670fce5c5e185f062ebc48e2a480e1f4bafb0
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 function fix_encoding($in_str)
17 $cur_encoding = mb_detect_encoding($in_str) ;
18 if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8")) {
19 return $in_str;
20 } else {
21 return utf8_encode($in_str);
25 /**
26 * Format author's name & wrap it to links etc.
28 function format_author($author)
30 global $page;
32 if (isset($page['project'])) {
33 // FIXME 'h' - use only if available
34 return '<a href="'. makelink(array('a' => 'search', 'p' => $page['project'], 'h' => 'HEAD', 'st' => 'author', 's' => $author)) .'">'. htmlentities_wrapper($author) .'</a>';
35 } else {
36 return htmlentities_wrapper($author);
40 /**
41 * Formats "git diff" output into xhtml.
42 * @return array(array of filenames, xhtml)
44 function format_diff($text)
46 $files = array();
48 // match every "^diff --git a/<path> b/<path>$" line
49 foreach (explode("\n", $text) as $line) {
50 if (preg_match('#^diff --git a/(.*) b/(.*)$#', $line, $matches) > 0) {
51 $files[$matches[1]] = urlencode($matches[1]);
55 $text = htmlentities_wrapper($text);
57 $text = preg_replace(
58 array(
59 '/^(\+.*)$/m',
60 '/^(-.*)$/m',
61 '/^(@.*)$/m',
62 '/^([^d\+-@].*)$/m',
64 array(
65 '<span class="add">$1</span>',
66 '<span class="del">$1</span>',
67 '<span class="pos">$1</span>',
68 '<span class="etc">$1</span>',
70 $text);
71 $text = preg_replace_callback('#^diff --git a/(.*) b/(.*)$#m',
72 create_function(
73 '$m',
74 'return "<span class=\"diffline\"><a name=\"". urlencode($m[1]) ."\">diff --git a/$m[1] b/$m[2]</a></span>";'
76 $text);
78 return array($files, $text);
81 /**
82 * Get project information from config and git, name/description and HEAD
83 * commit info are returned in an array.
85 function get_project_info($name)
87 global $conf;
89 $info = $conf['projects'][$name];
90 $info['name'] = $name;
92 // If description is not set, read it from the repository's description
93 if (!isset($info['description'])) {
94 $info['description'] = file_get_contents($info['repo'] .'/description');
97 $headinfo = git_get_commit_info($name, 'HEAD');
98 $info['head_stamp'] = $headinfo['author_utcstamp'];
99 $info['head_datetime'] = gmstrftime($conf['datetime'], $headinfo['author_utcstamp']);
100 $info['head_hash'] = $headinfo['h'];
101 $info['head_tree'] = $headinfo['tree'];
102 $info['message'] = $headinfo['message'];
104 return $info;
107 function git_describe($project, $commit)
109 $output = run_git($project, "describe --always ". escapeshellarg($commit));
110 return $output[0];
114 * Get diff between given revisions as text.
116 function git_diff($project, $from, $to)
118 return join("\n", run_git($project, "diff \"$from..$to\""));
121 function git_diffstat($project, $commit, $commit_base = null)
123 if (is_null($commit_base)) {
124 $commit_base = "$commit^";
126 return join("\n", run_git($project, "diff --stat $commit_base..$commit"));
130 * Get array of changed paths for a commit.
132 function git_get_changed_paths($project, $hash = 'HEAD')
134 $result = array();
135 $affected_files = run_git($project, "show --pretty=\"format:\" --name-only $hash");
136 foreach ($affected_files as $file ) {
137 // The format above contains a blank line; Skip it.
138 if ($file == '') {
139 continue;
142 $output = run_git($project, "ls-tree $hash $file");
143 foreach ($output as $line) {
144 $parts = preg_split('/\s+/', $line, 4);
145 $result[] = array('name' => $parts[3], 'hash' => $parts[2]);
148 return $result;
152 * Get details of a commit: tree, parents, author/committer (name, mail, date), message
154 function git_get_commit_info($project, $hash = 'HEAD', $path = null)
156 global $conf;
158 $info = array();
159 $info['h_name'] = $hash;
160 $info['message_full'] = '';
161 $info['parents'] = array();
163 $extra = '';
164 if (isset($path)) {
165 $extra = '-- '. escapeshellarg($path);
168 $output = run_git($project, "rev-list --header --max-count=1 $hash $extra");
169 // tree <h>
170 // parent <h>
171 // author <name> "<"<mail>">" <stamp> <timezone>
172 // committer
173 // <empty>
174 // <message>
175 $pattern = '/^(author|committer) ([^<]+) <([^>]*)> ([0-9]+) (.*)$/';
176 foreach ($output as $line) {
177 if (substr($line, 0, 4) === 'tree') {
178 $info['tree'] = substr($line, 5);
180 // may be repeated multiple times for merge/octopus
181 elseif (substr($line, 0, 6) === 'parent') {
182 $info['parents'][] = substr($line, 7);
184 elseif (preg_match($pattern, $line, $matches) > 0) {
185 $info[$matches[1] .'_name'] = $matches[2];
186 $info[$matches[1] .'_mail'] = $matches[3];
187 $info[$matches[1] .'_stamp'] = $matches[4] + ((intval($matches[5]) / 100.0) * 3600);
188 $info[$matches[1] .'_timezone'] = $matches[5];
189 $info[$matches[1] .'_utcstamp'] = $matches[4];
191 if (isset($conf['mail_filter'])) {
192 $info[$matches[1] .'_mail'] = $conf['mail_filter']($info[$matches[1] .'_mail']);
195 // Lines starting with four spaces and empty lines after first such line are part of commit message
196 elseif (substr($line, 0, 4) === ' ' || (strlen($line) == 0 && isset($info['message']))) {
197 $info['message_full'] .= substr($line, 4) ."\n";
198 if (!isset($info['message'])) {
199 $info['message'] = substr($line, 4, $conf['commit_message_maxlen']);
200 $info['message_firstline'] = substr($line, 4);
203 elseif (preg_match('/^[0-9a-f]{40}$/', $line) > 0) {
204 $info['h'] = $line;
208 // This is a workaround for the unlikely situation where a commit does
209 // not have a message. Such a commit can be created with the following
210 // command:
211 // git commit --allow-empty -m '' --cleanup=verbatim
212 if (!array_key_exists('message', $info)) {
213 $info['message'] = '(no message)';
214 $info['message_firstline'] = '(no message)';
217 $info['author_datetime'] = gmstrftime($conf['datetime_full'], $info['author_utcstamp']);
218 $info['author_datetime_local'] = gmstrftime($conf['datetime_full'], $info['author_stamp']) .' '. $info['author_timezone'];
219 $info['committer_datetime'] = gmstrftime($conf['datetime_full'], $info['committer_utcstamp']);
220 $info['committer_datetime_local'] = gmstrftime($conf['datetime_full'], $info['committer_stamp']) .' '. $info['committer_timezone'];
222 return $info;
226 * Get list of heads (branches) for a project.
228 function git_get_heads($project)
230 $heads = array();
232 $output = run_git($project, 'show-ref --heads');
233 foreach ($output as $line) {
234 $fullname = substr($line, 41);
235 $tmp = explode('/', $fullname);
236 $name = array_pop($tmp);
237 $pre = array_pop($tmp);
238 if ($pre != 'heads')
240 $name = $pre . '/' . $name;
242 $heads[] = array('h' => substr($line, 0, 40), 'fullname' => "$fullname", 'name' => "$name");
245 return $heads;
249 * Get array containing path information for parts, starting from root_hash.
251 * @param root_hash commit/tree hash for the root tree
252 * @param path path
254 function git_get_path_info($project, $root_hash, $path)
256 if (strlen($path) > 0) {
257 $parts = explode('/', $path);
258 } else {
259 $parts = array();
262 $pathinfo = array();
264 $tid = $root_hash;
265 $pathinfo = array();
266 foreach ($parts as $p) {
267 $entry = git_ls_tree_part($project, $tid, $p);
268 if (is_null($entry)) {
269 die("Invalid path info: $path");
271 $pathinfo[] = $entry;
272 $tid = $entry['hash'];
275 return $pathinfo;
279 * Get revision list starting from given commit.
280 * @param skip how many hashes to skip from the beginning
281 * @param max_count number of commit hashes to return, or all if not given
282 * @param start revision to start from, or HEAD if not given
284 function git_get_rev_list($project, $skip = 0, $max_count = null, $start = 'HEAD')
286 $cmd = "rev-list ";
287 if ($skip != 0) {
288 $cmd .= "--skip=$skip ";
290 if (!is_null($max_count)) {
291 $cmd .= "--max-count=$max_count ";
293 $cmd .= $start;
295 return run_git($project, $cmd);
299 * Get list of tags for a project.
301 function git_get_tags($project)
303 $tags = array();
305 $output = run_git($project, 'show-ref --tags');
306 foreach ($output as $line) {
307 $fullname = substr($line, 41);
308 $tmp = explode('/', $fullname);
309 $name = array_pop($tmp);
310 $tags[] = array('h' => substr($line, 0, 40), 'fullname' => $fullname, 'name' => $name);
312 return $tags;
316 * Get information about objects in a tree.
317 * @param tree tree or commit hash
318 * @return list of arrays containing name, mode, type, hash
320 function git_ls_tree($project, $tree)
322 $entries = array();
323 $output = run_git($project, "ls-tree $tree");
324 // 100644 blob 493b7fc4296d64af45dac64bceac2d9a96c958c1 .gitignore
325 // 040000 tree 715c78b1011dc58106da2a1af2fe0aa4c829542f doc
326 foreach ($output as $line) {
327 $parts = preg_split('/\s+/', $line, 4);
328 $entries[] = array('name' => $parts[3], 'mode' => $parts[0], 'type' => $parts[1], 'hash' => $parts[2]);
331 return $entries;
335 * Get information about the given object in a tree, or null if not in the tree.
337 function git_ls_tree_part($project, $tree, $name)
339 $entries = git_ls_tree($project, $tree);
340 foreach ($entries as $entry) {
341 if ($entry['name'] === $name) {
342 return $entry;
345 return null;
349 * Get the ref list as dict: hash -> list of names.
350 * @param tags whether to show tags
351 * @param heads whether to show heads
352 * @param remotes whether to show remote heads, currently implies tags and heads too.
354 function git_ref_list($project, $tags = true, $heads = true, $remotes = true)
356 $cmd = "show-ref --dereference";
357 if (!$remotes) {
358 if ($tags) { $cmd .= " --tags"; }
359 if ($heads) { $cmd .= " --heads"; }
362 $result = array();
363 $output = run_git($project, $cmd);
364 foreach ($output as $line) {
365 // <hash> <ref>
366 $parts = explode(' ', $line, 2);
367 $name = str_replace(array('refs/', '^{}'), array('', ''), $parts[1]);
368 $result[$parts[0]][] = $name;
370 return $result;
374 * Find commits based on search type and string.
376 function git_search_commits($project, $branch, $type, $string)
378 // git log -sFOO
379 if ($type == 'change') {
380 $cmd = 'log -S'. escapeshellarg($string);
382 elseif ($type == 'commit') {
383 $cmd = 'log -i --grep='. escapeshellarg($string);
385 elseif ($type == 'author') {
386 $cmd = 'log -i --author='. escapeshellarg($string);
388 elseif ($type == 'committer') {
389 $cmd = 'log -i --committer='. escapeshellarg($string);
391 else {
392 die('Unsupported type');
394 $cmd .= ' '. $branch;
395 $lines = run_git($project, $cmd);
397 $result = array();
398 foreach ($lines as $line) {
399 if (preg_match('/^commit (.*?)$/', $line, $matches)) {
400 $result[] = $matches[1];
403 return $result;
407 * Get shortlog entries for the given project.
409 function handle_shortlog($project, $hash = 'HEAD', $page = 0)
411 global $conf;
413 $refs_by_hash = git_ref_list($project, true, true, $conf['shortlog_remote_labels']);
415 $result = array();
416 $revs = git_get_rev_list($project, $page * $conf['summary_shortlog'], $conf['summary_shortlog'], $hash);
417 foreach ($revs as $rev) {
418 $info = git_get_commit_info($project, $rev);
419 $refs = array();
420 if (in_array($rev, array_keys($refs_by_hash))) {
421 $refs = $refs_by_hash[$rev];
423 $result[] = array(
424 'author' => $info['author_name'],
425 'date' => gmstrftime($conf['datetime'], $info['author_utcstamp']),
426 'message' => $info['message'],
427 'commit_id' => $rev,
428 'tree' => $info['tree'],
429 'refs' => $refs,
432 #print_r($result);
433 #die();
435 return $result;
439 * Fetch tags data, newest first.
441 * @param limit maximum number of tags to return
443 function handle_tags($project, $limit = 0)
445 global $conf;
447 $tags = git_get_tags($project);
448 $result = array();
449 foreach ($tags as $tag) {
450 $info = git_get_commit_info($project, $tag['h']);
451 $result[] = array(
452 'stamp' => $info['author_utcstamp'],
453 'date' => gmstrftime($conf['datetime'], $info['author_utcstamp']),
454 'h' => $tag['h'],
455 'fullname' => $tag['fullname'],
456 'name' => $tag['name'],
460 // sort tags newest first
461 // aka. two more reasons to hate PHP (figuring those out is your homework:)
462 usort($result, create_function(
463 '$x, $y',
464 '$a = $x["stamp"]; $b = $y["stamp"]; return ($a == $b ? 0 : ($a > $b ? -1 : 1));'
467 // TODO optimize this some way, currently all tags are fetched when only a
468 // few are shown. The problem is that without fetching the commit info
469 // above, we can't sort using dates, only by tag name...
470 if ($limit > 0) {
471 $result = array_splice($result, 0, $limit);
474 return $result;
477 function htmlentities_wrapper($text)
479 return htmlentities(@iconv('UTF-8', 'UTF-8//IGNORE', $text), ENT_NOQUOTES, 'UTF-8');
482 function xmlentities_wrapper($text)
484 return str_replace(array('&', '<'), array('&#x26;', '&#x3C;'), @iconv('UTF-8', 'UTF-8//IGNORE', $text));
488 * Return a URL that contains the given parameters.
490 function makelink($dict)
492 $params = array();
493 foreach ($dict as $k => $v) {
494 $params[] = rawurlencode($k) .'='. str_replace('%2F', '/', rawurlencode($v));
496 if (count($params) > 0) {
497 return '?'. htmlentities_wrapper(join('&', $params));
499 return '';
503 * Obfuscate the e-mail address.
505 function obfuscate_mail($mail)
507 return str_replace(array('@', '.'), array(' at ', ' dot '), $mail);
511 * Used to format RSS item title and description.
513 * @param info commit info from git_get_commit_info()
515 function rss_item_format($format, $info)
517 return preg_replace(array(
518 '/{AUTHOR}/',
519 '/{AUTHOR_MAIL}/',
520 '/{SHORTLOG}/',
521 '/{LOG}/',
522 '/{COMMITTER}/',
523 '/{COMMITTER_MAIL}/',
524 '/{DIFFSTAT}/',
525 ), array(
526 htmlentities_wrapper($info['author_name']),
527 htmlentities_wrapper($info['author_mail']),
528 htmlentities_wrapper($info['message_firstline']),
529 htmlentities_wrapper($info['message_full']),
530 htmlentities_wrapper($info['committer_name']),
531 htmlentities_wrapper($info['committer_mail']),
532 htmlentities_wrapper(isset($info['diffstat']) ? $info['diffstat'] : ''),
533 ), $format);
536 function rss_pubdate($secs)
538 return gmdate('D, d M Y H:i:s O', $secs);
542 * Executes a git command in the project repo.
543 * @return array of output lines
545 function run_git($project, $command)
547 global $conf;
549 $output = array();
550 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
551 $ret = 0;
552 exec($cmd, $output, $ret);
553 if ($conf['debug_command_trace']) {
554 static $count = 0;
555 $count++;
556 trigger_error("[$count]\$ $cmd [exit $ret]");
558 //if ($ret != 0) { die('FATAL: exec() for git failed, is the path properly configured?'); }
559 return $output;
563 * Executes a git command in the project repo, sending output directly to the
564 * client.
566 function run_git_passthru($project, $command)
568 global $conf;
570 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
571 $result = 0;
572 passthru($cmd, $result);
573 return $result;
577 * Makes sure the given project is valid. If it's not, this function will
578 * die().
579 * @return the project
581 function validate_project($project)
583 global $conf;
585 if (!in_array($project, array_keys($conf['projects']))) {
586 die('Invalid project');
588 return $project;
592 * Makes sure the given hash is valid. If it's not, this function will die().
593 * @return the hash
595 function validate_hash($hash)
597 if (!preg_match('/^[0-9a-z]{40}$/', $hash) && !preg_match('!^refs/(heads|tags)/[-_.0-9a-zA-Z/]+$!', $hash) && $hash !== 'HEAD') {
598 die('Invalid hash');
601 return $hash;
605 * Custom error handler for ViewGit. The errors are pushed to $page['notices']
606 * and displayed by templates/header.php.
608 function vg_error_handler($errno, $errstr, $errfile, $errline)
610 global $page;
612 $mask = ini_get('error_reporting');
614 $class = 'error';
616 // If mask for this error is not enabled, return silently
617 if (!($errno & $mask)) {
618 return true;
621 // Remove any preceding path until viewgit's directory
622 $file = $errfile;
623 $file = strstr($file, 'viewgit/');
625 $message = "$file:$errline $errstr [$errno]";
627 switch ($errno) {
628 case E_ERROR:
629 $class = 'error';
630 break;
631 case E_WARNING:
632 $class = 'warning';
633 break;
634 case E_NOTICE:
635 case E_STRICT:
636 default:
637 $class = 'info';
638 break;
641 $page['notices'][] = array(
642 'message' => $message,
643 'class' => $class,
646 return true;