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