Retain empty lines in commit messages.
[viewgit.git] / inc / functions.php
blob09f8055c7524fb6f18b44a2311dd000a1fdae02a
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('/tmp/viewgit.log', strftime('%H:%M:%S') ." $_SERVER[REMOTE_ADDR]:$_SERVER[REMOTE_PORT] $msg\n", FILE_APPEND);
15 /**
16 * Formats "git diff" output into xhtml.
17 * @return array(array of filenames, xhtml)
19 function format_diff($text)
21 $files = array();
23 // match every "^diff --git a/<path> b/<path>$" line
24 foreach (explode("\n", $text) as $line) {
25 if (preg_match('#^diff --git a/(.*) b/(.*)$#', $line, $matches) > 0) {
26 $files[$matches[1]] = urlencode($matches[1]);
30 $text = htmlentities($text);
32 $text = preg_replace(
33 array(
34 '/^(\+.*)$/m',
35 '/^(-.*)$/m',
36 '/^(@.*)$/m',
37 '/^([^d\+-@].*)$/m',
39 array(
40 '<span class="add">$1</span>',
41 '<span class="del">$1</span>',
42 '<span class="pos">$1</span>',
43 '<span class="etc">$1</span>',
45 $text);
46 $text = preg_replace_callback('#^diff --git a/(.*) b/(.*)$#m',
47 create_function(
48 '$m',
49 'return "<span class=\"diffline\"><a name=\"". urlencode($m[1]) ."\">diff --git a/$m[1] b/$m[2]</a></span>";'
51 $text);
53 return array($files, $text);
56 /**
57 * Get project information from config and git, name/description and HEAD
58 * commit info are returned in an array.
60 function get_project_info($name)
62 global $conf;
64 $info = $conf['projects'][$name];
65 $info['name'] = $name;
66 $info['description'] = file_get_contents($info['repo'] .'/description');
68 $headinfo = git_get_commit_info($name, 'HEAD');
69 $info['head_stamp'] = $headinfo['author_utcstamp'];
70 $info['head_datetime'] = strftime($conf['datetime'], $headinfo['author_utcstamp']);
71 $info['head_hash'] = $headinfo['h'];
72 $info['head_tree'] = $headinfo['tree'];
74 return $info;
77 function git_diffstat($project, $commit, $commit_base = null)
79 if (is_null($commit_base)) {
80 $commit_base = "$commit^";
82 return join("\n", run_git($project, "git diff --stat $commit_base..$commit"));
85 /**
86 * Get details of a commit: tree, parents, author/committer (name, mail, date), message
88 function git_get_commit_info($project, $hash = 'HEAD')
90 global $conf;
92 $info = array();
93 $info['h_name'] = $hash;
94 $info['message_full'] = '';
95 $info['parents'] = array();
97 $output = run_git($project, "git rev-list --header --max-count=1 $hash");
98 // tree <h>
99 // parent <h>
100 // author <name> "<"<mail>">" <stamp> <timezone>
101 // committer
102 // <empty>
103 // <message>
104 $pattern = '/^(author|committer) ([^<]+) <([^>]*)> ([0-9]+) (.*)$/';
105 foreach ($output as $line) {
106 if (substr($line, 0, 4) === 'tree') {
107 $info['tree'] = substr($line, 5);
109 // may be repeated multiple times for merge/octopus
110 elseif (substr($line, 0, 6) === 'parent') {
111 $info['parents'][] = substr($line, 7);
113 elseif (preg_match($pattern, $line, $matches) > 0) {
114 $info[$matches[1] .'_name'] = $matches[2];
115 $info[$matches[1] .'_mail'] = $matches[3];
116 $info[$matches[1] .'_stamp'] = $matches[4];
117 $info[$matches[1] .'_timezone'] = $matches[5];
118 $info[$matches[1] .'_utcstamp'] = $matches[4] - ((intval($matches[5]) / 100.0) * 3600);
120 if (isset($conf['mail_filter'])) {
121 $info[$matches[1] .'_mail'] = $conf['mail_filter']($info[$matches[1] .'_mail']);
124 // Lines starting with four spaces and empty lines after first such line are part of commit message
125 elseif (substr($line, 0, 4) === ' ' || (strlen($line) == 0 && isset($info['message']))) {
126 $info['message_full'] .= substr($line, 4) ."\n";
127 if (!isset($info['message'])) {
128 $info['message'] = substr($line, 4, $conf['commit_message_maxlen']);
129 $info['message_firstline'] = substr($line, 4);
132 elseif (preg_match('/^[0-9a-f]{40}$/', $line) > 0) {
133 $info['h'] = $line;
137 return $info;
141 * Get list of heads (branches) for a project.
143 function git_get_heads($project)
145 $heads = array();
147 $output = run_git($project, 'git show-ref --heads');
148 foreach ($output as $line) {
149 $fullname = substr($line, 41);
150 $name = array_pop(explode('/', $fullname));
151 $heads[] = array('h' => substr($line, 0, 40), 'fullname' => "$fullname", 'name' => "$name");
154 return $heads;
158 * Get array containing path information for parts, starting from root_hash.
160 * @param root_hash commit/tree hash for the root tree
161 * @param path path
163 function git_get_path_info($project, $root_hash, $path)
165 if (strlen($path) > 0) {
166 $parts = explode('/', $path);
167 } else {
168 $parts = array();
171 $pathinfo = array();
173 $tid = $root_hash;
174 $pathinfo = array();
175 foreach ($parts as $p) {
176 $entry = git_ls_tree_part($project, $tid, $p);
177 if (is_null($entry)) {
178 die("Invalid path info: $path");
180 $pathinfo[] = $entry;
181 $tid = $entry['hash'];
184 return $pathinfo;
188 * Get revision list starting from given commit.
189 * @param max_count number of commit hashes to return, or all if not given
190 * @param start revision to start from, or HEAD if not given
192 function git_get_rev_list($project, $max_count = null, $start = 'HEAD')
194 $cmd = "git rev-list $start";
195 if (!is_null($max_count)) {
196 $cmd = "git rev-list --max-count=$max_count $start";
199 return run_git($project, $cmd);
203 * Get list of tags for a project.
205 function git_get_tags($project)
207 $tags = array();
209 $output = run_git($project, 'git show-ref --tags');
210 foreach ($output as $line) {
211 $fullname = substr($line, 41);
212 $name = array_pop(explode('/', $fullname));
213 $tags[] = array('h' => substr($line, 0, 40), 'fullname' => $fullname, 'name' => $name);
215 return $tags;
219 * Get information about objects in a tree.
220 * @param tree tree or commit hash
221 * @return list of arrays containing name, mode, type, hash
223 function git_ls_tree($project, $tree)
225 $entries = array();
226 $output = run_git($project, "git ls-tree $tree");
227 // 100644 blob 493b7fc4296d64af45dac64bceac2d9a96c958c1 .gitignore
228 // 040000 tree 715c78b1011dc58106da2a1af2fe0aa4c829542f doc
229 foreach ($output as $line) {
230 $parts = preg_split('/\s+/', $line, 4);
231 $entries[] = array('name' => $parts[3], 'mode' => $parts[0], 'type' => $parts[1], 'hash' => $parts[2]);
234 return $entries;
238 * Get information about the given object in a tree, or null if not in the tree.
240 function git_ls_tree_part($project, $tree, $name)
242 $entries = git_ls_tree($project, $tree);
243 foreach ($entries as $entry) {
244 if ($entry['name'] === $name) {
245 return $entry;
248 return null;
252 * Get the ref list as dict: hash -> list of names.
253 * @param tags whether to show tags
254 * @param heads whether to show heads
255 * @param remotes whether to show remote heads, currently implies tags and heads too.
257 function git_ref_list($project, $tags = true, $heads = true, $remotes = true)
259 $cmd = "git show-ref --dereference";
260 if (!$remotes) {
261 if ($tags) { $cmd .= " --tags"; }
262 if ($heads) { $cmd .= " --heads"; }
265 $result = array();
266 $output = run_git($project, $cmd);
267 foreach ($output as $line) {
268 // <hash> <ref>
269 $parts = explode(' ', $line, 2);
270 $name = str_replace(array('refs/', '^{}'), array('', ''), $parts[1]);
271 $result[$parts[0]][] = $name;
273 return $result;
277 * Get shortlog entries for the given project.
279 function handle_shortlog($project, $hash = 'HEAD')
281 global $conf;
283 $refs_by_hash = git_ref_list($project, true, true, $conf['shortlog_remote_labels']);
285 $result = array();
286 $revs = git_get_rev_list($project, $conf['summary_shortlog'], $hash);
287 foreach ($revs as $rev) {
288 $info = git_get_commit_info($project, $rev);
289 $refs = array();
290 if (in_array($rev, array_keys($refs_by_hash))) {
291 $refs = $refs_by_hash[$rev];
293 $result[] = array(
294 'author' => $info['author_name'],
295 'date' => strftime($conf['datetime'], $info['author_utcstamp']),
296 'message' => $info['message'],
297 'commit_id' => $rev,
298 'tree' => $info['tree'],
299 'refs' => $refs,
302 #print_r($result);
303 #die();
305 return $result;
309 * Fetch tags data, newest first.
311 * @param limit maximum number of tags to return
313 function handle_tags($project, $limit = 0)
315 global $conf;
317 $tags = git_get_tags($project);
318 $result = array();
319 foreach ($tags as $tag) {
320 $info = git_get_commit_info($project, $tag['h']);
321 $result[] = array(
322 'stamp' => $info['author_utcstamp'],
323 'date' => strftime($conf['datetime'], $info['author_utcstamp']),
324 'h' => $tag['h'],
325 'fullname' => $tag['fullname'],
326 'name' => $tag['name'],
330 // sort tags newest first
331 // aka. two more reasons to hate PHP (figuring those out is your homework:)
332 usort($result, create_function(
333 '$x, $y',
334 '$a = $x["stamp"]; $b = $y["stamp"]; return ($a == $b ? 0 : ($a > $b ? -1 : 1));'
337 // TODO optimize this some way, currently all tags are fetched when only a
338 // few are shown. The problem is that without fetching the commit info
339 // above, we can't sort using dates, only by tag name...
340 if ($limit > 0) {
341 $result = array_splice($result, 0, $limit);
344 return $result;
348 * Return a URL that contains the given parameters.
350 function makelink($dict)
352 $params = array();
353 foreach ($dict as $k => $v) {
354 $params[] = rawurlencode($k) .'='. str_replace('%2F', '/', rawurlencode($v));
356 if (count($params) > 0) {
357 return '?'. htmlentities(join('&', $params));
359 return '';
363 * Obfuscate the e-mail address.
365 function obfuscate_mail($mail)
367 return str_replace(array('@', '.'), array(' at ', ' dot '), $mail);
371 * Used to format RSS item title and description.
373 * @param info commit info from git_get_commit_info()
375 function rss_item_format($format, $info)
377 return preg_replace(array(
378 '/{AUTHOR}/',
379 '/{AUTHOR_MAIL}/',
380 '/{SHORTLOG}/',
381 '/{LOG}/',
382 '/{COMMITTER}/',
383 '/{COMMITTER_MAIL}/',
384 '/{DIFFSTAT}/',
385 ), array(
386 $info['author_name'],
387 $info['author_mail'],
388 $info['message_firstline'],
389 htmlentities($info['message_full']),
390 $info['committer_name'],
391 $info['committer_mail'],
392 isset($info['diffstat']) ? $info['diffstat'] : '',
393 ), $format);
396 function rss_pubdate($secs)
398 return date('D, d M Y H:i:s O', $secs);
402 * Executes a git command in the project repo.
403 * @return array of output lines
405 function run_git($project, $command)
407 global $conf;
409 $output = array();
410 $cmd = "GIT_DIR=". $conf['projects'][$project]['repo'] ." $command";
411 exec($cmd, &$output);
412 return $output;
416 * Executes a git command in the project repo, sending output directly to the
417 * client.
419 function run_git_passthru($project, $command)
421 global $conf;
423 $cmd = "GIT_DIR=". $conf['projects'][$project]['repo'] ." $command";
424 $result = 0;
425 passthru($cmd, &$result);
426 return $result;
430 * Makes sure the given project is valid. If it's not, this function will
431 * die().
432 * @return the project
434 function validate_project($project)
436 global $conf;
438 if (!in_array($project, array_keys($conf['projects']))) {
439 die('Invalid project');
441 return $project;
445 * Makes sure the given hash is valid. If it's not, this function will die().
446 * @return the hash
448 function validate_hash($hash)
450 if (!preg_match('/^[0-9a-z]{40}$/', $hash) && !preg_match('!^refs/(heads|tags)/[-.0-9a-z]+$!', $hash) && $hash !== 'HEAD') {
451 die('Invalid hash');
454 return $hash;