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