3 * Functions used by ViewGit.
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")) {
21 return utf8_encode($in_str);
26 * Format author's name & wrap it to links etc.
28 function format_author($author)
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>';
36 return htmlentities_wrapper($author);
41 * Formats "git diff" output into xhtml.
42 * @return array(array of filenames, xhtml)
44 function format_diff($text)
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);
65 '<span class="add">$1</span>',
66 '<span class="del">$1</span>',
67 '<span class="pos">$1</span>',
68 '<span class="etc">$1</span>',
71 $text = preg_replace_callback('#^diff --git a/(.*) b/(.*)$#m',
74 'return "<span class=\"diffline\"><a name=\"". urlencode($m[1]) ."\">diff --git a/$m[1] b/$m[2]</a></span>";'
78 return array($files, $text);
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)
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'];
106 function git_describe($project, $commit)
108 $output = run_git($project, "describe --always ". escapeshellarg($commit));
113 * Get diff between given revisions as text.
115 function git_diff($project, $from, $to)
117 return join("\n", run_git($project, "diff \"$from..$to\""));
120 function git_diffstat($project, $commit, $commit_base = null)
122 if (is_null($commit_base)) {
123 $commit_base = "$commit^";
125 return join("\n", run_git($project, "diff --stat $commit_base..$commit"));
129 * Get array of changed paths for a commit.
131 function git_get_changed_paths($project, $hash = 'HEAD')
134 $affected_files = run_git($project, "show --pretty=\"format:\" --name-only $hash");
135 foreach ($affected_files as $file ) {
136 // The format above contains a blank line; Skip it.
141 $output = run_git($project, "ls-tree $hash $file");
142 foreach ($output as $line) {
143 $parts = preg_split('/\s+/', $line, 4);
144 $result[] = array('name' => $parts[3], 'hash' => $parts[2]);
151 * Get details of a commit: tree, parents, author/committer (name, mail, date), message
153 function git_get_commit_info($project, $hash = 'HEAD', $path = null)
158 $info['h_name'] = $hash;
159 $info['message_full'] = '';
160 $info['parents'] = array();
164 $extra = '-- '. escapeshellarg($path);
167 $output = run_git($project, "rev-list --header --max-count=1 $hash $extra");
170 // author <name> "<"<mail>">" <stamp> <timezone>
174 $pattern = '/^(author|committer) ([^<]+) <([^>]*)> ([0-9]+) (.*)$/';
175 foreach ($output as $line) {
176 if (substr($line, 0, 4) === 'tree') {
177 $info['tree'] = substr($line, 5);
179 // may be repeated multiple times for merge/octopus
180 elseif (substr($line, 0, 6) === 'parent') {
181 $info['parents'][] = substr($line, 7);
183 elseif (preg_match($pattern, $line, $matches) > 0) {
184 $info[$matches[1] .'_name'] = $matches[2];
185 $info[$matches[1] .'_mail'] = $matches[3];
186 $info[$matches[1] .'_stamp'] = $matches[4] +
((intval($matches[5]) / 100.0) * 3600);
187 $info[$matches[1] .'_timezone'] = $matches[5];
188 $info[$matches[1] .'_utcstamp'] = $matches[4];
190 if (isset($conf['mail_filter'])) {
191 $info[$matches[1] .'_mail'] = $conf['mail_filter']($info[$matches[1] .'_mail']);
194 // Lines starting with four spaces and empty lines after first such line are part of commit message
195 elseif (substr($line, 0, 4) === ' ' ||
(strlen($line) == 0 && isset($info['message']))) {
196 $info['message_full'] .= substr($line, 4) ."\n";
197 if (!isset($info['message'])) {
198 $info['message'] = substr($line, 4, $conf['commit_message_maxlen']);
199 $info['message_firstline'] = substr($line, 4);
202 elseif (preg_match('/^[0-9a-f]{40}$/', $line) > 0) {
207 // This is a workaround for the unlikely situation where a commit does
208 // not have a message. Such a commit can be created with the following
210 // git commit --allow-empty -m '' --cleanup=verbatim
211 if (!array_key_exists('message', $info)) {
212 $info['message'] = '(no message)';
213 $info['message_firstline'] = '(no message)';
216 $info['author_datetime'] = gmstrftime($conf['datetime_full'], $info['author_utcstamp']);
217 $info['author_datetime_local'] = gmstrftime($conf['datetime_full'], $info['author_stamp']) .' '. $info['author_timezone'];
218 $info['committer_datetime'] = gmstrftime($conf['datetime_full'], $info['committer_utcstamp']);
219 $info['committer_datetime_local'] = gmstrftime($conf['datetime_full'], $info['committer_stamp']) .' '. $info['committer_timezone'];
225 * Get list of heads (branches) for a project.
227 function git_get_heads($project)
231 $output = run_git($project, 'show-ref --heads');
232 foreach ($output as $line) {
233 $fullname = substr($line, 41);
234 $tmp = explode('/', $fullname);
235 $name = array_pop($tmp);
236 $heads[] = array('h' => substr($line, 0, 40), 'fullname' => "$fullname", 'name' => "$name");
243 * Get array containing path information for parts, starting from root_hash.
245 * @param root_hash commit/tree hash for the root tree
248 function git_get_path_info($project, $root_hash, $path)
250 if (strlen($path) > 0) {
251 $parts = explode('/', $path);
260 foreach ($parts as $p) {
261 $entry = git_ls_tree_part($project, $tid, $p);
262 if (is_null($entry)) {
263 die("Invalid path info: $path");
265 $pathinfo[] = $entry;
266 $tid = $entry['hash'];
273 * Get revision list starting from given commit.
274 * @param skip how many hashes to skip from the beginning
275 * @param max_count number of commit hashes to return, or all if not given
276 * @param start revision to start from, or HEAD if not given
278 function git_get_rev_list($project, $skip = 0, $max_count = null, $start = 'HEAD')
282 $cmd .= "--skip=$skip ";
284 if (!is_null($max_count)) {
285 $cmd .= "--max-count=$max_count ";
289 return run_git($project, $cmd);
293 * Get list of tags for a project.
295 function git_get_tags($project)
299 $output = run_git($project, 'show-ref --tags');
300 foreach ($output as $line) {
301 $fullname = substr($line, 41);
302 $tmp = explode('/', $fullname);
303 $name = array_pop($tmp);
304 $tags[] = array('h' => substr($line, 0, 40), 'fullname' => $fullname, 'name' => $name);
310 * Get information about objects in a tree.
311 * @param tree tree or commit hash
312 * @return list of arrays containing name, mode, type, hash
314 function git_ls_tree($project, $tree)
317 $output = run_git($project, "ls-tree $tree");
318 // 100644 blob 493b7fc4296d64af45dac64bceac2d9a96c958c1 .gitignore
319 // 040000 tree 715c78b1011dc58106da2a1af2fe0aa4c829542f doc
320 foreach ($output as $line) {
321 $parts = preg_split('/\s+/', $line, 4);
322 $entries[] = array('name' => $parts[3], 'mode' => $parts[0], 'type' => $parts[1], 'hash' => $parts[2]);
329 * Get information about the given object in a tree, or null if not in the tree.
331 function git_ls_tree_part($project, $tree, $name)
333 $entries = git_ls_tree($project, $tree);
334 foreach ($entries as $entry) {
335 if ($entry['name'] === $name) {
343 * Get the ref list as dict: hash -> list of names.
344 * @param tags whether to show tags
345 * @param heads whether to show heads
346 * @param remotes whether to show remote heads, currently implies tags and heads too.
348 function git_ref_list($project, $tags = true, $heads = true, $remotes = true)
350 $cmd = "show-ref --dereference";
352 if ($tags) { $cmd .= " --tags"; }
353 if ($heads) { $cmd .= " --heads"; }
357 $output = run_git($project, $cmd);
358 foreach ($output as $line) {
360 $parts = explode(' ', $line, 2);
361 $name = str_replace(array('refs/', '^{}'), array('', ''), $parts[1]);
362 $result[$parts[0]][] = $name;
368 * Find commits based on search type and string.
370 function git_search_commits($project, $branch, $type, $string)
373 if ($type == 'change') {
374 $cmd = 'log -S'. escapeshellarg($string);
376 elseif ($type == 'commit') {
377 $cmd = 'log -i --grep='. escapeshellarg($string);
379 elseif ($type == 'author') {
380 $cmd = 'log -i --author='. escapeshellarg($string);
382 elseif ($type == 'committer') {
383 $cmd = 'log -i --committer='. escapeshellarg($string);
386 die('Unsupported type');
388 $cmd .= ' '. $branch;
389 $lines = run_git($project, $cmd);
392 foreach ($lines as $line) {
393 if (preg_match('/^commit (.*?)$/', $line, $matches)) {
394 $result[] = $matches[1];
401 * Get shortlog entries for the given project.
403 function handle_shortlog($project, $hash = 'HEAD', $page = 0)
407 $refs_by_hash = git_ref_list($project, true, true, $conf['shortlog_remote_labels']);
410 $revs = git_get_rev_list($project, $page * $conf['summary_shortlog'], $conf['summary_shortlog'], $hash);
411 foreach ($revs as $rev) {
412 $info = git_get_commit_info($project, $rev);
414 if (in_array($rev, array_keys($refs_by_hash))) {
415 $refs = $refs_by_hash[$rev];
418 'author' => $info['author_name'],
419 'date' => gmstrftime($conf['datetime'], $info['author_utcstamp']),
420 'message' => $info['message'],
422 'tree' => $info['tree'],
433 * Fetch tags data, newest first.
435 * @param limit maximum number of tags to return
437 function handle_tags($project, $limit = 0)
441 $tags = git_get_tags($project);
443 foreach ($tags as $tag) {
444 $info = git_get_commit_info($project, $tag['h']);
446 'stamp' => $info['author_utcstamp'],
447 'date' => gmstrftime($conf['datetime'], $info['author_utcstamp']),
449 'fullname' => $tag['fullname'],
450 'name' => $tag['name'],
454 // sort tags newest first
455 // aka. two more reasons to hate PHP (figuring those out is your homework:)
456 usort($result, create_function(
458 '$a = $x["stamp"]; $b = $y["stamp"]; return ($a == $b ? 0 : ($a > $b ? -1 : 1));'
461 // TODO optimize this some way, currently all tags are fetched when only a
462 // few are shown. The problem is that without fetching the commit info
463 // above, we can't sort using dates, only by tag name...
465 $result = array_splice($result, 0, $limit);
471 function htmlentities_wrapper($text)
473 return htmlentities(@iconv
('UTF-8', 'UTF-8//IGNORE', $text), ENT_NOQUOTES
, 'UTF-8');
476 function xmlentities_wrapper($text)
478 return str_replace(array('&', '<'), array('&', '<'), @iconv
('UTF-8', 'UTF-8//IGNORE', $text));
482 * Return a URL that contains the given parameters.
484 function makelink($dict)
487 foreach ($dict as $k => $v) {
488 $params[] = rawurlencode($k) .'='. str_replace('%2F', '/', rawurlencode($v));
490 if (count($params) > 0) {
491 return '?'. htmlentities_wrapper(join('&', $params));
497 * Obfuscate the e-mail address.
499 function obfuscate_mail($mail)
501 return str_replace(array('@', '.'), array(' at ', ' dot '), $mail);
505 * Used to format RSS item title and description.
507 * @param info commit info from git_get_commit_info()
509 function rss_item_format($format, $info)
511 return preg_replace(array(
517 '/{COMMITTER_MAIL}/',
520 htmlentities_wrapper($info['author_name']),
521 htmlentities_wrapper($info['author_mail']),
522 htmlentities_wrapper($info['message_firstline']),
523 htmlentities_wrapper($info['message_full']),
524 htmlentities_wrapper($info['committer_name']),
525 htmlentities_wrapper($info['committer_mail']),
526 htmlentities_wrapper(isset($info['diffstat']) ?
$info['diffstat'] : ''),
530 function rss_pubdate($secs)
532 return gmdate('D, d M Y H:i:s O', $secs);
536 * Executes a git command in the project repo.
537 * @return array of output lines
539 function run_git($project, $command)
544 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
546 exec($cmd, $output, $ret);
547 if ($conf['debug_command_trace']) {
550 trigger_error("[$count]\$ $cmd [exit $ret]");
552 //if ($ret != 0) { die('FATAL: exec() for git failed, is the path properly configured?'); }
557 * Executes a git command in the project repo, sending output directly to the
560 function run_git_passthru($project, $command)
564 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
566 passthru($cmd, $result);
571 * Makes sure the given project is valid. If it's not, this function will
573 * @return the project
575 function validate_project($project)
579 if (!in_array($project, array_keys($conf['projects']))) {
580 die('Invalid project');
586 * Makes sure the given hash is valid. If it's not, this function will die().
589 function validate_hash($hash)
591 if (!preg_match('/^[0-9a-z]{40}$/', $hash) && !preg_match('!^refs/(heads|tags)/[-_.0-9a-zA-Z]+$!', $hash) && $hash !== 'HEAD') {
599 * Custom error handler for ViewGit. The errors are pushed to $page['notices']
600 * and displayed by templates/header.php.
602 function vg_error_handler($errno, $errstr, $errfile, $errline)
606 $mask = ini_get('error_reporting');
610 // If mask for this error is not enabled, return silently
611 if (!($errno & $mask)) {
615 // Remove any preceding path until viewgit's directory
617 $file = strstr($file, 'viewgit/');
619 $message = "$file:$errline $errstr [$errno]";
635 $page['notices'][] = array(
636 'message' => $message,