CSS cleanup.
[viewgit.git] / inc / functions.php
blob2470491ca07650e824182575cc98e2604e5352bf
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 elseif (substr($line, 0, 4) === ' ') {
125 $info['message_full'] .= substr($line, 4) ."\n";
126 if (!isset($info['message'])) {
127 $info['message'] = substr($line, 4, $conf['commit_message_maxlen']);
128 $info['message_firstline'] = substr($line, 4);
131 elseif (preg_match('/^[0-9a-f]{40}$/', $line) > 0) {
132 $info['h'] = $line;
136 return $info;
140 * Get list of heads (branches) for a project.
142 function git_get_heads($project)
144 $heads = array();
146 $output = run_git($project, 'git show-ref --heads');
147 foreach ($output as $line) {
148 $fullname = substr($line, 41);
149 $name = array_pop(explode('/', $fullname));
150 $heads[] = array('h' => substr($line, 0, 40), 'fullname' => "$fullname", 'name' => "$name");
153 return $heads;
157 * Get array containing path information for parts, starting from root_hash.
159 * @param root_hash commit/tree hash for the root tree
160 * @param path path
162 function git_get_path_info($project, $root_hash, $path)
164 if (strlen($path) > 0) {
165 $parts = explode('/', $path);
166 } else {
167 $parts = array();
170 $pathinfo = array();
172 $tid = $root_hash;
173 $pathinfo = array();
174 foreach ($parts as $p) {
175 $entry = git_ls_tree_part($project, $tid, $p);
176 if (is_null($entry)) {
177 die("Invalid path info: $path");
179 $pathinfo[] = $entry;
180 $tid = $entry['hash'];
183 return $pathinfo;
187 * Get revision list starting from given commit.
188 * @param max_count number of commit hashes to return, or all if not given
189 * @param start revision to start from, or HEAD if not given
191 function git_get_rev_list($project, $max_count = null, $start = 'HEAD')
193 $cmd = "git rev-list $start";
194 if (!is_null($max_count)) {
195 $cmd = "git rev-list --max-count=$max_count $start";
198 return run_git($project, $cmd);
202 * Get list of tags for a project.
204 function git_get_tags($project)
206 $tags = array();
208 $output = run_git($project, 'git show-ref --tags');
209 foreach ($output as $line) {
210 $fullname = substr($line, 41);
211 $name = array_pop(explode('/', $fullname));
212 $tags[] = array('h' => substr($line, 0, 40), 'fullname' => $fullname, 'name' => $name);
214 return $tags;
218 * Get information about objects in a tree.
219 * @param tree tree or commit hash
220 * @return list of arrays containing name, mode, type, hash
222 function git_ls_tree($project, $tree)
224 $entries = array();
225 $output = run_git($project, "git ls-tree $tree");
226 // 100644 blob 493b7fc4296d64af45dac64bceac2d9a96c958c1 .gitignore
227 // 040000 tree 715c78b1011dc58106da2a1af2fe0aa4c829542f doc
228 foreach ($output as $line) {
229 $parts = preg_split('/\s+/', $line, 4);
230 $entries[] = array('name' => $parts[3], 'mode' => $parts[0], 'type' => $parts[1], 'hash' => $parts[2]);
233 return $entries;
237 * Get information about the given object in a tree, or null if not in the tree.
239 function git_ls_tree_part($project, $tree, $name)
241 $entries = git_ls_tree($project, $tree);
242 foreach ($entries as $entry) {
243 if ($entry['name'] === $name) {
244 return $entry;
247 return null;
251 * Get the ref list as dict: hash -> list of names.
252 * @param tags whether to show tags
253 * @param heads whether to show heads
254 * @param remotes whether to show remote heads, currently implies tags and heads too.
256 function git_ref_list($project, $tags = true, $heads = true, $remotes = true)
258 $cmd = "git show-ref --dereference";
259 if (!$remotes) {
260 if ($tags) { $cmd .= " --tags"; }
261 if ($heads) { $cmd .= " --heads"; }
264 $result = array();
265 $output = run_git($project, $cmd);
266 foreach ($output as $line) {
267 // <hash> <ref>
268 $parts = explode(' ', $line, 2);
269 $name = str_replace(array('refs/', '^{}'), array('', ''), $parts[1]);
270 $result[$parts[0]][] = $name;
272 return $result;
276 * Get shortlog entries for the given project.
278 function handle_shortlog($project, $hash = 'HEAD')
280 global $conf;
282 $refs_by_hash = git_ref_list($project, true, true, $conf['shortlog_remote_labels']);
284 $result = array();
285 $revs = git_get_rev_list($project, $conf['summary_shortlog'], $hash);
286 foreach ($revs as $rev) {
287 $info = git_get_commit_info($project, $rev);
288 $refs = array();
289 if (in_array($rev, array_keys($refs_by_hash))) {
290 $refs = $refs_by_hash[$rev];
292 $result[] = array(
293 'author' => $info['author_name'],
294 'date' => strftime($conf['datetime'], $info['author_utcstamp']),
295 'message' => $info['message'],
296 'commit_id' => $rev,
297 'tree' => $info['tree'],
298 'refs' => $refs,
301 #print_r($result);
302 #die();
304 return $result;
308 * Fetch tags data, newest first.
310 * @param limit maximum number of tags to return
312 function handle_tags($project, $limit = 0)
314 global $conf;
316 $tags = git_get_tags($project);
317 $result = array();
318 foreach ($tags as $tag) {
319 $info = git_get_commit_info($project, $tag['h']);
320 $result[] = array(
321 'stamp' => $info['author_utcstamp'],
322 'date' => strftime($conf['datetime'], $info['author_utcstamp']),
323 'h' => $tag['h'],
324 'fullname' => $tag['fullname'],
325 'name' => $tag['name'],
329 // sort tags newest first
330 // aka. two more reasons to hate PHP (figuring those out is your homework:)
331 usort($result, create_function(
332 '$x, $y',
333 '$a = $x["stamp"]; $b = $y["stamp"]; return ($a == $b ? 0 : ($a > $b ? -1 : 1));'
336 // TODO optimize this some way, currently all tags are fetched when only a
337 // few are shown. The problem is that without fetching the commit info
338 // above, we can't sort using dates, only by tag name...
339 if ($limit > 0) {
340 $result = array_splice($result, 0, $limit);
343 return $result;
347 * Return a URL that contains the given parameters.
349 function makelink($dict)
351 $params = array();
352 foreach ($dict as $k => $v) {
353 $params[] = rawurlencode($k) .'='. str_replace('%2F', '/', rawurlencode($v));
355 if (count($params) > 0) {
356 return '?'. htmlentities(join('&', $params));
358 return '';
362 * Obfuscate the e-mail address.
364 function obfuscate_mail($mail)
366 return str_replace(array('@', '.'), array(' at ', ' dot '), $mail);
370 * Used to format RSS item title and description.
372 * @param info commit info from git_get_commit_info()
374 function rss_item_format($format, $info)
376 return preg_replace(array(
377 '/{AUTHOR}/',
378 '/{AUTHOR_MAIL}/',
379 '/{SHORTLOG}/',
380 '/{LOG}/',
381 '/{COMMITTER}/',
382 '/{COMMITTER_MAIL}/',
383 '/{DIFFSTAT}/',
384 ), array(
385 $info['author_name'],
386 $info['author_mail'],
387 $info['message_firstline'],
388 $info['message_full'],
389 $info['committer_name'],
390 $info['committer_mail'],
391 isset($info['diffstat']) ? $info['diffstat'] : '',
392 ), $format);
395 function rss_pubdate($secs)
397 return date('D, d M Y H:i:s O', $secs);
401 * Executes a git command in the project repo.
402 * @return array of output lines
404 function run_git($project, $command)
406 global $conf;
408 $output = array();
409 $cmd = "GIT_DIR=". $conf['projects'][$project]['repo'] ." $command";
410 exec($cmd, &$output);
411 return $output;
415 * Executes a git command in the project repo, sending output directly to the
416 * client.
418 function run_git_passthru($project, $command)
420 global $conf;
422 $cmd = "GIT_DIR=". $conf['projects'][$project]['repo'] ." $command";
423 $result = 0;
424 passthru($cmd, &$result);
425 return $result;
429 * Makes sure the given project is valid. If it's not, this function will
430 * die().
431 * @return the project
433 function validate_project($project)
435 global $conf;
437 if (!in_array($project, array_keys($conf['projects']))) {
438 die('Invalid project');
440 return $project;
444 * Makes sure the given hash is valid. If it's not, this function will die().
445 * @return the hash
447 function validate_hash($hash)
449 if (!preg_match('/^[0-9a-z]{40}$/', $hash) && !preg_match('!^refs/(heads|tags)/[-.0-9a-z]+$!', $hash) && $hash !== 'HEAD') {
450 die('Invalid hash');
453 return $hash;