gitweb: Add git_project_index for generating index.aux
[git] / gitweb / gitweb.perl
1 #!/usr/bin/perl
2
3 # gitweb - simple web interface to track changes in git repositories
4 #
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
7 #
8 # This program is licensed under the GPLv2
9
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
20
21 our $cgi = new CGI;
22 our $version = "++GIT_VERSION++";
23 our $my_url = $cgi->url();
24 our $my_uri = $cgi->url(-absolute => 1);
25
26 # core git executable to use
27 # this can just be "git" if your webserver has a sensible PATH
28 our $GIT = "++GIT_BINDIR++/git";
29
30 # absolute fs-path which will be prepended to the project path
31 #our $projectroot = "/pub/scm";
32 our $projectroot = "++GITWEB_PROJECTROOT++";
33
34 # target of the home link on top of all pages
35 our $home_link = $my_uri || "/";
36
37 # string of the home link on top of all pages
38 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
39
40 # name of your site or organization to appear in page titles
41 # replace this with something more descriptive for clearer bookmarks
42 our $site_name = "++GITWEB_SITENAME++" || $ENV{'SERVER_NAME'} || "Untitled";
43
44 # html text to include at home page
45 our $home_text = "++GITWEB_HOMETEXT++";
46
47 # URI of default stylesheet
48 our $stylesheet = "++GITWEB_CSS++";
49 # URI of GIT logo
50 our $logo = "++GITWEB_LOGO++";
51 # URI of GIT favicon, assumed to be image/png type
52 our $favicon = "++GITWEB_FAVICON++";
53
54 # source of projects list
55 our $projects_list = "++GITWEB_LIST++";
56
57 # list of git base URLs used for URL to where fetch project from,
58 # i.e. full URL is "$git_base_url/$project"
59 our @git_base_url_list = ("++GITWEB_BASE_URL++");
60
61 # default blob_plain mimetype and default charset for text/plain blob
62 our $default_blob_plain_mimetype = 'text/plain';
63 our $default_text_plain_charset  = undef;
64
65 # file to use for guessing MIME types before trying /etc/mime.types
66 # (relative to the current git repository)
67 our $mimetypes_file = undef;
68
69 # You define site-wide feature defaults here; override them with
70 # $GITWEB_CONFIG as necessary.
71 our %feature = (
72         # feature => {
73         #       'sub' => feature-sub (subroutine),
74         #       'override' => allow-override (boolean),
75         #       'default' => [ default options...] (array reference)}
76         #
77         # if feature is overridable (it means that allow-override has true value,
78         # then feature-sub will be called with default options as parameters;
79         # return value of feature-sub indicates if to enable specified feature
80         #
81         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
82
83         'blame' => {
84                 'sub' => \&feature_blame,
85                 'override' => 0,
86                 'default' => [0]},
87
88         'snapshot' => {
89                 'sub' => \&feature_snapshot,
90                 'override' => 0,
91                 #         => [content-encoding, suffix, program]
92                 'default' => ['x-gzip', 'gz', 'gzip']},
93
94         'pickaxe' => {
95                 'sub' => \&feature_pickaxe,
96                 'override' => 0,
97                 'default' => [1]},
98 );
99
100 sub gitweb_check_feature {
101         my ($name) = @_;
102         return undef unless exists $feature{$name};
103         my ($sub, $override, @defaults) = (
104                 $feature{$name}{'sub'},
105                 $feature{$name}{'override'},
106                 @{$feature{$name}{'default'}});
107         if (!$override) { return @defaults; }
108         return $sub->(@defaults);
109 }
110
111 # To enable system wide have in $GITWEB_CONFIG
112 # $feature{'blame'}{'default'} = [1];
113 # To have project specific config enable override in $GITWEB_CONFIG
114 # $feature{'blame'}{'override'} = 1;
115 # and in project config gitweb.blame = 0|1;
116
117 sub feature_blame {
118         my ($val) = git_get_project_config('blame', '--bool');
119
120         if ($val eq 'true') {
121                 return 1;
122         } elsif ($val eq 'false') {
123                 return 0;
124         }
125
126         return $_[0];
127 }
128
129 # To disable system wide have in $GITWEB_CONFIG
130 # $feature{'snapshot'}{'default'} = [undef];
131 # To have project specific config enable override in $GITWEB_CONFIG
132 # $feature{'blame'}{'override'} = 1;
133 # and in project config  gitweb.snapshot = none|gzip|bzip2
134
135 sub feature_snapshot {
136         my ($ctype, $suffix, $command) = @_;
137
138         my ($val) = git_get_project_config('snapshot');
139
140         if ($val eq 'gzip') {
141                 return ('x-gzip', 'gz', 'gzip');
142         } elsif ($val eq 'bzip2') {
143                 return ('x-bzip2', 'bz2', 'bzip2');
144         } elsif ($val eq 'none') {
145                 return ();
146         }
147
148         return ($ctype, $suffix, $command);
149 }
150
151 # To enable system wide have in $GITWEB_CONFIG
152 # $feature{'pickaxe'}{'default'} = [1];
153 # To have project specific config enable override in $GITWEB_CONFIG
154 # $feature{'pickaxe'}{'override'} = 1;
155 # and in project config gitweb.pickaxe = 0|1;
156
157 sub feature_pickaxe {
158         my ($val) = git_get_project_config('pickaxe', '--bool');
159
160         if ($val eq 'true') {
161                 return (1);
162         } elsif ($val eq 'false') {
163                 return (0);
164         }
165
166         return ($_[0]);
167 }
168
169 # rename detection options for git-diff and git-diff-tree
170 # - default is '-M', with the cost proportional to
171 #   (number of removed files) * (number of new files).
172 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
173 #   (number of changed files + number of removed files) * (number of new files)
174 # - even more costly is '-C', '--find-copies-harder' with cost
175 #   (number of files in the original tree) * (number of new files)
176 # - one might want to include '-B' option, e.g. '-B', '-M'
177 our @diff_opts = ('-M'); # taken from git_commit
178
179 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
180 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
181
182 # version of the core git binary
183 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
184
185 # path to the current git repository
186 our $git_dir;
187
188 $projects_list ||= $projectroot;
189
190 # ======================================================================
191 # input validation and dispatch
192 our $action = $cgi->param('a');
193 if (defined $action) {
194         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
195                 die_error(undef, "Invalid action parameter");
196         }
197 }
198
199 our $project = ($cgi->param('p') || $ENV{'PATH_INFO'});
200 if (defined $project) {
201         $project =~ s|^/||;
202         $project =~ s|/$||;
203         $project = undef unless $project;
204 }
205 if (defined $project) {
206         if (!validate_input($project)) {
207                 die_error(undef, "Invalid project parameter");
208         }
209         if (!(-d "$projectroot/$project")) {
210                 die_error(undef, "No such directory");
211         }
212         if (!(-e "$projectroot/$project/HEAD")) {
213                 die_error(undef, "No such project");
214         }
215         $git_dir = "$projectroot/$project";
216 }
217
218 our $file_name = $cgi->param('f');
219 if (defined $file_name) {
220         if (!validate_input($file_name)) {
221                 die_error(undef, "Invalid file parameter");
222         }
223 }
224
225 our $file_parent = $cgi->param('fp');
226 if (defined $file_parent) {
227         if (!validate_input($file_parent)) {
228                 die_error(undef, "Invalid file parent parameter");
229         }
230 }
231
232 our $hash = $cgi->param('h');
233 if (defined $hash) {
234         if (!validate_input($hash)) {
235                 die_error(undef, "Invalid hash parameter");
236         }
237 }
238
239 our $hash_parent = $cgi->param('hp');
240 if (defined $hash_parent) {
241         if (!validate_input($hash_parent)) {
242                 die_error(undef, "Invalid hash parent parameter");
243         }
244 }
245
246 our $hash_base = $cgi->param('hb');
247 if (defined $hash_base) {
248         if (!validate_input($hash_base)) {
249                 die_error(undef, "Invalid hash base parameter");
250         }
251 }
252
253 our $hash_parent_base = $cgi->param('hpb');
254 if (defined $hash_parent_base) {
255         if (!validate_input($hash_parent_base)) {
256                 die_error(undef, "Invalid hash parent base parameter");
257         }
258 }
259
260 our $page = $cgi->param('pg');
261 if (defined $page) {
262         if ($page =~ m/[^0-9]$/) {
263                 die_error(undef, "Invalid page parameter");
264         }
265 }
266
267 our $searchtext = $cgi->param('s');
268 if (defined $searchtext) {
269         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
270                 die_error(undef, "Invalid search parameter");
271         }
272         $searchtext = quotemeta $searchtext;
273 }
274
275 # dispatch
276 my %actions = (
277         "blame" => \&git_blame2,
278         "blobdiff" => \&git_blobdiff,
279         "blobdiff_plain" => \&git_blobdiff_plain,
280         "blob" => \&git_blob,
281         "blob_plain" => \&git_blob_plain,
282         "commitdiff" => \&git_commitdiff,
283         "commitdiff_plain" => \&git_commitdiff_plain,
284         "commit" => \&git_commit,
285         "heads" => \&git_heads,
286         "history" => \&git_history,
287         "log" => \&git_log,
288         "rss" => \&git_rss,
289         "search" => \&git_search,
290         "shortlog" => \&git_shortlog,
291         "summary" => \&git_summary,
292         "tag" => \&git_tag,
293         "tags" => \&git_tags,
294         "tree" => \&git_tree,
295         "snapshot" => \&git_snapshot,
296         # those below don't need $project
297         "opml" => \&git_opml,
298         "project_list" => \&git_project_list,
299         "project_index" => \&git_project_index,
300 );
301
302 if (defined $project) {
303         $action ||= 'summary';
304 } else {
305         $action ||= 'project_list';
306 }
307 if (!defined($actions{$action})) {
308         die_error(undef, "Unknown action");
309 }
310 $actions{$action}->();
311 exit;
312
313 ## ======================================================================
314 ## action links
315
316 sub href(%) {
317         my %params = @_;
318
319         my @mapping = (
320                 project => "p",
321                 action => "a",
322                 file_name => "f",
323                 file_parent => "fp",
324                 hash => "h",
325                 hash_parent => "hp",
326                 hash_base => "hb",
327                 hash_parent_base => "hpb",
328                 page => "pg",
329                 searchtext => "s",
330         );
331         my %mapping = @mapping;
332
333         $params{"project"} ||= $project;
334
335         my @result = ();
336         for (my $i = 0; $i < @mapping; $i += 2) {
337                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
338                 if (defined $params{$name}) {
339                         push @result, $symbol . "=" . esc_param($params{$name});
340                 }
341         }
342         return "$my_uri?" . join(';', @result);
343 }
344
345
346 ## ======================================================================
347 ## validation, quoting/unquoting and escaping
348
349 sub validate_input {
350         my $input = shift;
351
352         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
353                 return $input;
354         }
355         if ($input =~ m/(^|\/)(|\.|\.\.)($|\/)/) {
356                 return undef;
357         }
358         if ($input =~ m/[^a-zA-Z0-9_\x80-\xff\ \t\.\/\-\+\#\~\%]/) {
359                 return undef;
360         }
361         return $input;
362 }
363
364 # quote unsafe chars, but keep the slash, even when it's not
365 # correct, but quoted slashes look too horrible in bookmarks
366 sub esc_param {
367         my $str = shift;
368         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
369         $str =~ s/\+/%2B/g;
370         $str =~ s/ /\+/g;
371         return $str;
372 }
373
374 # replace invalid utf8 character with SUBSTITUTION sequence
375 sub esc_html {
376         my $str = shift;
377         $str = decode("utf8", $str, Encode::FB_DEFAULT);
378         $str = escapeHTML($str);
379         $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
380         return $str;
381 }
382
383 # git may return quoted and escaped filenames
384 sub unquote {
385         my $str = shift;
386         if ($str =~ m/^"(.*)"$/) {
387                 $str = $1;
388                 $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
389         }
390         return $str;
391 }
392
393 # escape tabs (convert tabs to spaces)
394 sub untabify {
395         my $line = shift;
396
397         while ((my $pos = index($line, "\t")) != -1) {
398                 if (my $count = (8 - ($pos % 8))) {
399                         my $spaces = ' ' x $count;
400                         $line =~ s/\t/$spaces/;
401                 }
402         }
403
404         return $line;
405 }
406
407 ## ----------------------------------------------------------------------
408 ## HTML aware string manipulation
409
410 sub chop_str {
411         my $str = shift;
412         my $len = shift;
413         my $add_len = shift || 10;
414
415         # allow only $len chars, but don't cut a word if it would fit in $add_len
416         # if it doesn't fit, cut it if it's still longer than the dots we would add
417         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
418         my $body = $1;
419         my $tail = $2;
420         if (length($tail) > 4) {
421                 $tail = " ...";
422                 $body =~ s/&[^;]*$//; # remove chopped character entities
423         }
424         return "$body$tail";
425 }
426
427 ## ----------------------------------------------------------------------
428 ## functions returning short strings
429
430 # CSS class for given age value (in seconds)
431 sub age_class {
432         my $age = shift;
433
434         if ($age < 60*60*2) {
435                 return "age0";
436         } elsif ($age < 60*60*24*2) {
437                 return "age1";
438         } else {
439                 return "age2";
440         }
441 }
442
443 # convert age in seconds to "nn units ago" string
444 sub age_string {
445         my $age = shift;
446         my $age_str;
447
448         if ($age > 60*60*24*365*2) {
449                 $age_str = (int $age/60/60/24/365);
450                 $age_str .= " years ago";
451         } elsif ($age > 60*60*24*(365/12)*2) {
452                 $age_str = int $age/60/60/24/(365/12);
453                 $age_str .= " months ago";
454         } elsif ($age > 60*60*24*7*2) {
455                 $age_str = int $age/60/60/24/7;
456                 $age_str .= " weeks ago";
457         } elsif ($age > 60*60*24*2) {
458                 $age_str = int $age/60/60/24;
459                 $age_str .= " days ago";
460         } elsif ($age > 60*60*2) {
461                 $age_str = int $age/60/60;
462                 $age_str .= " hours ago";
463         } elsif ($age > 60*2) {
464                 $age_str = int $age/60;
465                 $age_str .= " min ago";
466         } elsif ($age > 2) {
467                 $age_str = int $age;
468                 $age_str .= " sec ago";
469         } else {
470                 $age_str .= " right now";
471         }
472         return $age_str;
473 }
474
475 # convert file mode in octal to symbolic file mode string
476 sub mode_str {
477         my $mode = oct shift;
478
479         if (S_ISDIR($mode & S_IFMT)) {
480                 return 'drwxr-xr-x';
481         } elsif (S_ISLNK($mode)) {
482                 return 'lrwxrwxrwx';
483         } elsif (S_ISREG($mode)) {
484                 # git cares only about the executable bit
485                 if ($mode & S_IXUSR) {
486                         return '-rwxr-xr-x';
487                 } else {
488                         return '-rw-r--r--';
489                 };
490         } else {
491                 return '----------';
492         }
493 }
494
495 # convert file mode in octal to file type string
496 sub file_type {
497         my $mode = shift;
498
499         if ($mode !~ m/^[0-7]+$/) {
500                 return $mode;
501         } else {
502                 $mode = oct $mode;
503         }
504
505         if (S_ISDIR($mode & S_IFMT)) {
506                 return "directory";
507         } elsif (S_ISLNK($mode)) {
508                 return "symlink";
509         } elsif (S_ISREG($mode)) {
510                 return "file";
511         } else {
512                 return "unknown";
513         }
514 }
515
516 ## ----------------------------------------------------------------------
517 ## functions returning short HTML fragments, or transforming HTML fragments
518 ## which don't beling to other sections
519
520 # format line of commit message or tag comment
521 sub format_log_line_html {
522         my $line = shift;
523
524         $line = esc_html($line);
525         $line =~ s/ /&nbsp;/g;
526         if ($line =~ m/([0-9a-fA-F]{40})/) {
527                 my $hash_text = $1;
528                 if (git_get_type($hash_text) eq "commit") {
529                         my $link =
530                                 $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
531                                         -class => "text"}, $hash_text);
532                         $line =~ s/$hash_text/$link/;
533                 }
534         }
535         return $line;
536 }
537
538 # format marker of refs pointing to given object
539 sub format_ref_marker {
540         my ($refs, $id) = @_;
541         my $markers = '';
542
543         if (defined $refs->{$id}) {
544                 foreach my $ref (@{$refs->{$id}}) {
545                         my ($type, $name) = qw();
546                         # e.g. tags/v2.6.11 or heads/next
547                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
548                                 $type = $1;
549                                 $name = $2;
550                         } else {
551                                 $type = "ref";
552                                 $name = $ref;
553                         }
554
555                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
556                 }
557         }
558
559         if ($markers) {
560                 return ' <span class="refs">'. $markers . '</span>';
561         } else {
562                 return "";
563         }
564 }
565
566 # format, perhaps shortened and with markers, title line
567 sub format_subject_html {
568         my ($long, $short, $href, $extra) = @_;
569         $extra = '' unless defined($extra);
570
571         if (length($short) < length($long)) {
572                 return $cgi->a({-href => $href, -class => "list subject",
573                                 -title => $long},
574                        esc_html($short) . $extra);
575         } else {
576                 return $cgi->a({-href => $href, -class => "list subject"},
577                        esc_html($long)  . $extra);
578         }
579 }
580
581 sub format_diff_line {
582         my $line = shift;
583         my $char = substr($line, 0, 1);
584         my $diff_class = "";
585
586         chomp $line;
587
588         if ($char eq '+') {
589                 $diff_class = " add";
590         } elsif ($char eq "-") {
591                 $diff_class = " rem";
592         } elsif ($char eq "@") {
593                 $diff_class = " chunk_header";
594         } elsif ($char eq "\\") {
595                 $diff_class = " incomplete";
596         }
597         $line = untabify($line);
598         return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
599 }
600
601 ## ----------------------------------------------------------------------
602 ## git utility subroutines, invoking git commands
603
604 # returns path to the core git executable and the --git-dir parameter as list
605 sub git_cmd {
606         return $GIT, '--git-dir='.$git_dir;
607 }
608
609 # returns path to the core git executable and the --git-dir parameter as string
610 sub git_cmd_str {
611         return join(' ', git_cmd());
612 }
613
614 # get HEAD ref of given project as hash
615 sub git_get_head_hash {
616         my $project = shift;
617         my $o_git_dir = $git_dir;
618         my $retval = undef;
619         $git_dir = "$projectroot/$project";
620         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
621                 my $head = <$fd>;
622                 close $fd;
623                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
624                         $retval = $1;
625                 }
626         }
627         if (defined $o_git_dir) {
628                 $git_dir = $o_git_dir;
629         }
630         return $retval;
631 }
632
633 # get type of given object
634 sub git_get_type {
635         my $hash = shift;
636
637         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
638         my $type = <$fd>;
639         close $fd or return;
640         chomp $type;
641         return $type;
642 }
643
644 sub git_get_project_config {
645         my ($key, $type) = @_;
646
647         return unless ($key);
648         $key =~ s/^gitweb\.//;
649         return if ($key =~ m/\W/);
650
651         my @x = (git_cmd(), 'repo-config');
652         if (defined $type) { push @x, $type; }
653         push @x, "--get";
654         push @x, "gitweb.$key";
655         my $val = qx(@x);
656         chomp $val;
657         return ($val);
658 }
659
660 # get hash of given path at given ref
661 sub git_get_hash_by_path {
662         my $base = shift;
663         my $path = shift || return undef;
664
665         my $tree = $base;
666
667         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
668                 or die_error(undef, "Open git-ls-tree failed");
669         my $line = <$fd>;
670         close $fd or return undef;
671
672         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
673         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
674         return $3;
675 }
676
677 ## ......................................................................
678 ## git utility functions, directly accessing git repository
679
680 sub git_get_project_description {
681         my $path = shift;
682
683         open my $fd, "$projectroot/$path/description" or return undef;
684         my $descr = <$fd>;
685         close $fd;
686         chomp $descr;
687         return $descr;
688 }
689
690 sub git_get_project_url_list {
691         my $path = shift;
692
693         open my $fd, "$projectroot/$path/cloneurl" or return undef;
694         my @git_project_url_list = map { chomp; $_ } <$fd>;
695         close $fd;
696
697         return wantarray ? @git_project_url_list : \@git_project_url_list;
698 }
699
700 sub git_get_projects_list {
701         my @list;
702
703         if (-d $projects_list) {
704                 # search in directory
705                 my $dir = $projects_list;
706                 my $pfxlen = length("$dir");
707
708                 File::Find::find({
709                         follow_fast => 1, # follow symbolic links
710                         dangling_symlinks => 0, # ignore dangling symlinks, silently
711                         wanted => sub {
712                                 # skip project-list toplevel, if we get it.
713                                 return if (m!^[/.]$!);
714                                 # only directories can be git repositories
715                                 return unless (-d $_);
716
717                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
718                                 # we check related file in $projectroot
719                                 if (-e "$projectroot/$subdir/HEAD") {
720                                         push @list, { path => $subdir };
721                                         $File::Find::prune = 1;
722                                 }
723                         },
724                 }, "$dir");
725
726         } elsif (-f $projects_list) {
727                 # read from file(url-encoded):
728                 # 'git%2Fgit.git Linus+Torvalds'
729                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
730                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
731                 open my ($fd), $projects_list or return undef;
732                 while (my $line = <$fd>) {
733                         chomp $line;
734                         my ($path, $owner) = split ' ', $line;
735                         $path = unescape($path);
736                         $owner = unescape($owner);
737                         if (!defined $path) {
738                                 next;
739                         }
740                         if (-e "$projectroot/$path/HEAD") {
741                                 my $pr = {
742                                         path => $path,
743                                         owner => decode("utf8", $owner, Encode::FB_DEFAULT),
744                                 };
745                                 push @list, $pr
746                         }
747                 }
748                 close $fd;
749         }
750         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
751         return @list;
752 }
753
754 sub git_get_project_owner {
755         my $project = shift;
756         my $owner;
757
758         return undef unless $project;
759
760         # read from file (url-encoded):
761         # 'git%2Fgit.git Linus+Torvalds'
762         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
763         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
764         if (-f $projects_list) {
765                 open (my $fd , $projects_list);
766                 while (my $line = <$fd>) {
767                         chomp $line;
768                         my ($pr, $ow) = split ' ', $line;
769                         $pr = unescape($pr);
770                         $ow = unescape($ow);
771                         if ($pr eq $project) {
772                                 $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
773                                 last;
774                         }
775                 }
776                 close $fd;
777         }
778         if (!defined $owner) {
779                 $owner = get_file_owner("$projectroot/$project");
780         }
781
782         return $owner;
783 }
784
785 sub git_get_references {
786         my $type = shift || "";
787         my %refs;
788         my $fd;
789         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
790         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
791         if (-f "$projectroot/$project/info/refs") {
792                 open $fd, "$projectroot/$project/info/refs"
793                         or return;
794         } else {
795                 open $fd, "-|", git_cmd(), "ls-remote", "."
796                         or return;
797         }
798
799         while (my $line = <$fd>) {
800                 chomp $line;
801                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
802                         if (defined $refs{$1}) {
803                                 push @{$refs{$1}}, $2;
804                         } else {
805                                 $refs{$1} = [ $2 ];
806                         }
807                 }
808         }
809         close $fd or return;
810         return \%refs;
811 }
812
813 sub git_get_rev_name_tags {
814         my $hash = shift || return undef;
815
816         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
817                 or return;
818         my $name_rev = <$fd>;
819         close $fd;
820
821         if ($name_rev =~ m|^$hash tags/(.*)$|) {
822                 return $1;
823         } else {
824                 # catches also '$hash undefined' output
825                 return undef;
826         }
827 }
828
829 ## ----------------------------------------------------------------------
830 ## parse to hash functions
831
832 sub parse_date {
833         my $epoch = shift;
834         my $tz = shift || "-0000";
835
836         my %date;
837         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
838         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
839         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
840         $date{'hour'} = $hour;
841         $date{'minute'} = $min;
842         $date{'mday'} = $mday;
843         $date{'day'} = $days[$wday];
844         $date{'month'} = $months[$mon];
845         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
846                            $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
847         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
848                              $mday, $months[$mon], $hour ,$min;
849
850         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
851         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
852         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
853         $date{'hour_local'} = $hour;
854         $date{'minute_local'} = $min;
855         $date{'tz_local'} = $tz;
856         return %date;
857 }
858
859 sub parse_tag {
860         my $tag_id = shift;
861         my %tag;
862         my @comment;
863
864         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
865         $tag{'id'} = $tag_id;
866         while (my $line = <$fd>) {
867                 chomp $line;
868                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
869                         $tag{'object'} = $1;
870                 } elsif ($line =~ m/^type (.+)$/) {
871                         $tag{'type'} = $1;
872                 } elsif ($line =~ m/^tag (.+)$/) {
873                         $tag{'name'} = $1;
874                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
875                         $tag{'author'} = $1;
876                         $tag{'epoch'} = $2;
877                         $tag{'tz'} = $3;
878                 } elsif ($line =~ m/--BEGIN/) {
879                         push @comment, $line;
880                         last;
881                 } elsif ($line eq "") {
882                         last;
883                 }
884         }
885         push @comment, <$fd>;
886         $tag{'comment'} = \@comment;
887         close $fd or return;
888         if (!defined $tag{'name'}) {
889                 return
890         };
891         return %tag
892 }
893
894 sub parse_commit {
895         my $commit_id = shift;
896         my $commit_text = shift;
897
898         my @commit_lines;
899         my %co;
900
901         if (defined $commit_text) {
902                 @commit_lines = @$commit_text;
903         } else {
904                 $/ = "\0";
905                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
906                         or return;
907                 @commit_lines = split '\n', <$fd>;
908                 close $fd or return;
909                 $/ = "\n";
910                 pop @commit_lines;
911         }
912         my $header = shift @commit_lines;
913         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
914                 return;
915         }
916         ($co{'id'}, my @parents) = split ' ', $header;
917         $co{'parents'} = \@parents;
918         $co{'parent'} = $parents[0];
919         while (my $line = shift @commit_lines) {
920                 last if $line eq "\n";
921                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
922                         $co{'tree'} = $1;
923                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
924                         $co{'author'} = $1;
925                         $co{'author_epoch'} = $2;
926                         $co{'author_tz'} = $3;
927                         if ($co{'author'} =~ m/^([^<]+) </) {
928                                 $co{'author_name'} = $1;
929                         } else {
930                                 $co{'author_name'} = $co{'author'};
931                         }
932                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
933                         $co{'committer'} = $1;
934                         $co{'committer_epoch'} = $2;
935                         $co{'committer_tz'} = $3;
936                         $co{'committer_name'} = $co{'committer'};
937                         $co{'committer_name'} =~ s/ <.*//;
938                 }
939         }
940         if (!defined $co{'tree'}) {
941                 return;
942         };
943
944         foreach my $title (@commit_lines) {
945                 $title =~ s/^    //;
946                 if ($title ne "") {
947                         $co{'title'} = chop_str($title, 80, 5);
948                         # remove leading stuff of merges to make the interesting part visible
949                         if (length($title) > 50) {
950                                 $title =~ s/^Automatic //;
951                                 $title =~ s/^merge (of|with) /Merge ... /i;
952                                 if (length($title) > 50) {
953                                         $title =~ s/(http|rsync):\/\///;
954                                 }
955                                 if (length($title) > 50) {
956                                         $title =~ s/(master|www|rsync)\.//;
957                                 }
958                                 if (length($title) > 50) {
959                                         $title =~ s/kernel.org:?//;
960                                 }
961                                 if (length($title) > 50) {
962                                         $title =~ s/\/pub\/scm//;
963                                 }
964                         }
965                         $co{'title_short'} = chop_str($title, 50, 5);
966                         last;
967                 }
968         }
969         # remove added spaces
970         foreach my $line (@commit_lines) {
971                 $line =~ s/^    //;
972         }
973         $co{'comment'} = \@commit_lines;
974
975         my $age = time - $co{'committer_epoch'};
976         $co{'age'} = $age;
977         $co{'age_string'} = age_string($age);
978         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
979         if ($age > 60*60*24*7*2) {
980                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
981                 $co{'age_string_age'} = $co{'age_string'};
982         } else {
983                 $co{'age_string_date'} = $co{'age_string'};
984                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
985         }
986         return %co;
987 }
988
989 # parse ref from ref_file, given by ref_id, with given type
990 sub parse_ref {
991         my $ref_file = shift;
992         my $ref_id = shift;
993         my $type = shift || git_get_type($ref_id);
994         my %ref_item;
995
996         $ref_item{'type'} = $type;
997         $ref_item{'id'} = $ref_id;
998         $ref_item{'epoch'} = 0;
999         $ref_item{'age'} = "unknown";
1000         if ($type eq "tag") {
1001                 my %tag = parse_tag($ref_id);
1002                 $ref_item{'comment'} = $tag{'comment'};
1003                 if ($tag{'type'} eq "commit") {
1004                         my %co = parse_commit($tag{'object'});
1005                         $ref_item{'epoch'} = $co{'committer_epoch'};
1006                         $ref_item{'age'} = $co{'age_string'};
1007                 } elsif (defined($tag{'epoch'})) {
1008                         my $age = time - $tag{'epoch'};
1009                         $ref_item{'epoch'} = $tag{'epoch'};
1010                         $ref_item{'age'} = age_string($age);
1011                 }
1012                 $ref_item{'reftype'} = $tag{'type'};
1013                 $ref_item{'name'} = $tag{'name'};
1014                 $ref_item{'refid'} = $tag{'object'};
1015         } elsif ($type eq "commit"){
1016                 my %co = parse_commit($ref_id);
1017                 $ref_item{'reftype'} = "commit";
1018                 $ref_item{'name'} = $ref_file;
1019                 $ref_item{'title'} = $co{'title'};
1020                 $ref_item{'refid'} = $ref_id;
1021                 $ref_item{'epoch'} = $co{'committer_epoch'};
1022                 $ref_item{'age'} = $co{'age_string'};
1023         } else {
1024                 $ref_item{'reftype'} = $type;
1025                 $ref_item{'name'} = $ref_file;
1026                 $ref_item{'refid'} = $ref_id;
1027         }
1028
1029         return %ref_item;
1030 }
1031
1032 # parse line of git-diff-tree "raw" output
1033 sub parse_difftree_raw_line {
1034         my $line = shift;
1035         my %res;
1036
1037         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1038         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1039         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1040                 $res{'from_mode'} = $1;
1041                 $res{'to_mode'} = $2;
1042                 $res{'from_id'} = $3;
1043                 $res{'to_id'} = $4;
1044                 $res{'status'} = $5;
1045                 $res{'similarity'} = $6;
1046                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1047                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1048                 } else {
1049                         $res{'file'} = unquote($7);
1050                 }
1051         }
1052         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1053         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1054                 $res{'commit'} = $1;
1055         }
1056
1057         return wantarray ? %res : \%res;
1058 }
1059
1060 # parse line of git-ls-tree output
1061 sub parse_ls_tree_line ($;%) {
1062         my $line = shift;
1063         my %opts = @_;
1064         my %res;
1065
1066         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1067         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1068
1069         $res{'mode'} = $1;
1070         $res{'type'} = $2;
1071         $res{'hash'} = $3;
1072         if ($opts{'-z'}) {
1073                 $res{'name'} = $4;
1074         } else {
1075                 $res{'name'} = unquote($4);
1076         }
1077
1078         return wantarray ? %res : \%res;
1079 }
1080
1081 ## ......................................................................
1082 ## parse to array of hashes functions
1083
1084 sub git_get_refs_list {
1085         my $ref_dir = shift;
1086         my @reflist;
1087
1088         my @refs;
1089         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1090                 or return;
1091         while (my $line = <$fd>) {
1092                 chomp $line;
1093                 if ($line =~ m/^([0-9a-fA-F]{40})\t$ref_dir\/?([^\^]+)$/) {
1094                         push @refs, { hash => $1, name => $2 };
1095                 } elsif ($line =~ m/^[0-9a-fA-F]{40}\t$ref_dir\/?(.*)\^\{\}$/ &&
1096                          $1 eq $refs[-1]{'name'}) {
1097                         # most likely a tag is followed by its peeled
1098                         # (deref) one, and when that happens we know the
1099                         # previous one was of type 'tag'.
1100                         $refs[-1]{'type'} = "tag";
1101                 }
1102         }
1103         close $fd;
1104
1105         foreach my $ref (@refs) {
1106                 my $ref_file = $ref->{'name'};
1107                 my $ref_id   = $ref->{'hash'};
1108
1109                 my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1110                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
1111
1112                 push @reflist, \%ref_item;
1113         }
1114         # sort refs by age
1115         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1116         return \@reflist;
1117 }
1118
1119 ## ----------------------------------------------------------------------
1120 ## filesystem-related functions
1121
1122 sub get_file_owner {
1123         my $path = shift;
1124
1125         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1126         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1127         if (!defined $gcos) {
1128                 return undef;
1129         }
1130         my $owner = $gcos;
1131         $owner =~ s/[,;].*$//;
1132         return decode("utf8", $owner, Encode::FB_DEFAULT);
1133 }
1134
1135 ## ......................................................................
1136 ## mimetype related functions
1137
1138 sub mimetype_guess_file {
1139         my $filename = shift;
1140         my $mimemap = shift;
1141         -r $mimemap or return undef;
1142
1143         my %mimemap;
1144         open(MIME, $mimemap) or return undef;
1145         while (<MIME>) {
1146                 next if m/^#/; # skip comments
1147                 my ($mime, $exts) = split(/\t+/);
1148                 if (defined $exts) {
1149                         my @exts = split(/\s+/, $exts);
1150                         foreach my $ext (@exts) {
1151                                 $mimemap{$ext} = $mime;
1152                         }
1153                 }
1154         }
1155         close(MIME);
1156
1157         $filename =~ /\.(.*?)$/;
1158         return $mimemap{$1};
1159 }
1160
1161 sub mimetype_guess {
1162         my $filename = shift;
1163         my $mime;
1164         $filename =~ /\./ or return undef;
1165
1166         if ($mimetypes_file) {
1167                 my $file = $mimetypes_file;
1168                 if ($file !~ m!^/!) { # if it is relative path
1169                         # it is relative to project
1170                         $file = "$projectroot/$project/$file";
1171                 }
1172                 $mime = mimetype_guess_file($filename, $file);
1173         }
1174         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1175         return $mime;
1176 }
1177
1178 sub blob_mimetype {
1179         my $fd = shift;
1180         my $filename = shift;
1181
1182         if ($filename) {
1183                 my $mime = mimetype_guess($filename);
1184                 $mime and return $mime;
1185         }
1186
1187         # just in case
1188         return $default_blob_plain_mimetype unless $fd;
1189
1190         if (-T $fd) {
1191                 return 'text/plain' .
1192                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1193         } elsif (! $filename) {
1194                 return 'application/octet-stream';
1195         } elsif ($filename =~ m/\.png$/i) {
1196                 return 'image/png';
1197         } elsif ($filename =~ m/\.gif$/i) {
1198                 return 'image/gif';
1199         } elsif ($filename =~ m/\.jpe?g$/i) {
1200                 return 'image/jpeg';
1201         } else {
1202                 return 'application/octet-stream';
1203         }
1204 }
1205
1206 ## ======================================================================
1207 ## functions printing HTML: header, footer, error page
1208
1209 sub git_header_html {
1210         my $status = shift || "200 OK";
1211         my $expires = shift;
1212
1213         my $title = "$site_name git";
1214         if (defined $project) {
1215                 $title .= " - $project";
1216                 if (defined $action) {
1217                         $title .= "/$action";
1218                         if (defined $file_name) {
1219                                 $title .= " - $file_name";
1220                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1221                                         $title .= "/";
1222                                 }
1223                         }
1224                 }
1225         }
1226         my $content_type;
1227         # require explicit support from the UA if we are to send the page as
1228         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1229         # we have to do this because MSIE sometimes globs '*/*', pretending to
1230         # support xhtml+xml but choking when it gets what it asked for.
1231         if (defined $cgi->http('HTTP_ACCEPT') &&
1232             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1233             $cgi->Accept('application/xhtml+xml') != 0) {
1234                 $content_type = 'application/xhtml+xml';
1235         } else {
1236                 $content_type = 'text/html';
1237         }
1238         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1239                            -status=> $status, -expires => $expires);
1240         print <<EOF;
1241 <?xml version="1.0" encoding="utf-8"?>
1242 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1243 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1244 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1245 <!-- git core binaries version $git_version -->
1246 <head>
1247 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1248 <meta name="generator" content="gitweb/$version git/$git_version"/>
1249 <meta name="robots" content="index, nofollow"/>
1250 <title>$title</title>
1251 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1252 EOF
1253         if (defined $project) {
1254                 printf('<link rel="alternate" title="%s log" '.
1255                        'href="%s" type="application/rss+xml"/>'."\n",
1256                        esc_param($project), href(action=>"rss"));
1257         }
1258         if (defined $favicon) {
1259                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1260         }
1261
1262         print "</head>\n" .
1263               "<body>\n" .
1264               "<div class=\"page_header\">\n" .
1265               "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1266               "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1267               "</a>\n";
1268         print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1269         if (defined $project) {
1270                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1271                 if (defined $action) {
1272                         print " / $action";
1273                 }
1274                 print "\n";
1275                 if (!defined $searchtext) {
1276                         $searchtext = "";
1277                 }
1278                 my $search_hash;
1279                 if (defined $hash_base) {
1280                         $search_hash = $hash_base;
1281                 } elsif (defined $hash) {
1282                         $search_hash = $hash;
1283                 } else {
1284                         $search_hash = "HEAD";
1285                 }
1286                 $cgi->param("a", "search");
1287                 $cgi->param("h", $search_hash);
1288                 print $cgi->startform(-method => "get", -action => $my_uri) .
1289                       "<div class=\"search\">\n" .
1290                       $cgi->hidden(-name => "p") . "\n" .
1291                       $cgi->hidden(-name => "a") . "\n" .
1292                       $cgi->hidden(-name => "h") . "\n" .
1293                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1294                       "</div>" .
1295                       $cgi->end_form() . "\n";
1296         }
1297         print "</div>\n";
1298 }
1299
1300 sub git_footer_html {
1301         print "<div class=\"page_footer\">\n";
1302         if (defined $project) {
1303                 my $descr = git_get_project_description($project);
1304                 if (defined $descr) {
1305                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1306                 }
1307                 print $cgi->a({-href => href(action=>"rss"), -class => "rss_logo"}, "RSS") . "\n";
1308         } else {
1309                 print $cgi->a({-href => href(action=>"opml"), -class => "rss_logo"}, "OPML") . "\n";
1310         }
1311         print "</div>\n" .
1312               "</body>\n" .
1313               "</html>";
1314 }
1315
1316 sub die_error {
1317         my $status = shift || "403 Forbidden";
1318         my $error = shift || "Malformed query, file missing or permission denied";
1319
1320         git_header_html($status);
1321         print <<EOF;
1322 <div class="page_body">
1323 <br /><br />
1324 $status - $error
1325 <br />
1326 </div>
1327 EOF
1328         git_footer_html();
1329         exit;
1330 }
1331
1332 ## ----------------------------------------------------------------------
1333 ## functions printing or outputting HTML: navigation
1334
1335 sub git_print_page_nav {
1336         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1337         $extra = '' if !defined $extra; # pager or formats
1338
1339         my @navs = qw(summary shortlog log commit commitdiff tree);
1340         if ($suppress) {
1341                 @navs = grep { $_ ne $suppress } @navs;
1342         }
1343
1344         my %arg = map { $_ => {action=>$_} } @navs;
1345         if (defined $head) {
1346                 for (qw(commit commitdiff)) {
1347                         $arg{$_}{hash} = $head;
1348                 }
1349                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1350                         for (qw(shortlog log)) {
1351                                 $arg{$_}{hash} = $head;
1352                         }
1353                 }
1354         }
1355         $arg{tree}{hash} = $treehead if defined $treehead;
1356         $arg{tree}{hash_base} = $treebase if defined $treebase;
1357
1358         print "<div class=\"page_nav\">\n" .
1359                 (join " | ",
1360                  map { $_ eq $current ?
1361                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1362                  } @navs);
1363         print "<br/>\n$extra<br/>\n" .
1364               "</div>\n";
1365 }
1366
1367 sub format_paging_nav {
1368         my ($action, $hash, $head, $page, $nrevs) = @_;
1369         my $paging_nav;
1370
1371
1372         if ($hash ne $head || $page) {
1373                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1374         } else {
1375                 $paging_nav .= "HEAD";
1376         }
1377
1378         if ($page > 0) {
1379                 $paging_nav .= " &sdot; " .
1380                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1381                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1382         } else {
1383                 $paging_nav .= " &sdot; prev";
1384         }
1385
1386         if ($nrevs >= (100 * ($page+1)-1)) {
1387                 $paging_nav .= " &sdot; " .
1388                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1389                                  -accesskey => "n", -title => "Alt-n"}, "next");
1390         } else {
1391                 $paging_nav .= " &sdot; next";
1392         }
1393
1394         return $paging_nav;
1395 }
1396
1397 ## ......................................................................
1398 ## functions printing or outputting HTML: div
1399
1400 sub git_print_header_div {
1401         my ($action, $title, $hash, $hash_base) = @_;
1402         my %args = ();
1403
1404         $args{action} = $action;
1405         $args{hash} = $hash if $hash;
1406         $args{hash_base} = $hash_base if $hash_base;
1407
1408         print "<div class=\"header\">\n" .
1409               $cgi->a({-href => href(%args), -class => "title"},
1410               $title ? $title : $action) .
1411               "\n</div>\n";
1412 }
1413
1414 #sub git_print_authorship (\%) {
1415 sub git_print_authorship {
1416         my $co = shift;
1417
1418         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1419         print "<div class=\"author_date\">" .
1420               esc_html($co->{'author_name'}) .
1421               " [$ad{'rfc2822'}";
1422         if ($ad{'hour_local'} < 6) {
1423                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1424                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1425         } else {
1426                 printf(" (%02d:%02d %s)",
1427                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1428         }
1429         print "]</div>\n";
1430 }
1431
1432 sub git_print_page_path {
1433         my $name = shift;
1434         my $type = shift;
1435         my $hb = shift;
1436
1437         if (!defined $name) {
1438                 print "<div class=\"page_path\">/</div>\n";
1439         } else {
1440                 my @dirname = split '/', $name;
1441                 my $basename = pop @dirname;
1442                 my $fullname = '';
1443
1444                 print "<div class=\"page_path\">";
1445                 foreach my $dir (@dirname) {
1446                         $fullname .= $dir . '/';
1447                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1448                                                      hash_base=>$hb),
1449                                       -title => $fullname}, esc_html($dir));
1450                         print "/";
1451                 }
1452                 if (defined $type && $type eq 'blob') {
1453                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1454                                                      hash_base=>$hb),
1455                                       -title => $name}, esc_html($basename));
1456                 } elsif (defined $type && $type eq 'tree') {
1457                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1458                                                      hash_base=>$hb),
1459                                       -title => $name}, esc_html($basename));
1460                         print "/";
1461                 } else {
1462                         print esc_html($basename);
1463                 }
1464                 print "<br/></div>\n";
1465         }
1466 }
1467
1468 # sub git_print_log (\@;%) {
1469 sub git_print_log ($;%) {
1470         my $log = shift;
1471         my %opts = @_;
1472
1473         if ($opts{'-remove_title'}) {
1474                 # remove title, i.e. first line of log
1475                 shift @$log;
1476         }
1477         # remove leading empty lines
1478         while (defined $log->[0] && $log->[0] eq "") {
1479                 shift @$log;
1480         }
1481
1482         # print log
1483         my $signoff = 0;
1484         my $empty = 0;
1485         foreach my $line (@$log) {
1486                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1487                         $signoff = 1;
1488                         $empty = 0;
1489                         if (! $opts{'-remove_signoff'}) {
1490                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1491                                 next;
1492                         } else {
1493                                 # remove signoff lines
1494                                 next;
1495                         }
1496                 } else {
1497                         $signoff = 0;
1498                 }
1499
1500                 # print only one empty line
1501                 # do not print empty line after signoff
1502                 if ($line eq "") {
1503                         next if ($empty || $signoff);
1504                         $empty = 1;
1505                 } else {
1506                         $empty = 0;
1507                 }
1508
1509                 print format_log_line_html($line) . "<br/>\n";
1510         }
1511
1512         if ($opts{'-final_empty_line'}) {
1513                 # end with single empty line
1514                 print "<br/>\n" unless $empty;
1515         }
1516 }
1517
1518 sub git_print_simplified_log {
1519         my $log = shift;
1520         my $remove_title = shift;
1521
1522         git_print_log($log,
1523                 -final_empty_line=> 1,
1524                 -remove_title => $remove_title);
1525 }
1526
1527 # print tree entry (row of git_tree), but without encompassing <tr> element
1528 sub git_print_tree_entry {
1529         my ($t, $basedir, $hash_base, $have_blame) = @_;
1530
1531         my %base_key = ();
1532         $base_key{hash_base} = $hash_base if defined $hash_base;
1533
1534         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1535         if ($t->{'type'} eq "blob") {
1536                 print "<td class=\"list\">" .
1537                       $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1538                                              file_name=>"$basedir$t->{'name'}", %base_key),
1539                               -class => "list"}, esc_html($t->{'name'})) .
1540                       "</td>\n" .
1541                       "<td class=\"link\">" .
1542                       $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1543                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1544                               "blob");
1545                 if ($have_blame) {
1546                         print " | " .
1547                                 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1548                                                        file_name=>"$basedir$t->{'name'}", %base_key)},
1549                                         "blame");
1550                 }
1551                 if (defined $hash_base) {
1552                         print " | " .
1553                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1554                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1555                                       "history");
1556                 }
1557                 print " | " .
1558                       $cgi->a({-href => href(action=>"blob_plain",
1559                                              hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1560                               "raw") .
1561                       "</td>\n";
1562
1563         } elsif ($t->{'type'} eq "tree") {
1564                 print "<td class=\"list\">" .
1565                       $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1566                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1567                               esc_html($t->{'name'})) .
1568                       "</td>\n" .
1569                       "<td class=\"link\">" .
1570                       $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1571                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1572                               "tree");
1573                 if (defined $hash_base) {
1574                         print " | " .
1575                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1576                                                      file_name=>"$basedir$t->{'name'}")},
1577                                       "history");
1578                 }
1579                 print "</td>\n";
1580         }
1581 }
1582
1583 ## ......................................................................
1584 ## functions printing large fragments of HTML
1585
1586 sub git_difftree_body {
1587         my ($difftree, $hash, $parent) = @_;
1588
1589         print "<div class=\"list_head\">\n";
1590         if ($#{$difftree} > 10) {
1591                 print(($#{$difftree} + 1) . " files changed:\n");
1592         }
1593         print "</div>\n";
1594
1595         print "<table class=\"diff_tree\">\n";
1596         my $alternate = 0;
1597         my $patchno = 0;
1598         foreach my $line (@{$difftree}) {
1599                 my %diff = parse_difftree_raw_line($line);
1600
1601                 if ($alternate) {
1602                         print "<tr class=\"dark\">\n";
1603                 } else {
1604                         print "<tr class=\"light\">\n";
1605                 }
1606                 $alternate ^= 1;
1607
1608                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1609                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1610                 if ($diff{'to_mode'} ne ('0' x 6)) {
1611                         $to_mode_oct = oct $diff{'to_mode'};
1612                         if (S_ISREG($to_mode_oct)) { # only for regular file
1613                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1614                         }
1615                         $to_file_type = file_type($diff{'to_mode'});
1616                 }
1617                 if ($diff{'from_mode'} ne ('0' x 6)) {
1618                         $from_mode_oct = oct $diff{'from_mode'};
1619                         if (S_ISREG($to_mode_oct)) { # only for regular file
1620                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1621                         }
1622                         $from_file_type = file_type($diff{'from_mode'});
1623                 }
1624
1625                 if ($diff{'status'} eq "A") { # created
1626                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1627                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1628                         $mode_chng   .= "]</span>";
1629                         print "<td>" .
1630                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1631                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1632                                       -class => "list"}, esc_html($diff{'file'})) .
1633                               "</td>\n" .
1634                               "<td>$mode_chng</td>\n" .
1635                               "<td class=\"link\">" .
1636                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1637                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1638                                       "blob");
1639                         if ($action eq 'commitdiff') {
1640                                 # link to patch
1641                                 $patchno++;
1642                                 print " | " .
1643                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1644                         }
1645                         print "</td>\n";
1646
1647                 } elsif ($diff{'status'} eq "D") { # deleted
1648                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1649                         print "<td>" .
1650                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1651                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1652                                        -class => "list"}, esc_html($diff{'file'})) .
1653                               "</td>\n" .
1654                               "<td>$mode_chng</td>\n" .
1655                               "<td class=\"link\">" .
1656                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1657                                                      hash_base=>$parent, file_name=>$diff{'file'})},
1658                                       "blob") .
1659                               " | ";
1660                         if ($action eq 'commitdiff') {
1661                                 # link to patch
1662                                 $patchno++;
1663                                 print " | " .
1664                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1665                         }
1666                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1667                                                      file_name=>$diff{'file'})},
1668                                       "history") .
1669                               "</td>\n";
1670
1671                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1672                         my $mode_chnge = "";
1673                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1674                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1675                                 if ($from_file_type != $to_file_type) {
1676                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1677                                 }
1678                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1679                                         if ($from_mode_str && $to_mode_str) {
1680                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1681                                         } elsif ($to_mode_str) {
1682                                                 $mode_chnge .= " mode: $to_mode_str";
1683                                         }
1684                                 }
1685                                 $mode_chnge .= "]</span>\n";
1686                         }
1687                         print "<td>";
1688                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1689                                 print $cgi->a({-href => href(action=>"blobdiff",
1690                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1691                                                              hash_base=>$hash, hash_parent_base=>$parent,
1692                                                              file_name=>$diff{'file'}),
1693                                               -class => "list"}, esc_html($diff{'file'}));
1694                         } else { # only mode changed
1695                                 print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1696                                                              hash_base=>$hash, file_name=>$diff{'file'}),
1697                                               -class => "list"}, esc_html($diff{'file'}));
1698                         }
1699                         print "</td>\n" .
1700                               "<td>$mode_chnge</td>\n" .
1701                               "<td class=\"link\">" .
1702                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1703                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1704                                       "blob");
1705                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1706                                 if ($action eq 'commitdiff') {
1707                                         # link to patch
1708                                         $patchno++;
1709                                         print " | " .
1710                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1711                                 } else {
1712                                         print " | " .
1713                                                 $cgi->a({-href => href(action=>"blobdiff",
1714                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1715                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1716                                                                        file_name=>$diff{'file'})},
1717                                                         "diff");
1718                                 }
1719                         }
1720                         print " | " .
1721                                 $cgi->a({-href => href(action=>"history",
1722                                                        hash_base=>$hash, file_name=>$diff{'file'})},
1723                                         "history");
1724                         print "</td>\n";
1725
1726                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1727                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1728                         my $nstatus = $status_name{$diff{'status'}};
1729                         my $mode_chng = "";
1730                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1731                                 # mode also for directories, so we cannot use $to_mode_str
1732                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1733                         }
1734                         print "<td>" .
1735                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1736                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1737                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1738                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1739                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1740                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1741                                       -class => "list"}, esc_html($diff{'from_file'})) .
1742                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1743                               "<td class=\"link\">" .
1744                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1745                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1746                                       "blob");
1747                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1748                                 if ($action eq 'commitdiff') {
1749                                         # link to patch
1750                                         $patchno++;
1751                                         print " | " .
1752                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1753                                 } else {
1754                                         print " | " .
1755                                                 $cgi->a({-href => href(action=>"blobdiff",
1756                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1757                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1758                                                                        file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1759                                                         "diff");
1760                                 }
1761                         }
1762                         print "</td>\n";
1763
1764                 } # we should not encounter Unmerged (U) or Unknown (X) status
1765                 print "</tr>\n";
1766         }
1767         print "</table>\n";
1768 }
1769
1770 sub git_patchset_body {
1771         my ($fd, $difftree, $hash, $hash_parent) = @_;
1772
1773         my $patch_idx = 0;
1774         my $in_header = 0;
1775         my $patch_found = 0;
1776         my $diffinfo;
1777
1778         print "<div class=\"patchset\">\n";
1779
1780         LINE:
1781         while (my $patch_line = <$fd>) {
1782                 chomp $patch_line;
1783
1784                 if ($patch_line =~ m/^diff /) { # "git diff" header
1785                         # beginning of patch (in patchset)
1786                         if ($patch_found) {
1787                                 # close previous patch
1788                                 print "</div>\n"; # class="patch"
1789                         } else {
1790                                 # first patch in patchset
1791                                 $patch_found = 1;
1792                         }
1793                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1794
1795                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1796                                 $diffinfo = $difftree->[$patch_idx];
1797                         } else {
1798                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1799                         }
1800                         $patch_idx++;
1801
1802                         # for now, no extended header, hence we skip empty patches
1803                         # companion to  next LINE if $in_header;
1804                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1805                                 $in_header = 1;
1806                                 next LINE;
1807                         }
1808
1809                         if ($diffinfo->{'status'} eq "A") { # added
1810                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1811                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1812                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1813                                               $diffinfo->{'to_id'}) . "(new)" .
1814                                       "</div>\n"; # class="diff_info"
1815
1816                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1817                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1818                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1819                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1820                                               $diffinfo->{'from_id'}) . "(deleted)" .
1821                                       "</div>\n"; # class="diff_info"
1822
1823                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1824                                  $diffinfo->{'status'} eq "C" || # copied
1825                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1826                                 print "<div class=\"diff_info\">" .
1827                                       file_type($diffinfo->{'from_mode'}) . ":" .
1828                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1829                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1830                                               $diffinfo->{'from_id'}) .
1831                                       " -> " .
1832                                       file_type($diffinfo->{'to_mode'}) . ":" .
1833                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1834                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1835                                               $diffinfo->{'to_id'});
1836                                 print "</div>\n"; # class="diff_info"
1837
1838                         } else { # modified, mode changed, ...
1839                                 print "<div class=\"diff_info\">" .
1840                                       file_type($diffinfo->{'from_mode'}) . ":" .
1841                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1842                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1843                                               $diffinfo->{'from_id'}) .
1844                                       " -> " .
1845                                       file_type($diffinfo->{'to_mode'}) . ":" .
1846                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1847                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1848                                               $diffinfo->{'to_id'});
1849                                 print "</div>\n"; # class="diff_info"
1850                         }
1851
1852                         #print "<div class=\"diff extended_header\">\n";
1853                         $in_header = 1;
1854                         next LINE;
1855                 } # start of patch in patchset
1856
1857
1858                 if ($in_header && $patch_line =~ m/^---/) {
1859                         #print "</div>\n"; # class="diff extended_header"
1860                         $in_header = 0;
1861
1862                         my $file = $diffinfo->{'from_file'};
1863                         $file  ||= $diffinfo->{'file'};
1864                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1865                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
1866                                         -class => "list"}, esc_html($file));
1867                         $patch_line =~ s|a/.*$|a/$file|g;
1868                         print "<div class=\"diff from_file\">$patch_line</div>\n";
1869
1870                         $patch_line = <$fd>;
1871                         chomp $patch_line;
1872
1873                         #$patch_line =~ m/^+++/;
1874                         $file    = $diffinfo->{'to_file'};
1875                         $file  ||= $diffinfo->{'file'};
1876                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1877                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
1878                                         -class => "list"}, esc_html($file));
1879                         $patch_line =~ s|b/.*|b/$file|g;
1880                         print "<div class=\"diff to_file\">$patch_line</div>\n";
1881
1882                         next LINE;
1883                 }
1884                 next LINE if $in_header;
1885
1886                 print format_diff_line($patch_line);
1887         }
1888         print "</div>\n" if $patch_found; # class="patch"
1889
1890         print "</div>\n"; # class="patchset"
1891 }
1892
1893 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1894
1895 sub git_shortlog_body {
1896         # uses global variable $project
1897         my ($revlist, $from, $to, $refs, $extra) = @_;
1898
1899         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
1900         my $have_snapshot = (defined $ctype && defined $suffix);
1901
1902         $from = 0 unless defined $from;
1903         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1904
1905         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1906         my $alternate = 0;
1907         for (my $i = $from; $i <= $to; $i++) {
1908                 my $commit = $revlist->[$i];
1909                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1910                 my $ref = format_ref_marker($refs, $commit);
1911                 my %co = parse_commit($commit);
1912                 if ($alternate) {
1913                         print "<tr class=\"dark\">\n";
1914                 } else {
1915                         print "<tr class=\"light\">\n";
1916                 }
1917                 $alternate ^= 1;
1918                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1919                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1920                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1921                       "<td>";
1922                 print format_subject_html($co{'title'}, $co{'title_short'},
1923                                           href(action=>"commit", hash=>$commit), $ref);
1924                 print "</td>\n" .
1925                       "<td class=\"link\">" .
1926                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1927                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
1928                 if ($have_snapshot) {
1929                         print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
1930                 }
1931                 print "</td>\n" .
1932                       "</tr>\n";
1933         }
1934         if (defined $extra) {
1935                 print "<tr>\n" .
1936                       "<td colspan=\"4\">$extra</td>\n" .
1937                       "</tr>\n";
1938         }
1939         print "</table>\n";
1940 }
1941
1942 sub git_history_body {
1943         # Warning: assumes constant type (blob or tree) during history
1944         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
1945
1946         $from = 0 unless defined $from;
1947         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
1948
1949         print "<table class=\"history\" cellspacing=\"0\">\n";
1950         my $alternate = 0;
1951         for (my $i = $from; $i <= $to; $i++) {
1952                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
1953                         next;
1954                 }
1955
1956                 my $commit = $1;
1957                 my %co = parse_commit($commit);
1958                 if (!%co) {
1959                         next;
1960                 }
1961
1962                 my $ref = format_ref_marker($refs, $commit);
1963
1964                 if ($alternate) {
1965                         print "<tr class=\"dark\">\n";
1966                 } else {
1967                         print "<tr class=\"light\">\n";
1968                 }
1969                 $alternate ^= 1;
1970                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1971                       # shortlog uses      chop_str($co{'author_name'}, 10)
1972                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
1973                       "<td>";
1974                 # originally git_history used chop_str($co{'title'}, 50)
1975                 print format_subject_html($co{'title'}, $co{'title_short'},
1976                                           href(action=>"commit", hash=>$commit), $ref);
1977                 print "</td>\n" .
1978                       "<td class=\"link\">" .
1979                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1980                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
1981                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
1982
1983                 if ($ftype eq 'blob') {
1984                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
1985                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
1986                         if (defined $blob_current && defined $blob_parent &&
1987                                         $blob_current ne $blob_parent) {
1988                                 print " | " .
1989                                         $cgi->a({-href => href(action=>"blobdiff",
1990                                                                hash=>$blob_current, hash_parent=>$blob_parent,
1991                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
1992                                                                file_name=>$file_name)},
1993                                                 "diff to current");
1994                         }
1995                 }
1996                 print "</td>\n" .
1997                       "</tr>\n";
1998         }
1999         if (defined $extra) {
2000                 print "<tr>\n" .
2001                       "<td colspan=\"4\">$extra</td>\n" .
2002                       "</tr>\n";
2003         }
2004         print "</table>\n";
2005 }
2006
2007 sub git_tags_body {
2008         # uses global variable $project
2009         my ($taglist, $from, $to, $extra) = @_;
2010         $from = 0 unless defined $from;
2011         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2012
2013         print "<table class=\"tags\" cellspacing=\"0\">\n";
2014         my $alternate = 0;
2015         for (my $i = $from; $i <= $to; $i++) {
2016                 my $entry = $taglist->[$i];
2017                 my %tag = %$entry;
2018                 my $comment_lines = $tag{'comment'};
2019                 my $comment = shift @$comment_lines;
2020                 my $comment_short;
2021                 if (defined $comment) {
2022                         $comment_short = chop_str($comment, 30, 5);
2023                 }
2024                 if ($alternate) {
2025                         print "<tr class=\"dark\">\n";
2026                 } else {
2027                         print "<tr class=\"light\">\n";
2028                 }
2029                 $alternate ^= 1;
2030                 print "<td><i>$tag{'age'}</i></td>\n" .
2031                       "<td>" .
2032                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2033                                -class => "list name"}, esc_html($tag{'name'})) .
2034                       "</td>\n" .
2035                       "<td>";
2036                 if (defined $comment) {
2037                         print format_subject_html($comment, $comment_short,
2038                                                   href(action=>"tag", hash=>$tag{'id'}));
2039                 }
2040                 print "</td>\n" .
2041                       "<td class=\"selflink\">";
2042                 if ($tag{'type'} eq "tag") {
2043                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2044                 } else {
2045                         print "&nbsp;";
2046                 }
2047                 print "</td>\n" .
2048                       "<td class=\"link\">" . " | " .
2049                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2050                 if ($tag{'reftype'} eq "commit") {
2051                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2052                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2053                 } elsif ($tag{'reftype'} eq "blob") {
2054                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2055                 }
2056                 print "</td>\n" .
2057                       "</tr>";
2058         }
2059         if (defined $extra) {
2060                 print "<tr>\n" .
2061                       "<td colspan=\"5\">$extra</td>\n" .
2062                       "</tr>\n";
2063         }
2064         print "</table>\n";
2065 }
2066
2067 sub git_heads_body {
2068         # uses global variable $project
2069         my ($taglist, $head, $from, $to, $extra) = @_;
2070         $from = 0 unless defined $from;
2071         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2072
2073         print "<table class=\"heads\" cellspacing=\"0\">\n";
2074         my $alternate = 0;
2075         for (my $i = $from; $i <= $to; $i++) {
2076                 my $entry = $taglist->[$i];
2077                 my %tag = %$entry;
2078                 my $curr = $tag{'id'} eq $head;
2079                 if ($alternate) {
2080                         print "<tr class=\"dark\">\n";
2081                 } else {
2082                         print "<tr class=\"light\">\n";
2083                 }
2084                 $alternate ^= 1;
2085                 print "<td><i>$tag{'age'}</i></td>\n" .
2086                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2087                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2088                                -class => "list name"},esc_html($tag{'name'})) .
2089                       "</td>\n" .
2090                       "<td class=\"link\">" .
2091                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2092                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
2093                       "</td>\n" .
2094                       "</tr>";
2095         }
2096         if (defined $extra) {
2097                 print "<tr>\n" .
2098                       "<td colspan=\"3\">$extra</td>\n" .
2099                       "</tr>\n";
2100         }
2101         print "</table>\n";
2102 }
2103
2104 ## ======================================================================
2105 ## ======================================================================
2106 ## actions
2107
2108 sub git_project_list {
2109         my $order = $cgi->param('o');
2110         if (defined $order && $order !~ m/project|descr|owner|age/) {
2111                 die_error(undef, "Unknown order parameter");
2112         }
2113
2114         my @list = git_get_projects_list();
2115         my @projects;
2116         if (!@list) {
2117                 die_error(undef, "No projects found");
2118         }
2119         foreach my $pr (@list) {
2120                 my $head = git_get_head_hash($pr->{'path'});
2121                 if (!defined $head) {
2122                         next;
2123                 }
2124                 $git_dir = "$projectroot/$pr->{'path'}";
2125                 my %co = parse_commit($head);
2126                 if (!%co) {
2127                         next;
2128                 }
2129                 $pr->{'commit'} = \%co;
2130                 if (!defined $pr->{'descr'}) {
2131                         my $descr = git_get_project_description($pr->{'path'}) || "";
2132                         $pr->{'descr'} = chop_str($descr, 25, 5);
2133                 }
2134                 if (!defined $pr->{'owner'}) {
2135                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2136                 }
2137                 push @projects, $pr;
2138         }
2139
2140         git_header_html();
2141         if (-f $home_text) {
2142                 print "<div class=\"index_include\">\n";
2143                 open (my $fd, $home_text);
2144                 print <$fd>;
2145                 close $fd;
2146                 print "</div>\n";
2147         }
2148         print "<table class=\"project_list\">\n" .
2149               "<tr>\n";
2150         $order ||= "project";
2151         if ($order eq "project") {
2152                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2153                 print "<th>Project</th>\n";
2154         } else {
2155                 print "<th>" .
2156                       $cgi->a({-href => "$my_uri?" . esc_param("o=project"),
2157                                -class => "header"}, "Project") .
2158                       "</th>\n";
2159         }
2160         if ($order eq "descr") {
2161                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2162                 print "<th>Description</th>\n";
2163         } else {
2164                 print "<th>" .
2165                       $cgi->a({-href => "$my_uri?" . esc_param("o=descr"),
2166                                -class => "header"}, "Description") .
2167                       "</th>\n";
2168         }
2169         if ($order eq "owner") {
2170                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2171                 print "<th>Owner</th>\n";
2172         } else {
2173                 print "<th>" .
2174                       $cgi->a({-href => "$my_uri?" . esc_param("o=owner"),
2175                                -class => "header"}, "Owner") .
2176                       "</th>\n";
2177         }
2178         if ($order eq "age") {
2179                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2180                 print "<th>Last Change</th>\n";
2181         } else {
2182                 print "<th>" .
2183                       $cgi->a({-href => "$my_uri?" . esc_param("o=age"),
2184                                -class => "header"}, "Last Change") .
2185                       "</th>\n";
2186         }
2187         print "<th></th>\n" .
2188               "</tr>\n";
2189         my $alternate = 0;
2190         foreach my $pr (@projects) {
2191                 if ($alternate) {
2192                         print "<tr class=\"dark\">\n";
2193                 } else {
2194                         print "<tr class=\"light\">\n";
2195                 }
2196                 $alternate ^= 1;
2197                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2198                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2199                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2200                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2201                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2202                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2203                       "<td class=\"link\">" .
2204                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2205                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2206                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
2207                       "</td>\n" .
2208                       "</tr>\n";
2209         }
2210         print "</table>\n";
2211         git_footer_html();
2212 }
2213
2214 sub git_project_index {
2215         my @projects = git_get_projects_list();
2216
2217         print $cgi->header(
2218                 -type => 'text/plain',
2219                 -charset => 'utf-8',
2220                 -content_disposition => qq(inline; filename="index.aux"));
2221
2222         foreach my $pr (@projects) {
2223                 if (!exists $pr->{'owner'}) {
2224                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2225                 }
2226
2227                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2228                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2229                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2230                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2231                 $path  =~ s/ /\+/g;
2232                 $owner =~ s/ /\+/g;
2233
2234                 print "$path $owner\n";
2235         }
2236 }
2237
2238 sub git_summary {
2239         my $descr = git_get_project_description($project) || "none";
2240         my $head = git_get_head_hash($project);
2241         my %co = parse_commit($head);
2242         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2243
2244         my $owner = git_get_project_owner($project);
2245
2246         my $refs = git_get_references();
2247         git_header_html();
2248         git_print_page_nav('summary','', $head);
2249
2250         print "<div class=\"title\">&nbsp;</div>\n";
2251         print "<table cellspacing=\"0\">\n" .
2252               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2253               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2254               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2255         # use per project git URL list in $projectroot/$project/cloneurl
2256         # or make project git URL from git base URL and project name
2257         my $url_tag = "URL";
2258         my @url_list = git_get_project_url_list($project);
2259         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2260         foreach my $git_url (@url_list) {
2261                 next unless $git_url;
2262                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2263                 $url_tag = "";
2264         }
2265         print "</table>\n";
2266
2267         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2268                 git_get_head_hash($project)
2269                 or die_error(undef, "Open git-rev-list failed");
2270         my @revlist = map { chomp; $_ } <$fd>;
2271         close $fd;
2272         git_print_header_div('shortlog');
2273         git_shortlog_body(\@revlist, 0, 15, $refs,
2274                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2275
2276         my $taglist = git_get_refs_list("refs/tags");
2277         if (defined @$taglist) {
2278                 git_print_header_div('tags');
2279                 git_tags_body($taglist, 0, 15,
2280                               $cgi->a({-href => href(action=>"tags")}, "..."));
2281         }
2282
2283         my $headlist = git_get_refs_list("refs/heads");
2284         if (defined @$headlist) {
2285                 git_print_header_div('heads');
2286                 git_heads_body($headlist, $head, 0, 15,
2287                                $cgi->a({-href => href(action=>"heads")}, "..."));
2288         }
2289
2290         git_footer_html();
2291 }
2292
2293 sub git_tag {
2294         my $head = git_get_head_hash($project);
2295         git_header_html();
2296         git_print_page_nav('','', $head,undef,$head);
2297         my %tag = parse_tag($hash);
2298         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2299         print "<div class=\"title_text\">\n" .
2300               "<table cellspacing=\"0\">\n" .
2301               "<tr>\n" .
2302               "<td>object</td>\n" .
2303               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2304                                $tag{'object'}) . "</td>\n" .
2305               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2306                                               $tag{'type'}) . "</td>\n" .
2307               "</tr>\n";
2308         if (defined($tag{'author'})) {
2309                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2310                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2311                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2312                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2313                         "</td></tr>\n";
2314         }
2315         print "</table>\n\n" .
2316               "</div>\n";
2317         print "<div class=\"page_body\">";
2318         my $comment = $tag{'comment'};
2319         foreach my $line (@$comment) {
2320                 print esc_html($line) . "<br/>\n";
2321         }
2322         print "</div>\n";
2323         git_footer_html();
2324 }
2325
2326 sub git_blame2 {
2327         my $fd;
2328         my $ftype;
2329
2330         my ($have_blame) = gitweb_check_feature('blame');
2331         if (!$have_blame) {
2332                 die_error('403 Permission denied', "Permission denied");
2333         }
2334         die_error('404 Not Found', "File name not defined") if (!$file_name);
2335         $hash_base ||= git_get_head_hash($project);
2336         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2337         my %co = parse_commit($hash_base)
2338                 or die_error(undef, "Reading commit failed");
2339         if (!defined $hash) {
2340                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2341                         or die_error(undef, "Error looking up file");
2342         }
2343         $ftype = git_get_type($hash);
2344         if ($ftype !~ "blob") {
2345                 die_error("400 Bad Request", "Object is not a blob");
2346         }
2347         open ($fd, "-|", git_cmd(), "blame", '-l', $file_name, $hash_base)
2348                 or die_error(undef, "Open git-blame failed");
2349         git_header_html();
2350         my $formats_nav =
2351                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2352                         "blob") .
2353                 " | " .
2354                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2355                         "head");
2356         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2357         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2358         git_print_page_path($file_name, $ftype, $hash_base);
2359         my @rev_color = (qw(light2 dark2));
2360         my $num_colors = scalar(@rev_color);
2361         my $current_color = 0;
2362         my $last_rev;
2363         print <<HTML;
2364 <div class="page_body">
2365 <table class="blame">
2366 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2367 HTML
2368         while (<$fd>) {
2369                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2370                 my $full_rev = $1;
2371                 my $rev = substr($full_rev, 0, 8);
2372                 my $lineno = $2;
2373                 my $data = $3;
2374
2375                 if (!defined $last_rev) {
2376                         $last_rev = $full_rev;
2377                 } elsif ($last_rev ne $full_rev) {
2378                         $last_rev = $full_rev;
2379                         $current_color = ++$current_color % $num_colors;
2380                 }
2381                 print "<tr class=\"$rev_color[$current_color]\">\n";
2382                 print "<td class=\"sha1\">" .
2383                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2384                                 esc_html($rev)) . "</td>\n";
2385                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2386                       esc_html($lineno) . "</a></td>\n";
2387                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2388                 print "</tr>\n";
2389         }
2390         print "</table>\n";
2391         print "</div>";
2392         close $fd
2393                 or print "Reading blob failed\n";
2394         git_footer_html();
2395 }
2396
2397 sub git_blame {
2398         my $fd;
2399
2400         my ($have_blame) = gitweb_check_feature('blame');
2401         if (!$have_blame) {
2402                 die_error('403 Permission denied', "Permission denied");
2403         }
2404         die_error('404 Not Found', "File name not defined") if (!$file_name);
2405         $hash_base ||= git_get_head_hash($project);
2406         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2407         my %co = parse_commit($hash_base)
2408                 or die_error(undef, "Reading commit failed");
2409         if (!defined $hash) {
2410                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2411                         or die_error(undef, "Error lookup file");
2412         }
2413         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2414                 or die_error(undef, "Open git-annotate failed");
2415         git_header_html();
2416         my $formats_nav =
2417                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2418                         "blob") .
2419                 " | " .
2420                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2421                         "head");
2422         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2423         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2424         git_print_page_path($file_name, 'blob', $hash_base);
2425         print "<div class=\"page_body\">\n";
2426         print <<HTML;
2427 <table class="blame">
2428   <tr>
2429     <th>Commit</th>
2430     <th>Age</th>
2431     <th>Author</th>
2432     <th>Line</th>
2433     <th>Data</th>
2434   </tr>
2435 HTML
2436         my @line_class = (qw(light dark));
2437         my $line_class_len = scalar (@line_class);
2438         my $line_class_num = $#line_class;
2439         while (my $line = <$fd>) {
2440                 my $long_rev;
2441                 my $short_rev;
2442                 my $author;
2443                 my $time;
2444                 my $lineno;
2445                 my $data;
2446                 my $age;
2447                 my $age_str;
2448                 my $age_class;
2449
2450                 chomp $line;
2451                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2452
2453                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2454                         $long_rev = $1;
2455                         $author   = $2;
2456                         $time     = $3;
2457                         $lineno   = $4;
2458                         $data     = $5;
2459                 } else {
2460                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2461                         next;
2462                 }
2463                 $short_rev  = substr ($long_rev, 0, 8);
2464                 $age        = time () - $time;
2465                 $age_str    = age_string ($age);
2466                 $age_str    =~ s/ /&nbsp;/g;
2467                 $age_class  = age_class($age);
2468                 $author     = esc_html ($author);
2469                 $author     =~ s/ /&nbsp;/g;
2470
2471                 $data = untabify($data);
2472                 $data = esc_html ($data);
2473
2474                 print <<HTML;
2475   <tr class="$line_class[$line_class_num]">
2476     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2477     <td class="$age_class">$age_str</td>
2478     <td>$author</td>
2479     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2480     <td class="pre">$data</td>
2481   </tr>
2482 HTML
2483         } # while (my $line = <$fd>)
2484         print "</table>\n\n";
2485         close $fd
2486                 or print "Reading blob failed.\n";
2487         print "</div>";
2488         git_footer_html();
2489 }
2490
2491 sub git_tags {
2492         my $head = git_get_head_hash($project);
2493         git_header_html();
2494         git_print_page_nav('','', $head,undef,$head);
2495         git_print_header_div('summary', $project);
2496
2497         my $taglist = git_get_refs_list("refs/tags");
2498         if (defined @$taglist) {
2499                 git_tags_body($taglist);
2500         }
2501         git_footer_html();
2502 }
2503
2504 sub git_heads {
2505         my $head = git_get_head_hash($project);
2506         git_header_html();
2507         git_print_page_nav('','', $head,undef,$head);
2508         git_print_header_div('summary', $project);
2509
2510         my $taglist = git_get_refs_list("refs/heads");
2511         if (defined @$taglist) {
2512                 git_heads_body($taglist, $head);
2513         }
2514         git_footer_html();
2515 }
2516
2517 sub git_blob_plain {
2518         # blobs defined by non-textual hash id's can be cached
2519         my $expires;
2520         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2521                 $expires = "+1d";
2522         }
2523
2524         if (!defined $hash) {
2525                 if (defined $file_name) {
2526                         my $base = $hash_base || git_get_head_hash($project);
2527                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2528                                 or die_error(undef, "Error lookup file");
2529                 } else {
2530                         die_error(undef, "No file name defined");
2531                 }
2532         }
2533         my $type = shift;
2534         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2535                 or die_error(undef, "Couldn't cat $file_name, $hash");
2536
2537         $type ||= blob_mimetype($fd, $file_name);
2538
2539         # save as filename, even when no $file_name is given
2540         my $save_as = "$hash";
2541         if (defined $file_name) {
2542                 $save_as = $file_name;
2543         } elsif ($type =~ m/^text\//) {
2544                 $save_as .= '.txt';
2545         }
2546
2547         print $cgi->header(
2548                 -type => "$type",
2549                 -expires=>$expires,
2550                 -content_disposition => "inline; filename=\"$save_as\"");
2551         undef $/;
2552         binmode STDOUT, ':raw';
2553         print <$fd>;
2554         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2555         $/ = "\n";
2556         close $fd;
2557 }
2558
2559 sub git_blob {
2560         # blobs defined by non-textual hash id's can be cached
2561         my $expires;
2562         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2563                 $expires = "+1d";
2564         }
2565
2566         if (!defined $hash) {
2567                 if (defined $file_name) {
2568                         my $base = $hash_base || git_get_head_hash($project);
2569                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2570                                 or die_error(undef, "Error lookup file");
2571                 } else {
2572                         die_error(undef, "No file name defined");
2573                 }
2574         }
2575         my ($have_blame) = gitweb_check_feature('blame');
2576         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2577                 or die_error(undef, "Couldn't cat $file_name, $hash");
2578         my $mimetype = blob_mimetype($fd, $file_name);
2579         if ($mimetype !~ m/^text\//) {
2580                 close $fd;
2581                 return git_blob_plain($mimetype);
2582         }
2583         git_header_html(undef, $expires);
2584         my $formats_nav = '';
2585         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2586                 if (defined $file_name) {
2587                         if ($have_blame) {
2588                                 $formats_nav .=
2589                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2590                                                                hash=>$hash, file_name=>$file_name)},
2591                                                 "blame") .
2592                                         " | ";
2593                         }
2594                         $formats_nav .=
2595                                 $cgi->a({-href => href(action=>"blob_plain",
2596                                                        hash=>$hash, file_name=>$file_name)},
2597                                         "plain") .
2598                                 " | " .
2599                                 $cgi->a({-href => href(action=>"blob",
2600                                                        hash_base=>"HEAD", file_name=>$file_name)},
2601                                         "head");
2602                 } else {
2603                         $formats_nav .=
2604                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2605                 }
2606                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2607                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2608         } else {
2609                 print "<div class=\"page_nav\">\n" .
2610                       "<br/><br/></div>\n" .
2611                       "<div class=\"title\">$hash</div>\n";
2612         }
2613         git_print_page_path($file_name, "blob", $hash_base);
2614         print "<div class=\"page_body\">\n";
2615         my $nr;
2616         while (my $line = <$fd>) {
2617                 chomp $line;
2618                 $nr++;
2619                 $line = untabify($line);
2620                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2621                        $nr, $nr, $nr, esc_html($line);
2622         }
2623         close $fd
2624                 or print "Reading blob failed.\n";
2625         print "</div>";
2626         git_footer_html();
2627 }
2628
2629 sub git_tree {
2630         if (!defined $hash) {
2631                 $hash = git_get_head_hash($project);
2632                 if (defined $file_name) {
2633                         my $base = $hash_base || $hash;
2634                         $hash = git_get_hash_by_path($base, $file_name, "tree");
2635                 }
2636                 if (!defined $hash_base) {
2637                         $hash_base = $hash;
2638                 }
2639         }
2640         $/ = "\0";
2641         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2642                 or die_error(undef, "Open git-ls-tree failed");
2643         my @entries = map { chomp; $_ } <$fd>;
2644         close $fd or die_error(undef, "Reading tree failed");
2645         $/ = "\n";
2646
2647         my $refs = git_get_references();
2648         my $ref = format_ref_marker($refs, $hash_base);
2649         git_header_html();
2650         my $base = "";
2651         my ($have_blame) = gitweb_check_feature('blame');
2652         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2653                 git_print_page_nav('tree','', $hash_base);
2654                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2655         } else {
2656                 undef $hash_base;
2657                 print "<div class=\"page_nav\">\n";
2658                 print "<br/><br/></div>\n";
2659                 print "<div class=\"title\">$hash</div>\n";
2660         }
2661         if (defined $file_name) {
2662                 $base = esc_html("$file_name/");
2663         }
2664         git_print_page_path($file_name, 'tree', $hash_base);
2665         print "<div class=\"page_body\">\n";
2666         print "<table cellspacing=\"0\">\n";
2667         my $alternate = 0;
2668         foreach my $line (@entries) {
2669                 my %t = parse_ls_tree_line($line, -z => 1);
2670
2671                 if ($alternate) {
2672                         print "<tr class=\"dark\">\n";
2673                 } else {
2674                         print "<tr class=\"light\">\n";
2675                 }
2676                 $alternate ^= 1;
2677
2678                 git_print_tree_entry(\%t, $base, $hash_base, $have_blame);
2679
2680                 print "</tr>\n";
2681         }
2682         print "</table>\n" .
2683               "</div>";
2684         git_footer_html();
2685 }
2686
2687 sub git_snapshot {
2688
2689         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2690         my $have_snapshot = (defined $ctype && defined $suffix);
2691         if (!$have_snapshot) {
2692                 die_error('403 Permission denied', "Permission denied");
2693         }
2694
2695         if (!defined $hash) {
2696                 $hash = git_get_head_hash($project);
2697         }
2698
2699         my $filename = basename($project) . "-$hash.tar.$suffix";
2700
2701         print $cgi->header(-type => 'application/x-tar',
2702                            -content_encoding => $ctype,
2703                            -content_disposition => "inline; filename=\"$filename\"",
2704                            -status => '200 OK');
2705
2706         my $git_command = git_cmd_str();
2707         open my $fd, "-|", "$git_command tar-tree $hash \'$project\' | $command" or
2708                 die_error(undef, "Execute git-tar-tree failed.");
2709         binmode STDOUT, ':raw';
2710         print <$fd>;
2711         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2712         close $fd;
2713
2714 }
2715
2716 sub git_log {
2717         my $head = git_get_head_hash($project);
2718         if (!defined $hash) {
2719                 $hash = $head;
2720         }
2721         if (!defined $page) {
2722                 $page = 0;
2723         }
2724         my $refs = git_get_references();
2725
2726         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2727         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2728                 or die_error(undef, "Open git-rev-list failed");
2729         my @revlist = map { chomp; $_ } <$fd>;
2730         close $fd;
2731
2732         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2733
2734         git_header_html();
2735         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2736
2737         if (!@revlist) {
2738                 my %co = parse_commit($hash);
2739
2740                 git_print_header_div('summary', $project);
2741                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2742         }
2743         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2744                 my $commit = $revlist[$i];
2745                 my $ref = format_ref_marker($refs, $commit);
2746                 my %co = parse_commit($commit);
2747                 next if !%co;
2748                 my %ad = parse_date($co{'author_epoch'});
2749                 git_print_header_div('commit',
2750                                "<span class=\"age\">$co{'age_string'}</span>" .
2751                                esc_html($co{'title'}) . $ref,
2752                                $commit);
2753                 print "<div class=\"title_text\">\n" .
2754                       "<div class=\"log_link\">\n" .
2755                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2756                       " | " .
2757                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2758                       "<br/>\n" .
2759                       "</div>\n" .
2760                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2761                       "</div>\n";
2762
2763                 print "<div class=\"log_body\">\n";
2764                 git_print_simplified_log($co{'comment'});
2765                 print "</div>\n";
2766         }
2767         git_footer_html();
2768 }
2769
2770 sub git_commit {
2771         my %co = parse_commit($hash);
2772         if (!%co) {
2773                 die_error(undef, "Unknown commit object");
2774         }
2775         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2776         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2777
2778         my $parent = $co{'parent'};
2779         if (!defined $parent) {
2780                 $parent = "--root";
2781         }
2782         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2783                 or die_error(undef, "Open git-diff-tree failed");
2784         my @difftree = map { chomp; $_ } <$fd>;
2785         close $fd or die_error(undef, "Reading git-diff-tree failed");
2786
2787         # non-textual hash id's can be cached
2788         my $expires;
2789         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2790                 $expires = "+1d";
2791         }
2792         my $refs = git_get_references();
2793         my $ref = format_ref_marker($refs, $co{'id'});
2794
2795         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2796         my $have_snapshot = (defined $ctype && defined $suffix);
2797
2798         my $formats_nav = '';
2799         if (defined $file_name && defined $co{'parent'}) {
2800                 my $parent = $co{'parent'};
2801                 $formats_nav .=
2802                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2803                                 "blame");
2804         }
2805         git_header_html(undef, $expires);
2806         git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2807                            $hash, $co{'tree'}, $hash,
2808                            $formats_nav);
2809
2810         if (defined $co{'parent'}) {
2811                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2812         } else {
2813                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2814         }
2815         print "<div class=\"title_text\">\n" .
2816               "<table cellspacing=\"0\">\n";
2817         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2818               "<tr>" .
2819               "<td></td><td> $ad{'rfc2822'}";
2820         if ($ad{'hour_local'} < 6) {
2821                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2822                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2823         } else {
2824                 printf(" (%02d:%02d %s)",
2825                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2826         }
2827         print "</td>" .
2828               "</tr>\n";
2829         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2830         print "<tr><td></td><td> $cd{'rfc2822'}" .
2831               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2832               "</td></tr>\n";
2833         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2834         print "<tr>" .
2835               "<td>tree</td>" .
2836               "<td class=\"sha1\">" .
2837               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2838                        class => "list"}, $co{'tree'}) .
2839               "</td>" .
2840               "<td class=\"link\">" .
2841               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2842                       "tree");
2843         if ($have_snapshot) {
2844                 print " | " .
2845                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2846         }
2847         print "</td>" .
2848               "</tr>\n";
2849         my $parents = $co{'parents'};
2850         foreach my $par (@$parents) {
2851                 print "<tr>" .
2852                       "<td>parent</td>" .
2853                       "<td class=\"sha1\">" .
2854                       $cgi->a({-href => href(action=>"commit", hash=>$par),
2855                                class => "list"}, $par) .
2856                       "</td>" .
2857                       "<td class=\"link\">" .
2858                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2859                       " | " .
2860                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
2861                       "</td>" .
2862                       "</tr>\n";
2863         }
2864         print "</table>".
2865               "</div>\n";
2866
2867         print "<div class=\"page_body\">\n";
2868         git_print_log($co{'comment'});
2869         print "</div>\n";
2870
2871         git_difftree_body(\@difftree, $hash, $parent);
2872
2873         git_footer_html();
2874 }
2875
2876 sub git_blobdiff {
2877         my $format = shift || 'html';
2878
2879         my $fd;
2880         my @difftree;
2881         my %diffinfo;
2882         my $expires;
2883
2884         # preparing $fd and %diffinfo for git_patchset_body
2885         # new style URI
2886         if (defined $hash_base && defined $hash_parent_base) {
2887                 if (defined $file_name) {
2888                         # read raw output
2889                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
2890                                 "--", $file_name
2891                                 or die_error(undef, "Open git-diff-tree failed");
2892                         @difftree = map { chomp; $_ } <$fd>;
2893                         close $fd
2894                                 or die_error(undef, "Reading git-diff-tree failed");
2895                         @difftree
2896                                 or die_error('404 Not Found', "Blob diff not found");
2897
2898                 } elsif (defined $hash &&
2899                          $hash =~ /[0-9a-fA-F]{40}/) {
2900                         # try to find filename from $hash
2901
2902                         # read filtered raw output
2903                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
2904                                 or die_error(undef, "Open git-diff-tree failed");
2905                         @difftree =
2906                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
2907                                 # $hash == to_id
2908                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
2909                                 map { chomp; $_ } <$fd>;
2910                         close $fd
2911                                 or die_error(undef, "Reading git-diff-tree failed");
2912                         @difftree
2913                                 or die_error('404 Not Found', "Blob diff not found");
2914
2915                 } else {
2916                         die_error('404 Not Found', "Missing one of the blob diff parameters");
2917                 }
2918
2919                 if (@difftree > 1) {
2920                         die_error('404 Not Found', "Ambiguous blob diff specification");
2921                 }
2922
2923                 %diffinfo = parse_difftree_raw_line($difftree[0]);
2924                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
2925                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
2926
2927                 $hash_parent ||= $diffinfo{'from_id'};
2928                 $hash        ||= $diffinfo{'to_id'};
2929
2930                 # non-textual hash id's can be cached
2931                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
2932                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
2933                         $expires = '+1d';
2934                 }
2935
2936                 # open patch output
2937                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
2938                         '-p', $hash_parent_base, $hash_base,
2939                         "--", $file_name
2940                         or die_error(undef, "Open git-diff-tree failed");
2941         }
2942
2943         # old/legacy style URI
2944         if (!%diffinfo && # if new style URI failed
2945             defined $hash && defined $hash_parent) {
2946                 # fake git-diff-tree raw output
2947                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
2948                 $diffinfo{'from_id'} = $hash_parent;
2949                 $diffinfo{'to_id'}   = $hash;
2950                 if (defined $file_name) {
2951                         if (defined $file_parent) {
2952                                 $diffinfo{'status'} = '2';
2953                                 $diffinfo{'from_file'} = $file_parent;
2954                                 $diffinfo{'to_file'}   = $file_name;
2955                         } else { # assume not renamed
2956                                 $diffinfo{'status'} = '1';
2957                                 $diffinfo{'from_file'} = $file_name;
2958                                 $diffinfo{'to_file'}   = $file_name;
2959                         }
2960                 } else { # no filename given
2961                         $diffinfo{'status'} = '2';
2962                         $diffinfo{'from_file'} = $hash_parent;
2963                         $diffinfo{'to_file'}   = $hash;
2964                 }
2965
2966                 # non-textual hash id's can be cached
2967                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
2968                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
2969                         $expires = '+1d';
2970                 }
2971
2972                 # open patch output
2973                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
2974                         or die_error(undef, "Open git-diff failed");
2975         } else  {
2976                 die_error('404 Not Found', "Missing one of the blob diff parameters")
2977                         unless %diffinfo;
2978         }
2979
2980         # header
2981         if ($format eq 'html') {
2982                 my $formats_nav =
2983                         $cgi->a({-href => href(action=>"blobdiff_plain",
2984                                                hash=>$hash, hash_parent=>$hash_parent,
2985                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
2986                                                file_name=>$file_name, file_parent=>$file_parent)},
2987                                 "plain");
2988                 git_header_html(undef, $expires);
2989                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2990                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2991                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2992                 } else {
2993                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
2994                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
2995                 }
2996                 if (defined $file_name) {
2997                         git_print_page_path($file_name, "blob", $hash_base);
2998                 } else {
2999                         print "<div class=\"page_path\"></div>\n";
3000                 }
3001
3002         } elsif ($format eq 'plain') {
3003                 print $cgi->header(
3004                         -type => 'text/plain',
3005                         -charset => 'utf-8',
3006                         -expires => $expires,
3007                         -content_disposition => qq(inline; filename="${file_name}.patch"));
3008
3009                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3010
3011         } else {
3012                 die_error(undef, "Unknown blobdiff format");
3013         }
3014
3015         # patch
3016         if ($format eq 'html') {
3017                 print "<div class=\"page_body\">\n";
3018
3019                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3020                 close $fd;
3021
3022                 print "</div>\n"; # class="page_body"
3023                 git_footer_html();
3024
3025         } else {
3026                 while (my $line = <$fd>) {
3027                         $line =~ s!a/($hash|$hash_parent)!a/$diffinfo{'from_file'}!g;
3028                         $line =~ s!b/($hash|$hash_parent)!b/$diffinfo{'to_file'}!g;
3029
3030                         print $line;
3031
3032                         last if $line =~ m!^\+\+\+!;
3033                 }
3034                 local $/ = undef;
3035                 print <$fd>;
3036                 close $fd;
3037         }
3038 }
3039
3040 sub git_blobdiff_plain {
3041         git_blobdiff('plain');
3042 }
3043
3044 sub git_commitdiff {
3045         my $format = shift || 'html';
3046         my %co = parse_commit($hash);
3047         if (!%co) {
3048                 die_error(undef, "Unknown commit object");
3049         }
3050         if (!defined $hash_parent) {
3051                 $hash_parent = $co{'parent'} || '--root';
3052         }
3053
3054         # read commitdiff
3055         my $fd;
3056         my @difftree;
3057         if ($format eq 'html') {
3058                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3059                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3060                         or die_error(undef, "Open git-diff-tree failed");
3061
3062                 while (chomp(my $line = <$fd>)) {
3063                         # empty line ends raw part of diff-tree output
3064                         last unless $line;
3065                         push @difftree, $line;
3066                 }
3067
3068         } elsif ($format eq 'plain') {
3069                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3070                         '-p', $hash_parent, $hash
3071                         or die_error(undef, "Open git-diff-tree failed");
3072
3073         } else {
3074                 die_error(undef, "Unknown commitdiff format");
3075         }
3076
3077         # non-textual hash id's can be cached
3078         my $expires;
3079         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3080                 $expires = "+1d";
3081         }
3082
3083         # write commit message
3084         if ($format eq 'html') {
3085                 my $refs = git_get_references();
3086                 my $ref = format_ref_marker($refs, $co{'id'});
3087                 my $formats_nav =
3088                         $cgi->a({-href => href(action=>"commitdiff_plain",
3089                                                hash=>$hash, hash_parent=>$hash_parent)},
3090                                 "plain");
3091
3092                 git_header_html(undef, $expires);
3093                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3094                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3095                 git_print_authorship(\%co);
3096                 print "<div class=\"page_body\">\n";
3097                 print "<div class=\"log\">\n";
3098                 git_print_simplified_log($co{'comment'}, 1); # skip title
3099                 print "</div>\n"; # class="log"
3100
3101         } elsif ($format eq 'plain') {
3102                 my $refs = git_get_references("tags");
3103                 my $tagname = git_get_rev_name_tags($hash);
3104                 my $filename = basename($project) . "-$hash.patch";
3105
3106                 print $cgi->header(
3107                         -type => 'text/plain',
3108                         -charset => 'utf-8',
3109                         -expires => $expires,
3110                         -content_disposition => qq(inline; filename="$filename"));
3111                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3112                 print <<TEXT;
3113 From: $co{'author'}
3114 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3115 Subject: $co{'title'}
3116 TEXT
3117                 print "X-Git-Tag: $tagname\n" if $tagname;
3118                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3119
3120                 foreach my $line (@{$co{'comment'}}) {
3121                         print "$line\n";
3122                 }
3123                 print "---\n\n";
3124         }
3125
3126         # write patch
3127         if ($format eq 'html') {
3128                 git_difftree_body(\@difftree, $hash, $hash_parent);
3129                 print "<br/>\n";
3130
3131                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3132                 close $fd;
3133                 print "</div>\n"; # class="page_body"
3134                 git_footer_html();
3135
3136         } elsif ($format eq 'plain') {
3137                 local $/ = undef;
3138                 print <$fd>;
3139                 close $fd
3140                         or print "Reading git-diff-tree failed\n";
3141         }
3142 }
3143
3144 sub git_commitdiff_plain {
3145         git_commitdiff('plain');
3146 }
3147
3148 sub git_history {
3149         if (!defined $hash_base) {
3150                 $hash_base = git_get_head_hash($project);
3151         }
3152         if (!defined $page) {
3153                 $page = 0;
3154         }
3155         my $ftype;
3156         my %co = parse_commit($hash_base);
3157         if (!%co) {
3158                 die_error(undef, "Unknown commit object");
3159         }
3160
3161         my $refs = git_get_references();
3162         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3163
3164         if (!defined $hash && defined $file_name) {
3165                 $hash = git_get_hash_by_path($hash_base, $file_name);
3166         }
3167         if (defined $hash) {
3168                 $ftype = git_get_type($hash);
3169         }
3170
3171         open my $fd, "-|",
3172                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3173                         or die_error(undef, "Open git-rev-list-failed");
3174         my @revlist = map { chomp; $_ } <$fd>;
3175         close $fd
3176                 or die_error(undef, "Reading git-rev-list failed");
3177
3178         my $paging_nav = '';
3179         if ($page > 0) {
3180                 $paging_nav .=
3181                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3182                                                file_name=>$file_name)},
3183                                 "first");
3184                 $paging_nav .= " &sdot; " .
3185                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3186                                                file_name=>$file_name, page=>$page-1),
3187                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3188         } else {
3189                 $paging_nav .= "first";
3190                 $paging_nav .= " &sdot; prev";
3191         }
3192         if ($#revlist >= (100 * ($page+1)-1)) {
3193                 $paging_nav .= " &sdot; " .
3194                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3195                                                file_name=>$file_name, page=>$page+1),
3196                                  -accesskey => "n", -title => "Alt-n"}, "next");
3197         } else {
3198                 $paging_nav .= " &sdot; next";
3199         }
3200         my $next_link = '';
3201         if ($#revlist >= (100 * ($page+1)-1)) {
3202                 $next_link =
3203                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3204                                                file_name=>$file_name, page=>$page+1),
3205                                  -title => "Alt-n"}, "next");
3206         }
3207
3208         git_header_html();
3209         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3210         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3211         git_print_page_path($file_name, $ftype, $hash_base);
3212
3213         git_history_body(\@revlist, ($page * 100), $#revlist,
3214                          $refs, $hash_base, $ftype, $next_link);
3215
3216         git_footer_html();
3217 }
3218
3219 sub git_search {
3220         if (!defined $searchtext) {
3221                 die_error(undef, "Text field empty");
3222         }
3223         if (!defined $hash) {
3224                 $hash = git_get_head_hash($project);
3225         }
3226         my %co = parse_commit($hash);
3227         if (!%co) {
3228                 die_error(undef, "Unknown commit object");
3229         }
3230
3231         my $commit_search = 1;
3232         my $author_search = 0;
3233         my $committer_search = 0;
3234         my $pickaxe_search = 0;
3235         if ($searchtext =~ s/^author\\://i) {
3236                 $author_search = 1;
3237         } elsif ($searchtext =~ s/^committer\\://i) {
3238                 $committer_search = 1;
3239         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3240                 $commit_search = 0;
3241                 $pickaxe_search = 1;
3242
3243                 # pickaxe may take all resources of your box and run for several minutes
3244                 # with every query - so decide by yourself how public you make this feature
3245                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3246                 if (!$have_pickaxe) {
3247                         die_error('403 Permission denied', "Permission denied");
3248                 }
3249         }
3250         git_header_html();
3251         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3252         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3253
3254         print "<table cellspacing=\"0\">\n";
3255         my $alternate = 0;
3256         if ($commit_search) {
3257                 $/ = "\0";
3258                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3259                 while (my $commit_text = <$fd>) {
3260                         if (!grep m/$searchtext/i, $commit_text) {
3261                                 next;
3262                         }
3263                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3264                                 next;
3265                         }
3266                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3267                                 next;
3268                         }
3269                         my @commit_lines = split "\n", $commit_text;
3270                         my %co = parse_commit(undef, \@commit_lines);
3271                         if (!%co) {
3272                                 next;
3273                         }
3274                         if ($alternate) {
3275                                 print "<tr class=\"dark\">\n";
3276                         } else {
3277                                 print "<tr class=\"light\">\n";
3278                         }
3279                         $alternate ^= 1;
3280                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3281                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3282                               "<td>" .
3283                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3284                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3285                         my $comment = $co{'comment'};
3286                         foreach my $line (@$comment) {
3287                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3288                                         my $lead = esc_html($1) || "";
3289                                         $lead = chop_str($lead, 30, 10);
3290                                         my $match = esc_html($2) || "";
3291                                         my $trail = esc_html($3) || "";
3292                                         $trail = chop_str($trail, 30, 10);
3293                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3294                                         print chop_str($text, 80, 5) . "<br/>\n";
3295                                 }
3296                         }
3297                         print "</td>\n" .
3298                               "<td class=\"link\">" .
3299                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3300                               " | " .
3301                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3302                         print "</td>\n" .
3303                               "</tr>\n";
3304                 }
3305                 close $fd;
3306         }
3307
3308         if ($pickaxe_search) {
3309                 $/ = "\n";
3310                 my $git_command = git_cmd_str();
3311                 open my $fd, "-|", "$git_command rev-list $hash | " .
3312                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3313                 undef %co;
3314                 my @files;
3315                 while (my $line = <$fd>) {
3316                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3317                                 my %set;
3318                                 $set{'file'} = $6;
3319                                 $set{'from_id'} = $3;
3320                                 $set{'to_id'} = $4;
3321                                 $set{'id'} = $set{'to_id'};
3322                                 if ($set{'id'} =~ m/0{40}/) {
3323                                         $set{'id'} = $set{'from_id'};
3324                                 }
3325                                 if ($set{'id'} =~ m/0{40}/) {
3326                                         next;
3327                                 }
3328                                 push @files, \%set;
3329                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3330                                 if (%co) {
3331                                         if ($alternate) {
3332                                                 print "<tr class=\"dark\">\n";
3333                                         } else {
3334                                                 print "<tr class=\"light\">\n";
3335                                         }
3336                                         $alternate ^= 1;
3337                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3338                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3339                                               "<td>" .
3340                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3341                                                       -class => "list subject"},
3342                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3343                                         while (my $setref = shift @files) {
3344                                                 my %set = %$setref;
3345                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3346                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3347                                                               -class => "list"},
3348                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3349                                                       "<br/>\n";
3350                                         }
3351                                         print "</td>\n" .
3352                                               "<td class=\"link\">" .
3353                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3354                                               " | " .
3355                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3356                                         print "</td>\n" .
3357                                               "</tr>\n";
3358                                 }
3359                                 %co = parse_commit($1);
3360                         }
3361                 }
3362                 close $fd;
3363         }
3364         print "</table>\n";
3365         git_footer_html();
3366 }
3367
3368 sub git_shortlog {
3369         my $head = git_get_head_hash($project);
3370         if (!defined $hash) {
3371                 $hash = $head;
3372         }
3373         if (!defined $page) {
3374                 $page = 0;
3375         }
3376         my $refs = git_get_references();
3377
3378         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3379         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3380                 or die_error(undef, "Open git-rev-list failed");
3381         my @revlist = map { chomp; $_ } <$fd>;
3382         close $fd;
3383
3384         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3385         my $next_link = '';
3386         if ($#revlist >= (100 * ($page+1)-1)) {
3387                 $next_link =
3388                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3389                                  -title => "Alt-n"}, "next");
3390         }
3391
3392
3393         git_header_html();
3394         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3395         git_print_header_div('summary', $project);
3396
3397         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3398
3399         git_footer_html();
3400 }
3401
3402 ## ......................................................................
3403 ## feeds (RSS, OPML)
3404
3405 sub git_rss {
3406         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3407         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3408                 or die_error(undef, "Open git-rev-list failed");
3409         my @revlist = map { chomp; $_ } <$fd>;
3410         close $fd or die_error(undef, "Reading git-rev-list failed");
3411         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3412         print <<XML;
3413 <?xml version="1.0" encoding="utf-8"?>
3414 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3415 <channel>
3416 <title>$project $my_uri $my_url</title>
3417 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3418 <description>$project log</description>
3419 <language>en</language>
3420 XML
3421
3422         for (my $i = 0; $i <= $#revlist; $i++) {
3423                 my $commit = $revlist[$i];
3424                 my %co = parse_commit($commit);
3425                 # we read 150, we always show 30 and the ones more recent than 48 hours
3426                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3427                         last;
3428                 }
3429                 my %cd = parse_date($co{'committer_epoch'});
3430                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3431                         $co{'parent'}, $co{'id'}
3432                         or next;
3433                 my @difftree = map { chomp; $_ } <$fd>;
3434                 close $fd
3435                         or next;
3436                 print "<item>\n" .
3437                       "<title>" .
3438                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3439                       "</title>\n" .
3440                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3441                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3442                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3443                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3444                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3445                       "<content:encoded>" .
3446                       "<![CDATA[\n";
3447                 my $comment = $co{'comment'};
3448                 foreach my $line (@$comment) {
3449                         $line = decode("utf8", $line, Encode::FB_DEFAULT);
3450                         print "$line<br/>\n";
3451                 }
3452                 print "<br/>\n";
3453                 foreach my $line (@difftree) {
3454                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3455                                 next;
3456                         }
3457                         my $file = validate_input(unquote($7));
3458                         $file = decode("utf8", $file, Encode::FB_DEFAULT);
3459                         print "$file<br/>\n";
3460                 }
3461                 print "]]>\n" .
3462                       "</content:encoded>\n" .
3463                       "</item>\n";
3464         }
3465         print "</channel></rss>";
3466 }
3467
3468 sub git_opml {
3469         my @list = git_get_projects_list();
3470
3471         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3472         print <<XML;
3473 <?xml version="1.0" encoding="utf-8"?>
3474 <opml version="1.0">
3475 <head>
3476   <title>$site_name Git OPML Export</title>
3477 </head>
3478 <body>
3479 <outline text="git RSS feeds">
3480 XML
3481
3482         foreach my $pr (@list) {
3483                 my %proj = %$pr;
3484                 my $head = git_get_head_hash($proj{'path'});
3485                 if (!defined $head) {
3486                         next;
3487                 }
3488                 $git_dir = "$projectroot/$proj{'path'}";
3489                 my %co = parse_commit($head);
3490                 if (!%co) {
3491                         next;
3492                 }
3493
3494                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3495                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3496                 my $html = "$my_url?p=$proj{'path'};a=summary";
3497                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3498         }
3499         print <<XML;
3500 </outline>
3501 </body>
3502 </opml>
3503 XML
3504 }