tree: added a "browse at HEAD" link.
[viewgit.git] / inc / functions.php
blob33c84b225a85f297f3f9e6257174066aa8ae6729
1 <?php
2 /** @file
3 * Functions used by ViewGit.
4 */
6 function debug($msg)
8 file_put_contents('/tmp/viewgit.log', strftime('%H:%M:%S') ." $_SERVER[REMOTE_ADDR]:$_SERVER[REMOTE_PORT] $msg\n", FILE_APPEND);
11 /**
12 * Formats "git diff" output into xhtml.
13 * @return array(array of filenames, xhtml)
15 function format_diff($text)
17 $files = array();
19 // match every "^diff --git a/<path> b/<path>$" line
20 foreach (explode("\n", $text) as $line) {
21 if (preg_match('#^diff --git a/(.*) b/(.*)$#', $line, $matches) > 0) {
22 $files[$matches[1]] = urlencode($matches[1]);
26 $text = htmlentities($text);
28 $text = preg_replace(
29 array(
30 '/^(\+.*)$/m',
31 '/^(-.*)$/m',
32 '/^(@.*)$/m',
33 '/^([^d\+-@].*)$/m',
35 array(
36 '<span class="add">$1</span>',
37 '<span class="del">$1</span>',
38 '<span class="pos">$1</span>',
39 '<span class="etc">$1</span>',
41 $text);
42 $text = preg_replace_callback('#^diff --git a/(.*) b/(.*)$#m',
43 create_function(
44 '$m',
45 'return "<span class=\"diffline\"><a name=\"". urlencode($m[1]) ."\">diff --git a/$m[1] b/$m[2]</a></span>";'
47 $text);
49 return array($files, $text);
52 /**
53 * Get project information from config and git, name/description and HEAD
54 * commit info are returned in an array.
56 function get_project_info($name)
58 global $conf;
60 $info = $conf['projects'][$name];
61 $info['name'] = $name;
62 $info['description'] = file_get_contents($info['repo'] .'/description');
64 $headinfo = git_get_commit_info($name, 'HEAD');
65 $info['head_stamp'] = $headinfo['author_utcstamp'];
66 $info['head_datetime'] = strftime($conf['datetime'], $headinfo['author_utcstamp']);
67 $info['head_hash'] = $headinfo['h'];
68 $info['head_tree'] = $headinfo['tree'];
70 return $info;
73 function git_diffstat($project, $commit, $commit_base = null)
75 if (is_null($commit_base)) {
76 $commit_base = "$commit^";
78 return join("\n", run_git($project, "git diff --stat $commit_base..$commit"));
81 /**
82 * Get details of a commit: tree, parents, author/committer (name, mail, date), message
84 function git_get_commit_info($project, $hash = 'HEAD')
86 global $conf;
88 $info = array();
89 $info['h_name'] = $hash;
90 $info['message_full'] = '';
91 $info['parents'] = array();
93 $output = run_git($project, "git rev-list --header --max-count=1 $hash");
94 // tree <h>
95 // parent <h>
96 // author <name> "<"<mail>">" <stamp> <timezone>
97 // committer
98 // <empty>
99 // <message>
100 $pattern = '/^(author|committer) ([^<]+) <([^>]*)> ([0-9]+) (.*)$/';
101 foreach ($output as $line) {
102 if (substr($line, 0, 4) === 'tree') {
103 $info['tree'] = substr($line, 5);
105 // may be repeated multiple times for merge/octopus
106 elseif (substr($line, 0, 6) === 'parent') {
107 $info['parents'][] = substr($line, 7);
109 elseif (preg_match($pattern, $line, $matches) > 0) {
110 $info[$matches[1] .'_name'] = $matches[2];
111 $info[$matches[1] .'_mail'] = $matches[3];
112 $info[$matches[1] .'_stamp'] = $matches[4];
113 $info[$matches[1] .'_timezone'] = $matches[5];
114 $info[$matches[1] .'_utcstamp'] = $matches[4] - ((intval($matches[5]) / 100.0) * 3600);
116 if (isset($conf['mail_filter'])) {
117 $info[$matches[1] .'_mail'] = $conf['mail_filter']($info[$matches[1] .'_mail']);
120 elseif (substr($line, 0, 4) === ' ') {
121 $info['message_full'] .= substr($line, 4) ."\n";
122 if (!isset($info['message'])) {
123 $info['message'] = substr($line, 4, $conf['commit_message_maxlen']);
124 $info['message_firstline'] = substr($line, 4);
127 elseif (preg_match('/^[0-9a-f]{40}$/', $line) > 0) {
128 $info['h'] = $line;
132 return $info;
136 * Get list of heads (branches) for a project.
138 function git_get_heads($project)
140 $heads = array();
142 $output = run_git($project, 'git show-ref --heads');
143 foreach ($output as $line) {
144 $fullname = substr($line, 41);
145 $name = array_pop(explode('/', $fullname));
146 $heads[] = array('h' => substr($line, 0, 40), 'fullname' => "$fullname", 'name' => "$name");
149 return $heads;
153 * Get array containing path information for parts, starting from root_hash.
155 * @param root_hash commit/tree hash for the root tree
156 * @param path path
158 function git_get_path_info($project, $root_hash, $path)
160 if (strlen($path) > 0) {
161 $parts = explode('/', $path);
162 } else {
163 $parts = array();
166 $pathinfo = array();
168 $tid = $root_hash;
169 $pathinfo = array();
170 foreach ($parts as $p) {
171 $entry = git_ls_tree_part($project, $tid, $p);
172 $pathinfo[] = $entry;
173 $tid = $entry['hash'];
176 return $pathinfo;
180 * Get revision list starting from given commit.
181 * @param max_count number of commit hashes to return, or all if not given
182 * @param start revision to start from, or HEAD if not given
184 function git_get_rev_list($project, $max_count = null, $start = 'HEAD')
186 $cmd = "git rev-list $start";
187 if (!is_null($max_count)) {
188 $cmd = "git rev-list --max-count=$max_count $start";
191 return run_git($project, $cmd);
195 * Get list of tags for a project.
197 function git_get_tags($project)
199 $tags = array();
201 $output = run_git($project, 'git show-ref --tags');
202 foreach ($output as $line) {
203 $fullname = substr($line, 41);
204 $name = array_pop(explode('/', $fullname));
205 $tags[] = array('h' => substr($line, 0, 40), 'fullname' => $fullname, 'name' => $name);
207 return $tags;
211 * Get information about objects in a tree.
212 * @param tree tree or commit hash
213 * @return list of arrays containing name, mode, type, hash
215 function git_ls_tree($project, $tree)
217 $entries = array();
218 $output = run_git($project, "git ls-tree $tree");
219 // 100644 blob 493b7fc4296d64af45dac64bceac2d9a96c958c1 .gitignore
220 // 040000 tree 715c78b1011dc58106da2a1af2fe0aa4c829542f doc
221 foreach ($output as $line) {
222 $parts = preg_split('/\s+/', $line, 4);
223 $entries[] = array('name' => $parts[3], 'mode' => $parts[0], 'type' => $parts[1], 'hash' => $parts[2]);
226 return $entries;
230 * Get information about the given object in a tree, or null if not in the tree.
232 function git_ls_tree_part($project, $tree, $name)
234 $entries = git_ls_tree($project, $tree);
235 foreach ($entries as $entry) {
236 if ($entry['name'] === $name) {
237 return $entry;
240 return null;
244 * Fetch tags data, newest first.
246 * @param limit maximum number of tags to return
248 function handle_tags($project, $limit = 0)
250 global $conf;
252 $tags = git_get_tags($project);
253 $result = array();
254 foreach ($tags as $tag) {
255 $info = git_get_commit_info($project, $tag['h']);
256 $result[] = array(
257 'stamp' => $info['author_utcstamp'],
258 'date' => strftime($conf['datetime'], $info['author_utcstamp']),
259 'h' => $tag['h'],
260 'fullname' => $tag['fullname'],
261 'name' => $tag['name'],
265 // sort tags newest first
266 // aka. two more reasons to hate PHP (figuring those out is your homework:)
267 usort($result, create_function(
268 '$x, $y',
269 '$a = $x["stamp"]; $b = $y["stamp"]; return ($a == $b ? 0 : ($a > $b ? -1 : 1));'
272 // TODO optimize this some way, currently all tags are fetched when only a
273 // few are shown. The problem is that without fetching the commit info
274 // above, we can't sort using dates, only by tag name...
275 if ($limit > 0) {
276 $result = array_splice($result, 0, $limit);
279 return $result;
283 * Return a URL that contains the given parameters.
285 function makelink($dict)
287 $params = array();
288 foreach ($dict as $k => $v) {
289 $params[] = rawurlencode($k) .'='. str_replace('%2F', '/', rawurlencode($v));
291 if (count($params) > 0) {
292 return '?'. htmlentities(join('&', $params));
294 return '';
298 * Obfuscate the e-mail address.
300 function obfuscate_mail($mail)
302 return str_replace(array('@', '.'), array(' at ', ' dot '), $mail);
306 * Used to format RSS item title and description.
308 * @param info commit info from git_get_commit_info()
310 function rss_item_format($format, $info)
312 return preg_replace(array(
313 '/{AUTHOR}/',
314 '/{AUTHOR_MAIL}/',
315 '/{SHORTLOG}/',
316 '/{LOG}/',
317 '/{COMMITTER}/',
318 '/{COMMITTER_MAIL}/',
319 '/{DIFFSTAT}/',
320 ), array(
321 $info['author_name'],
322 $info['author_mail'],
323 $info['message_firstline'],
324 $info['message_full'],
325 $info['committer_name'],
326 $info['committer_mail'],
327 isset($info['diffstat']) ? $info['diffstat'] : '',
328 ), $format);
331 function rss_pubdate($secs)
333 return date('D, d M Y H:i:s O', $secs);
337 * Executes a git command in the project repo.
338 * @return array of output lines
340 function run_git($project, $command)
342 global $conf;
344 $output = array();
345 $cmd = "GIT_DIR=". $conf['projects'][$project]['repo'] ." $command";
346 exec($cmd, &$output);
347 return $output;
351 * Executes a git command in the project repo, sending output directly to the
352 * client.
354 function run_git_passthru($project, $command)
356 global $conf;
358 $cmd = "GIT_DIR=". $conf['projects'][$project]['repo'] ." $command";
359 $result = 0;
360 passthru($cmd, &$result);
361 return $result;
365 * Makes sure the given project is valid. If it's not, this function will
366 * die().
367 * @return the project
369 function validate_project($project)
371 global $conf;
373 if (!in_array($project, array_keys($conf['projects']))) {
374 die('Invalid project');
376 return $project;
380 * Makes sure the given hash is valid. If it's not, this function will die().
381 * @return the hash
383 function validate_hash($hash)
385 if (!preg_match('/^[0-9a-z]{40}$/', $hash) && !preg_match('!^refs/(heads|tags)/[-.0-9a-z]+$!', $hash) && $hash !== 'HEAD') {
386 die('Invalid hash');
389 return $hash;