Code

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