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