Code

gitweb: Require project for almost all actions
[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         my $fd;
847         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
848         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
849         if (-f "$projectroot/$project/info/refs") {
850                 open $fd, "$projectroot/$project/info/refs"
851                         or return;
852         } else {
853                 open $fd, "-|", git_cmd(), "ls-remote", "."
854                         or return;
855         }
857         while (my $line = <$fd>) {
858                 chomp $line;
859                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
860                         if (defined $refs{$1}) {
861                                 push @{$refs{$1}}, $2;
862                         } else {
863                                 $refs{$1} = [ $2 ];
864                         }
865                 }
866         }
867         close $fd or return;
868         return \%refs;
871 sub git_get_rev_name_tags {
872         my $hash = shift || return undef;
874         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
875                 or return;
876         my $name_rev = <$fd>;
877         close $fd;
879         if ($name_rev =~ m|^$hash tags/(.*)$|) {
880                 return $1;
881         } else {
882                 # catches also '$hash undefined' output
883                 return undef;
884         }
887 ## ----------------------------------------------------------------------
888 ## parse to hash functions
890 sub parse_date {
891         my $epoch = shift;
892         my $tz = shift || "-0000";
894         my %date;
895         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
896         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
897         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
898         $date{'hour'} = $hour;
899         $date{'minute'} = $min;
900         $date{'mday'} = $mday;
901         $date{'day'} = $days[$wday];
902         $date{'month'} = $months[$mon];
903         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
904                            $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
905         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
906                              $mday, $months[$mon], $hour ,$min;
908         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
909         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
910         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
911         $date{'hour_local'} = $hour;
912         $date{'minute_local'} = $min;
913         $date{'tz_local'} = $tz;
914         return %date;
917 sub parse_tag {
918         my $tag_id = shift;
919         my %tag;
920         my @comment;
922         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
923         $tag{'id'} = $tag_id;
924         while (my $line = <$fd>) {
925                 chomp $line;
926                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
927                         $tag{'object'} = $1;
928                 } elsif ($line =~ m/^type (.+)$/) {
929                         $tag{'type'} = $1;
930                 } elsif ($line =~ m/^tag (.+)$/) {
931                         $tag{'name'} = $1;
932                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
933                         $tag{'author'} = $1;
934                         $tag{'epoch'} = $2;
935                         $tag{'tz'} = $3;
936                 } elsif ($line =~ m/--BEGIN/) {
937                         push @comment, $line;
938                         last;
939                 } elsif ($line eq "") {
940                         last;
941                 }
942         }
943         push @comment, <$fd>;
944         $tag{'comment'} = \@comment;
945         close $fd or return;
946         if (!defined $tag{'name'}) {
947                 return
948         };
949         return %tag
952 sub parse_commit {
953         my $commit_id = shift;
954         my $commit_text = shift;
956         my @commit_lines;
957         my %co;
959         if (defined $commit_text) {
960                 @commit_lines = @$commit_text;
961         } else {
962                 $/ = "\0";
963                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
964                         or return;
965                 @commit_lines = split '\n', <$fd>;
966                 close $fd or return;
967                 $/ = "\n";
968                 pop @commit_lines;
969         }
970         my $header = shift @commit_lines;
971         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
972                 return;
973         }
974         ($co{'id'}, my @parents) = split ' ', $header;
975         $co{'parents'} = \@parents;
976         $co{'parent'} = $parents[0];
977         while (my $line = shift @commit_lines) {
978                 last if $line eq "\n";
979                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
980                         $co{'tree'} = $1;
981                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
982                         $co{'author'} = $1;
983                         $co{'author_epoch'} = $2;
984                         $co{'author_tz'} = $3;
985                         if ($co{'author'} =~ m/^([^<]+) </) {
986                                 $co{'author_name'} = $1;
987                         } else {
988                                 $co{'author_name'} = $co{'author'};
989                         }
990                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
991                         $co{'committer'} = $1;
992                         $co{'committer_epoch'} = $2;
993                         $co{'committer_tz'} = $3;
994                         $co{'committer_name'} = $co{'committer'};
995                         $co{'committer_name'} =~ s/ <.*//;
996                 }
997         }
998         if (!defined $co{'tree'}) {
999                 return;
1000         };
1002         foreach my $title (@commit_lines) {
1003                 $title =~ s/^    //;
1004                 if ($title ne "") {
1005                         $co{'title'} = chop_str($title, 80, 5);
1006                         # remove leading stuff of merges to make the interesting part visible
1007                         if (length($title) > 50) {
1008                                 $title =~ s/^Automatic //;
1009                                 $title =~ s/^merge (of|with) /Merge ... /i;
1010                                 if (length($title) > 50) {
1011                                         $title =~ s/(http|rsync):\/\///;
1012                                 }
1013                                 if (length($title) > 50) {
1014                                         $title =~ s/(master|www|rsync)\.//;
1015                                 }
1016                                 if (length($title) > 50) {
1017                                         $title =~ s/kernel.org:?//;
1018                                 }
1019                                 if (length($title) > 50) {
1020                                         $title =~ s/\/pub\/scm//;
1021                                 }
1022                         }
1023                         $co{'title_short'} = chop_str($title, 50, 5);
1024                         last;
1025                 }
1026         }
1027         # remove added spaces
1028         foreach my $line (@commit_lines) {
1029                 $line =~ s/^    //;
1030         }
1031         $co{'comment'} = \@commit_lines;
1033         my $age = time - $co{'committer_epoch'};
1034         $co{'age'} = $age;
1035         $co{'age_string'} = age_string($age);
1036         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1037         if ($age > 60*60*24*7*2) {
1038                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1039                 $co{'age_string_age'} = $co{'age_string'};
1040         } else {
1041                 $co{'age_string_date'} = $co{'age_string'};
1042                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1043         }
1044         return %co;
1047 # parse ref from ref_file, given by ref_id, with given type
1048 sub parse_ref {
1049         my $ref_file = shift;
1050         my $ref_id = shift;
1051         my $type = shift || git_get_type($ref_id);
1052         my %ref_item;
1054         $ref_item{'type'} = $type;
1055         $ref_item{'id'} = $ref_id;
1056         $ref_item{'epoch'} = 0;
1057         $ref_item{'age'} = "unknown";
1058         if ($type eq "tag") {
1059                 my %tag = parse_tag($ref_id);
1060                 $ref_item{'comment'} = $tag{'comment'};
1061                 if ($tag{'type'} eq "commit") {
1062                         my %co = parse_commit($tag{'object'});
1063                         $ref_item{'epoch'} = $co{'committer_epoch'};
1064                         $ref_item{'age'} = $co{'age_string'};
1065                 } elsif (defined($tag{'epoch'})) {
1066                         my $age = time - $tag{'epoch'};
1067                         $ref_item{'epoch'} = $tag{'epoch'};
1068                         $ref_item{'age'} = age_string($age);
1069                 }
1070                 $ref_item{'reftype'} = $tag{'type'};
1071                 $ref_item{'name'} = $tag{'name'};
1072                 $ref_item{'refid'} = $tag{'object'};
1073         } elsif ($type eq "commit"){
1074                 my %co = parse_commit($ref_id);
1075                 $ref_item{'reftype'} = "commit";
1076                 $ref_item{'name'} = $ref_file;
1077                 $ref_item{'title'} = $co{'title'};
1078                 $ref_item{'refid'} = $ref_id;
1079                 $ref_item{'epoch'} = $co{'committer_epoch'};
1080                 $ref_item{'age'} = $co{'age_string'};
1081         } else {
1082                 $ref_item{'reftype'} = $type;
1083                 $ref_item{'name'} = $ref_file;
1084                 $ref_item{'refid'} = $ref_id;
1085         }
1087         return %ref_item;
1090 # parse line of git-diff-tree "raw" output
1091 sub parse_difftree_raw_line {
1092         my $line = shift;
1093         my %res;
1095         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1096         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1097         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1098                 $res{'from_mode'} = $1;
1099                 $res{'to_mode'} = $2;
1100                 $res{'from_id'} = $3;
1101                 $res{'to_id'} = $4;
1102                 $res{'status'} = $5;
1103                 $res{'similarity'} = $6;
1104                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1105                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1106                 } else {
1107                         $res{'file'} = unquote($7);
1108                 }
1109         }
1110         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1111         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1112                 $res{'commit'} = $1;
1113         }
1115         return wantarray ? %res : \%res;
1118 # parse line of git-ls-tree output
1119 sub parse_ls_tree_line ($;%) {
1120         my $line = shift;
1121         my %opts = @_;
1122         my %res;
1124         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1125         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1127         $res{'mode'} = $1;
1128         $res{'type'} = $2;
1129         $res{'hash'} = $3;
1130         if ($opts{'-z'}) {
1131                 $res{'name'} = $4;
1132         } else {
1133                 $res{'name'} = unquote($4);
1134         }
1136         return wantarray ? %res : \%res;
1139 ## ......................................................................
1140 ## parse to array of hashes functions
1142 sub git_get_refs_list {
1143         my $ref_dir = shift;
1144         my @reflist;
1146         my @refs;
1147         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1148                 or return;
1149         while (my $line = <$fd>) {
1150                 chomp $line;
1151                 if ($line =~ m/^([0-9a-fA-F]{40})\t$ref_dir\/?([^\^]+)$/) {
1152                         push @refs, { hash => $1, name => $2 };
1153                 } elsif ($line =~ m/^[0-9a-fA-F]{40}\t$ref_dir\/?(.*)\^\{\}$/ &&
1154                          $1 eq $refs[-1]{'name'}) {
1155                         # most likely a tag is followed by its peeled
1156                         # (deref) one, and when that happens we know the
1157                         # previous one was of type 'tag'.
1158                         $refs[-1]{'type'} = "tag";
1159                 }
1160         }
1161         close $fd;
1163         foreach my $ref (@refs) {
1164                 my $ref_file = $ref->{'name'};
1165                 my $ref_id   = $ref->{'hash'};
1167                 my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1168                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
1170                 push @reflist, \%ref_item;
1171         }
1172         # sort refs by age
1173         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1174         return \@reflist;
1177 ## ----------------------------------------------------------------------
1178 ## filesystem-related functions
1180 sub get_file_owner {
1181         my $path = shift;
1183         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1184         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1185         if (!defined $gcos) {
1186                 return undef;
1187         }
1188         my $owner = $gcos;
1189         $owner =~ s/[,;].*$//;
1190         return decode("utf8", $owner, Encode::FB_DEFAULT);
1193 ## ......................................................................
1194 ## mimetype related functions
1196 sub mimetype_guess_file {
1197         my $filename = shift;
1198         my $mimemap = shift;
1199         -r $mimemap or return undef;
1201         my %mimemap;
1202         open(MIME, $mimemap) or return undef;
1203         while (<MIME>) {
1204                 next if m/^#/; # skip comments
1205                 my ($mime, $exts) = split(/\t+/);
1206                 if (defined $exts) {
1207                         my @exts = split(/\s+/, $exts);
1208                         foreach my $ext (@exts) {
1209                                 $mimemap{$ext} = $mime;
1210                         }
1211                 }
1212         }
1213         close(MIME);
1215         $filename =~ /\.([^.]*)$/;
1216         return $mimemap{$1};
1219 sub mimetype_guess {
1220         my $filename = shift;
1221         my $mime;
1222         $filename =~ /\./ or return undef;
1224         if ($mimetypes_file) {
1225                 my $file = $mimetypes_file;
1226                 if ($file !~ m!^/!) { # if it is relative path
1227                         # it is relative to project
1228                         $file = "$projectroot/$project/$file";
1229                 }
1230                 $mime = mimetype_guess_file($filename, $file);
1231         }
1232         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1233         return $mime;
1236 sub blob_mimetype {
1237         my $fd = shift;
1238         my $filename = shift;
1240         if ($filename) {
1241                 my $mime = mimetype_guess($filename);
1242                 $mime and return $mime;
1243         }
1245         # just in case
1246         return $default_blob_plain_mimetype unless $fd;
1248         if (-T $fd) {
1249                 return 'text/plain' .
1250                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1251         } elsif (! $filename) {
1252                 return 'application/octet-stream';
1253         } elsif ($filename =~ m/\.png$/i) {
1254                 return 'image/png';
1255         } elsif ($filename =~ m/\.gif$/i) {
1256                 return 'image/gif';
1257         } elsif ($filename =~ m/\.jpe?g$/i) {
1258                 return 'image/jpeg';
1259         } else {
1260                 return 'application/octet-stream';
1261         }
1264 ## ======================================================================
1265 ## functions printing HTML: header, footer, error page
1267 sub git_header_html {
1268         my $status = shift || "200 OK";
1269         my $expires = shift;
1271         my $title = "$site_name git";
1272         if (defined $project) {
1273                 $title .= " - $project";
1274                 if (defined $action) {
1275                         $title .= "/$action";
1276                         if (defined $file_name) {
1277                                 $title .= " - $file_name";
1278                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1279                                         $title .= "/";
1280                                 }
1281                         }
1282                 }
1283         }
1284         my $content_type;
1285         # require explicit support from the UA if we are to send the page as
1286         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1287         # we have to do this because MSIE sometimes globs '*/*', pretending to
1288         # support xhtml+xml but choking when it gets what it asked for.
1289         if (defined $cgi->http('HTTP_ACCEPT') &&
1290             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1291             $cgi->Accept('application/xhtml+xml') != 0) {
1292                 $content_type = 'application/xhtml+xml';
1293         } else {
1294                 $content_type = 'text/html';
1295         }
1296         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1297                            -status=> $status, -expires => $expires);
1298         print <<EOF;
1299 <?xml version="1.0" encoding="utf-8"?>
1300 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1301 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1302 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1303 <!-- git core binaries version $git_version -->
1304 <head>
1305 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1306 <meta name="generator" content="gitweb/$version git/$git_version"/>
1307 <meta name="robots" content="index, nofollow"/>
1308 <title>$title</title>
1309 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1310 EOF
1311         if (defined $project) {
1312                 printf('<link rel="alternate" title="%s log" '.
1313                        'href="%s" type="application/rss+xml"/>'."\n",
1314                        esc_param($project), href(action=>"rss"));
1315         } else {
1316                 printf('<link rel="alternate" title="%s projects list" '.
1317                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1318                        $site_name, href(project=>undef, action=>"project_index"));
1319                 printf('<link rel="alternate" title="%s projects logs" '.
1320                        'href="%s" type="text/x-opml"/>'."\n",
1321                        $site_name, href(project=>undef, action=>"opml"));
1322         }
1323         if (defined $favicon) {
1324                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1325         }
1327         print "</head>\n" .
1328               "<body>\n" .
1329               "<div class=\"page_header\">\n" .
1330               "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1331               "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1332               "</a>\n";
1333         print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1334         if (defined $project) {
1335                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1336                 if (defined $action) {
1337                         print " / $action";
1338                 }
1339                 print "\n";
1340                 if (!defined $searchtext) {
1341                         $searchtext = "";
1342                 }
1343                 my $search_hash;
1344                 if (defined $hash_base) {
1345                         $search_hash = $hash_base;
1346                 } elsif (defined $hash) {
1347                         $search_hash = $hash;
1348                 } else {
1349                         $search_hash = "HEAD";
1350                 }
1351                 $cgi->param("a", "search");
1352                 $cgi->param("h", $search_hash);
1353                 print $cgi->startform(-method => "get", -action => $my_uri) .
1354                       "<div class=\"search\">\n" .
1355                       $cgi->hidden(-name => "p") . "\n" .
1356                       $cgi->hidden(-name => "a") . "\n" .
1357                       $cgi->hidden(-name => "h") . "\n" .
1358                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1359                       "</div>" .
1360                       $cgi->end_form() . "\n";
1361         }
1362         print "</div>\n";
1365 sub git_footer_html {
1366         print "<div class=\"page_footer\">\n";
1367         if (defined $project) {
1368                 my $descr = git_get_project_description($project);
1369                 if (defined $descr) {
1370                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1371                 }
1372                 print $cgi->a({-href => href(action=>"rss"),
1373                               -class => "rss_logo"}, "RSS") . "\n";
1374         } else {
1375                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1376                               -class => "rss_logo"}, "OPML") . " ";
1377                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1378                               -class => "rss_logo"}, "TXT") . "\n";
1379         }
1380         print "</div>\n" .
1381               "</body>\n" .
1382               "</html>";
1385 sub die_error {
1386         my $status = shift || "403 Forbidden";
1387         my $error = shift || "Malformed query, file missing or permission denied";
1389         git_header_html($status);
1390         print <<EOF;
1391 <div class="page_body">
1392 <br /><br />
1393 $status - $error
1394 <br />
1395 </div>
1396 EOF
1397         git_footer_html();
1398         exit;
1401 ## ----------------------------------------------------------------------
1402 ## functions printing or outputting HTML: navigation
1404 sub git_print_page_nav {
1405         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1406         $extra = '' if !defined $extra; # pager or formats
1408         my @navs = qw(summary shortlog log commit commitdiff tree);
1409         if ($suppress) {
1410                 @navs = grep { $_ ne $suppress } @navs;
1411         }
1413         my %arg = map { $_ => {action=>$_} } @navs;
1414         if (defined $head) {
1415                 for (qw(commit commitdiff)) {
1416                         $arg{$_}{hash} = $head;
1417                 }
1418                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1419                         for (qw(shortlog log)) {
1420                                 $arg{$_}{hash} = $head;
1421                         }
1422                 }
1423         }
1424         $arg{tree}{hash} = $treehead if defined $treehead;
1425         $arg{tree}{hash_base} = $treebase if defined $treebase;
1427         print "<div class=\"page_nav\">\n" .
1428                 (join " | ",
1429                  map { $_ eq $current ?
1430                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1431                  } @navs);
1432         print "<br/>\n$extra<br/>\n" .
1433               "</div>\n";
1436 sub format_paging_nav {
1437         my ($action, $hash, $head, $page, $nrevs) = @_;
1438         my $paging_nav;
1441         if ($hash ne $head || $page) {
1442                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1443         } else {
1444                 $paging_nav .= "HEAD";
1445         }
1447         if ($page > 0) {
1448                 $paging_nav .= " &sdot; " .
1449                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1450                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1451         } else {
1452                 $paging_nav .= " &sdot; prev";
1453         }
1455         if ($nrevs >= (100 * ($page+1)-1)) {
1456                 $paging_nav .= " &sdot; " .
1457                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1458                                  -accesskey => "n", -title => "Alt-n"}, "next");
1459         } else {
1460                 $paging_nav .= " &sdot; next";
1461         }
1463         return $paging_nav;
1466 ## ......................................................................
1467 ## functions printing or outputting HTML: div
1469 sub git_print_header_div {
1470         my ($action, $title, $hash, $hash_base) = @_;
1471         my %args = ();
1473         $args{action} = $action;
1474         $args{hash} = $hash if $hash;
1475         $args{hash_base} = $hash_base if $hash_base;
1477         print "<div class=\"header\">\n" .
1478               $cgi->a({-href => href(%args), -class => "title"},
1479               $title ? $title : $action) .
1480               "\n</div>\n";
1483 #sub git_print_authorship (\%) {
1484 sub git_print_authorship {
1485         my $co = shift;
1487         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1488         print "<div class=\"author_date\">" .
1489               esc_html($co->{'author_name'}) .
1490               " [$ad{'rfc2822'}";
1491         if ($ad{'hour_local'} < 6) {
1492                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1493                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1494         } else {
1495                 printf(" (%02d:%02d %s)",
1496                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1497         }
1498         print "]</div>\n";
1501 sub git_print_page_path {
1502         my $name = shift;
1503         my $type = shift;
1504         my $hb = shift;
1506         if (!defined $name) {
1507                 print "<div class=\"page_path\">/</div>\n";
1508         } else {
1509                 my @dirname = split '/', $name;
1510                 my $basename = pop @dirname;
1511                 my $fullname = '';
1513                 print "<div class=\"page_path\">";
1514                 foreach my $dir (@dirname) {
1515                         $fullname .= $dir . '/';
1516                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1517                                                      hash_base=>$hb),
1518                                       -title => $fullname}, esc_html($dir));
1519                         print "/";
1520                 }
1521                 if (defined $type && $type eq 'blob') {
1522                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1523                                                      hash_base=>$hb),
1524                                       -title => $name}, esc_html($basename));
1525                 } elsif (defined $type && $type eq 'tree') {
1526                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1527                                                      hash_base=>$hb),
1528                                       -title => $name}, esc_html($basename));
1529                         print "/";
1530                 } else {
1531                         print esc_html($basename);
1532                 }
1533                 print "<br/></div>\n";
1534         }
1537 # sub git_print_log (\@;%) {
1538 sub git_print_log ($;%) {
1539         my $log = shift;
1540         my %opts = @_;
1542         if ($opts{'-remove_title'}) {
1543                 # remove title, i.e. first line of log
1544                 shift @$log;
1545         }
1546         # remove leading empty lines
1547         while (defined $log->[0] && $log->[0] eq "") {
1548                 shift @$log;
1549         }
1551         # print log
1552         my $signoff = 0;
1553         my $empty = 0;
1554         foreach my $line (@$log) {
1555                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1556                         $signoff = 1;
1557                         $empty = 0;
1558                         if (! $opts{'-remove_signoff'}) {
1559                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1560                                 next;
1561                         } else {
1562                                 # remove signoff lines
1563                                 next;
1564                         }
1565                 } else {
1566                         $signoff = 0;
1567                 }
1569                 # print only one empty line
1570                 # do not print empty line after signoff
1571                 if ($line eq "") {
1572                         next if ($empty || $signoff);
1573                         $empty = 1;
1574                 } else {
1575                         $empty = 0;
1576                 }
1578                 print format_log_line_html($line) . "<br/>\n";
1579         }
1581         if ($opts{'-final_empty_line'}) {
1582                 # end with single empty line
1583                 print "<br/>\n" unless $empty;
1584         }
1587 sub git_print_simplified_log {
1588         my $log = shift;
1589         my $remove_title = shift;
1591         git_print_log($log,
1592                 -final_empty_line=> 1,
1593                 -remove_title => $remove_title);
1596 # print tree entry (row of git_tree), but without encompassing <tr> element
1597 sub git_print_tree_entry {
1598         my ($t, $basedir, $hash_base, $have_blame) = @_;
1600         my %base_key = ();
1601         $base_key{hash_base} = $hash_base if defined $hash_base;
1603         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1604         if ($t->{'type'} eq "blob") {
1605                 print "<td class=\"list\">" .
1606                       $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1607                                              file_name=>"$basedir$t->{'name'}", %base_key),
1608                               -class => "list"}, esc_html($t->{'name'})) .
1609                       "</td>\n" .
1610                       "<td class=\"link\">" .
1611                       $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1612                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1613                               "blob");
1614                 if ($have_blame) {
1615                         print " | " .
1616                                 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1617                                                        file_name=>"$basedir$t->{'name'}", %base_key)},
1618                                         "blame");
1619                 }
1620                 if (defined $hash_base) {
1621                         print " | " .
1622                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1623                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1624                                       "history");
1625                 }
1626                 print " | " .
1627                       $cgi->a({-href => href(action=>"blob_plain",
1628                                              hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1629                               "raw") .
1630                       "</td>\n";
1632         } elsif ($t->{'type'} eq "tree") {
1633                 print "<td class=\"list\">" .
1634                       $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1635                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1636                               esc_html($t->{'name'})) .
1637                       "</td>\n" .
1638                       "<td class=\"link\">" .
1639                       $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1640                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1641                               "tree");
1642                 if (defined $hash_base) {
1643                         print " | " .
1644                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1645                                                      file_name=>"$basedir$t->{'name'}")},
1646                                       "history");
1647                 }
1648                 print "</td>\n";
1649         }
1652 ## ......................................................................
1653 ## functions printing large fragments of HTML
1655 sub git_difftree_body {
1656         my ($difftree, $hash, $parent) = @_;
1658         print "<div class=\"list_head\">\n";
1659         if ($#{$difftree} > 10) {
1660                 print(($#{$difftree} + 1) . " files changed:\n");
1661         }
1662         print "</div>\n";
1664         print "<table class=\"diff_tree\">\n";
1665         my $alternate = 0;
1666         my $patchno = 0;
1667         foreach my $line (@{$difftree}) {
1668                 my %diff = parse_difftree_raw_line($line);
1670                 if ($alternate) {
1671                         print "<tr class=\"dark\">\n";
1672                 } else {
1673                         print "<tr class=\"light\">\n";
1674                 }
1675                 $alternate ^= 1;
1677                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1678                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1679                 if ($diff{'to_mode'} ne ('0' x 6)) {
1680                         $to_mode_oct = oct $diff{'to_mode'};
1681                         if (S_ISREG($to_mode_oct)) { # only for regular file
1682                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1683                         }
1684                         $to_file_type = file_type($diff{'to_mode'});
1685                 }
1686                 if ($diff{'from_mode'} ne ('0' x 6)) {
1687                         $from_mode_oct = oct $diff{'from_mode'};
1688                         if (S_ISREG($to_mode_oct)) { # only for regular file
1689                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1690                         }
1691                         $from_file_type = file_type($diff{'from_mode'});
1692                 }
1694                 if ($diff{'status'} eq "A") { # created
1695                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1696                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1697                         $mode_chng   .= "]</span>";
1698                         print "<td>" .
1699                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1700                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1701                                       -class => "list"}, esc_html($diff{'file'})) .
1702                               "</td>\n" .
1703                               "<td>$mode_chng</td>\n" .
1704                               "<td class=\"link\">" .
1705                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1706                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1707                                       "blob");
1708                         if ($action eq 'commitdiff') {
1709                                 # link to patch
1710                                 $patchno++;
1711                                 print " | " .
1712                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1713                         }
1714                         print "</td>\n";
1716                 } elsif ($diff{'status'} eq "D") { # deleted
1717                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1718                         print "<td>" .
1719                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1720                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1721                                        -class => "list"}, esc_html($diff{'file'})) .
1722                               "</td>\n" .
1723                               "<td>$mode_chng</td>\n" .
1724                               "<td class=\"link\">" .
1725                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1726                                                      hash_base=>$parent, file_name=>$diff{'file'})},
1727                                       "blob") .
1728                               " | ";
1729                         if ($action eq 'commitdiff') {
1730                                 # link to patch
1731                                 $patchno++;
1732                                 print " | " .
1733                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1734                         }
1735                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1736                                                      file_name=>$diff{'file'})},
1737                                       "history") .
1738                               "</td>\n";
1740                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1741                         my $mode_chnge = "";
1742                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1743                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1744                                 if ($from_file_type != $to_file_type) {
1745                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1746                                 }
1747                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1748                                         if ($from_mode_str && $to_mode_str) {
1749                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1750                                         } elsif ($to_mode_str) {
1751                                                 $mode_chnge .= " mode: $to_mode_str";
1752                                         }
1753                                 }
1754                                 $mode_chnge .= "]</span>\n";
1755                         }
1756                         print "<td>";
1757                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1758                                 print $cgi->a({-href => href(action=>"blobdiff",
1759                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1760                                                              hash_base=>$hash, hash_parent_base=>$parent,
1761                                                              file_name=>$diff{'file'}),
1762                                               -class => "list"}, esc_html($diff{'file'}));
1763                         } else { # only mode changed
1764                                 print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1765                                                              hash_base=>$hash, file_name=>$diff{'file'}),
1766                                               -class => "list"}, esc_html($diff{'file'}));
1767                         }
1768                         print "</td>\n" .
1769                               "<td>$mode_chnge</td>\n" .
1770                               "<td class=\"link\">" .
1771                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1772                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1773                                       "blob");
1774                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1775                                 if ($action eq 'commitdiff') {
1776                                         # link to patch
1777                                         $patchno++;
1778                                         print " | " .
1779                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1780                                 } else {
1781                                         print " | " .
1782                                                 $cgi->a({-href => href(action=>"blobdiff",
1783                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1784                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1785                                                                        file_name=>$diff{'file'})},
1786                                                         "diff");
1787                                 }
1788                         }
1789                         print " | " .
1790                                 $cgi->a({-href => href(action=>"history",
1791                                                        hash_base=>$hash, file_name=>$diff{'file'})},
1792                                         "history");
1793                         print "</td>\n";
1795                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1796                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1797                         my $nstatus = $status_name{$diff{'status'}};
1798                         my $mode_chng = "";
1799                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1800                                 # mode also for directories, so we cannot use $to_mode_str
1801                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1802                         }
1803                         print "<td>" .
1804                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1805                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1806                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1807                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1808                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1809                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1810                                       -class => "list"}, esc_html($diff{'from_file'})) .
1811                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1812                               "<td class=\"link\">" .
1813                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1814                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1815                                       "blob");
1816                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1817                                 if ($action eq 'commitdiff') {
1818                                         # link to patch
1819                                         $patchno++;
1820                                         print " | " .
1821                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1822                                 } else {
1823                                         print " | " .
1824                                                 $cgi->a({-href => href(action=>"blobdiff",
1825                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1826                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1827                                                                        file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1828                                                         "diff");
1829                                 }
1830                         }
1831                         print "</td>\n";
1833                 } # we should not encounter Unmerged (U) or Unknown (X) status
1834                 print "</tr>\n";
1835         }
1836         print "</table>\n";
1839 sub git_patchset_body {
1840         my ($fd, $difftree, $hash, $hash_parent) = @_;
1842         my $patch_idx = 0;
1843         my $in_header = 0;
1844         my $patch_found = 0;
1845         my $diffinfo;
1847         print "<div class=\"patchset\">\n";
1849         LINE:
1850         while (my $patch_line = <$fd>) {
1851                 chomp $patch_line;
1853                 if ($patch_line =~ m/^diff /) { # "git diff" header
1854                         # beginning of patch (in patchset)
1855                         if ($patch_found) {
1856                                 # close previous patch
1857                                 print "</div>\n"; # class="patch"
1858                         } else {
1859                                 # first patch in patchset
1860                                 $patch_found = 1;
1861                         }
1862                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1864                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1865                                 $diffinfo = $difftree->[$patch_idx];
1866                         } else {
1867                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1868                         }
1869                         $patch_idx++;
1871                         # for now, no extended header, hence we skip empty patches
1872                         # companion to  next LINE if $in_header;
1873                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1874                                 $in_header = 1;
1875                                 next LINE;
1876                         }
1878                         if ($diffinfo->{'status'} eq "A") { # added
1879                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1880                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1881                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1882                                               $diffinfo->{'to_id'}) . "(new)" .
1883                                       "</div>\n"; # class="diff_info"
1885                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1886                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1887                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1888                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1889                                               $diffinfo->{'from_id'}) . "(deleted)" .
1890                                       "</div>\n"; # class="diff_info"
1892                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1893                                  $diffinfo->{'status'} eq "C" || # copied
1894                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1895                                 print "<div class=\"diff_info\">" .
1896                                       file_type($diffinfo->{'from_mode'}) . ":" .
1897                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1898                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1899                                               $diffinfo->{'from_id'}) .
1900                                       " -> " .
1901                                       file_type($diffinfo->{'to_mode'}) . ":" .
1902                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1903                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1904                                               $diffinfo->{'to_id'});
1905                                 print "</div>\n"; # class="diff_info"
1907                         } else { # modified, mode changed, ...
1908                                 print "<div class=\"diff_info\">" .
1909                                       file_type($diffinfo->{'from_mode'}) . ":" .
1910                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1911                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1912                                               $diffinfo->{'from_id'}) .
1913                                       " -> " .
1914                                       file_type($diffinfo->{'to_mode'}) . ":" .
1915                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1916                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1917                                               $diffinfo->{'to_id'});
1918                                 print "</div>\n"; # class="diff_info"
1919                         }
1921                         #print "<div class=\"diff extended_header\">\n";
1922                         $in_header = 1;
1923                         next LINE;
1924                 } # start of patch in patchset
1927                 if ($in_header && $patch_line =~ m/^---/) {
1928                         #print "</div>\n"; # class="diff extended_header"
1929                         $in_header = 0;
1931                         my $file = $diffinfo->{'from_file'};
1932                         $file  ||= $diffinfo->{'file'};
1933                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1934                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
1935                                         -class => "list"}, esc_html($file));
1936                         $patch_line =~ s|a/.*$|a/$file|g;
1937                         print "<div class=\"diff from_file\">$patch_line</div>\n";
1939                         $patch_line = <$fd>;
1940                         chomp $patch_line;
1942                         #$patch_line =~ m/^+++/;
1943                         $file    = $diffinfo->{'to_file'};
1944                         $file  ||= $diffinfo->{'file'};
1945                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1946                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
1947                                         -class => "list"}, esc_html($file));
1948                         $patch_line =~ s|b/.*|b/$file|g;
1949                         print "<div class=\"diff to_file\">$patch_line</div>\n";
1951                         next LINE;
1952                 }
1953                 next LINE if $in_header;
1955                 print format_diff_line($patch_line);
1956         }
1957         print "</div>\n" if $patch_found; # class="patch"
1959         print "</div>\n"; # class="patchset"
1962 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1964 sub git_shortlog_body {
1965         # uses global variable $project
1966         my ($revlist, $from, $to, $refs, $extra) = @_;
1968         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
1969         my $have_snapshot = (defined $ctype && defined $suffix);
1971         $from = 0 unless defined $from;
1972         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1974         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1975         my $alternate = 0;
1976         for (my $i = $from; $i <= $to; $i++) {
1977                 my $commit = $revlist->[$i];
1978                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1979                 my $ref = format_ref_marker($refs, $commit);
1980                 my %co = parse_commit($commit);
1981                 if ($alternate) {
1982                         print "<tr class=\"dark\">\n";
1983                 } else {
1984                         print "<tr class=\"light\">\n";
1985                 }
1986                 $alternate ^= 1;
1987                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1988                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1989                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1990                       "<td>";
1991                 print format_subject_html($co{'title'}, $co{'title_short'},
1992                                           href(action=>"commit", hash=>$commit), $ref);
1993                 print "</td>\n" .
1994                       "<td class=\"link\">" .
1995                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1996                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
1997                 if ($have_snapshot) {
1998                         print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
1999                 }
2000                 print "</td>\n" .
2001                       "</tr>\n";
2002         }
2003         if (defined $extra) {
2004                 print "<tr>\n" .
2005                       "<td colspan=\"4\">$extra</td>\n" .
2006                       "</tr>\n";
2007         }
2008         print "</table>\n";
2011 sub git_history_body {
2012         # Warning: assumes constant type (blob or tree) during history
2013         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2015         $from = 0 unless defined $from;
2016         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2018         print "<table class=\"history\" cellspacing=\"0\">\n";
2019         my $alternate = 0;
2020         for (my $i = $from; $i <= $to; $i++) {
2021                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2022                         next;
2023                 }
2025                 my $commit = $1;
2026                 my %co = parse_commit($commit);
2027                 if (!%co) {
2028                         next;
2029                 }
2031                 my $ref = format_ref_marker($refs, $commit);
2033                 if ($alternate) {
2034                         print "<tr class=\"dark\">\n";
2035                 } else {
2036                         print "<tr class=\"light\">\n";
2037                 }
2038                 $alternate ^= 1;
2039                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2040                       # shortlog uses      chop_str($co{'author_name'}, 10)
2041                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2042                       "<td>";
2043                 # originally git_history used chop_str($co{'title'}, 50)
2044                 print format_subject_html($co{'title'}, $co{'title_short'},
2045                                           href(action=>"commit", hash=>$commit), $ref);
2046                 print "</td>\n" .
2047                       "<td class=\"link\">" .
2048                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2049                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2050                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
2052                 if ($ftype eq 'blob') {
2053                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2054                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2055                         if (defined $blob_current && defined $blob_parent &&
2056                                         $blob_current ne $blob_parent) {
2057                                 print " | " .
2058                                         $cgi->a({-href => href(action=>"blobdiff",
2059                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2060                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2061                                                                file_name=>$file_name)},
2062                                                 "diff to current");
2063                         }
2064                 }
2065                 print "</td>\n" .
2066                       "</tr>\n";
2067         }
2068         if (defined $extra) {
2069                 print "<tr>\n" .
2070                       "<td colspan=\"4\">$extra</td>\n" .
2071                       "</tr>\n";
2072         }
2073         print "</table>\n";
2076 sub git_tags_body {
2077         # uses global variable $project
2078         my ($taglist, $from, $to, $extra) = @_;
2079         $from = 0 unless defined $from;
2080         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2082         print "<table class=\"tags\" cellspacing=\"0\">\n";
2083         my $alternate = 0;
2084         for (my $i = $from; $i <= $to; $i++) {
2085                 my $entry = $taglist->[$i];
2086                 my %tag = %$entry;
2087                 my $comment_lines = $tag{'comment'};
2088                 my $comment = shift @$comment_lines;
2089                 my $comment_short;
2090                 if (defined $comment) {
2091                         $comment_short = chop_str($comment, 30, 5);
2092                 }
2093                 if ($alternate) {
2094                         print "<tr class=\"dark\">\n";
2095                 } else {
2096                         print "<tr class=\"light\">\n";
2097                 }
2098                 $alternate ^= 1;
2099                 print "<td><i>$tag{'age'}</i></td>\n" .
2100                       "<td>" .
2101                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2102                                -class => "list name"}, esc_html($tag{'name'})) .
2103                       "</td>\n" .
2104                       "<td>";
2105                 if (defined $comment) {
2106                         print format_subject_html($comment, $comment_short,
2107                                                   href(action=>"tag", hash=>$tag{'id'}));
2108                 }
2109                 print "</td>\n" .
2110                       "<td class=\"selflink\">";
2111                 if ($tag{'type'} eq "tag") {
2112                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2113                 } else {
2114                         print "&nbsp;";
2115                 }
2116                 print "</td>\n" .
2117                       "<td class=\"link\">" . " | " .
2118                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2119                 if ($tag{'reftype'} eq "commit") {
2120                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2121                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2122                 } elsif ($tag{'reftype'} eq "blob") {
2123                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2124                 }
2125                 print "</td>\n" .
2126                       "</tr>";
2127         }
2128         if (defined $extra) {
2129                 print "<tr>\n" .
2130                       "<td colspan=\"5\">$extra</td>\n" .
2131                       "</tr>\n";
2132         }
2133         print "</table>\n";
2136 sub git_heads_body {
2137         # uses global variable $project
2138         my ($taglist, $head, $from, $to, $extra) = @_;
2139         $from = 0 unless defined $from;
2140         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2142         print "<table class=\"heads\" cellspacing=\"0\">\n";
2143         my $alternate = 0;
2144         for (my $i = $from; $i <= $to; $i++) {
2145                 my $entry = $taglist->[$i];
2146                 my %tag = %$entry;
2147                 my $curr = $tag{'id'} eq $head;
2148                 if ($alternate) {
2149                         print "<tr class=\"dark\">\n";
2150                 } else {
2151                         print "<tr class=\"light\">\n";
2152                 }
2153                 $alternate ^= 1;
2154                 print "<td><i>$tag{'age'}</i></td>\n" .
2155                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2156                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2157                                -class => "list name"},esc_html($tag{'name'})) .
2158                       "</td>\n" .
2159                       "<td class=\"link\">" .
2160                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2161                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
2162                       "</td>\n" .
2163                       "</tr>";
2164         }
2165         if (defined $extra) {
2166                 print "<tr>\n" .
2167                       "<td colspan=\"3\">$extra</td>\n" .
2168                       "</tr>\n";
2169         }
2170         print "</table>\n";
2173 ## ======================================================================
2174 ## ======================================================================
2175 ## actions
2177 sub git_project_list {
2178         my $order = $cgi->param('o');
2179         if (defined $order && $order !~ m/project|descr|owner|age/) {
2180                 die_error(undef, "Unknown order parameter");
2181         }
2183         my @list = git_get_projects_list();
2184         my @projects;
2185         if (!@list) {
2186                 die_error(undef, "No projects found");
2187         }
2188         foreach my $pr (@list) {
2189                 my $head = git_get_head_hash($pr->{'path'});
2190                 if (!defined $head) {
2191                         next;
2192                 }
2193                 $git_dir = "$projectroot/$pr->{'path'}";
2194                 my %co = parse_commit($head);
2195                 if (!%co) {
2196                         next;
2197                 }
2198                 $pr->{'commit'} = \%co;
2199                 if (!defined $pr->{'descr'}) {
2200                         my $descr = git_get_project_description($pr->{'path'}) || "";
2201                         $pr->{'descr'} = chop_str($descr, 25, 5);
2202                 }
2203                 if (!defined $pr->{'owner'}) {
2204                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2205                 }
2206                 push @projects, $pr;
2207         }
2209         git_header_html();
2210         if (-f $home_text) {
2211                 print "<div class=\"index_include\">\n";
2212                 open (my $fd, $home_text);
2213                 print <$fd>;
2214                 close $fd;
2215                 print "</div>\n";
2216         }
2217         print "<table class=\"project_list\">\n" .
2218               "<tr>\n";
2219         $order ||= "project";
2220         if ($order eq "project") {
2221                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2222                 print "<th>Project</th>\n";
2223         } else {
2224                 print "<th>" .
2225                       $cgi->a({-href => href(project=>undef, order=>'project'),
2226                                -class => "header"}, "Project") .
2227                       "</th>\n";
2228         }
2229         if ($order eq "descr") {
2230                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2231                 print "<th>Description</th>\n";
2232         } else {
2233                 print "<th>" .
2234                       $cgi->a({-href => href(project=>undef, order=>'descr'),
2235                                -class => "header"}, "Description") .
2236                       "</th>\n";
2237         }
2238         if ($order eq "owner") {
2239                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2240                 print "<th>Owner</th>\n";
2241         } else {
2242                 print "<th>" .
2243                       $cgi->a({-href => href(project=>undef, order=>'owner'),
2244                                -class => "header"}, "Owner") .
2245                       "</th>\n";
2246         }
2247         if ($order eq "age") {
2248                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2249                 print "<th>Last Change</th>\n";
2250         } else {
2251                 print "<th>" .
2252                       $cgi->a({-href => href(project=>undef, order=>'age'),
2253                                -class => "header"}, "Last Change") .
2254                       "</th>\n";
2255         }
2256         print "<th></th>\n" .
2257               "</tr>\n";
2258         my $alternate = 0;
2259         foreach my $pr (@projects) {
2260                 if ($alternate) {
2261                         print "<tr class=\"dark\">\n";
2262                 } else {
2263                         print "<tr class=\"light\">\n";
2264                 }
2265                 $alternate ^= 1;
2266                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2267                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2268                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2269                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2270                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2271                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2272                       "<td class=\"link\">" .
2273                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2274                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2275                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
2276                       "</td>\n" .
2277                       "</tr>\n";
2278         }
2279         print "</table>\n";
2280         git_footer_html();
2283 sub git_project_index {
2284         my @projects = git_get_projects_list();
2286         print $cgi->header(
2287                 -type => 'text/plain',
2288                 -charset => 'utf-8',
2289                 -content_disposition => qq(inline; filename="index.aux"));
2291         foreach my $pr (@projects) {
2292                 if (!exists $pr->{'owner'}) {
2293                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2294                 }
2296                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2297                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2298                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2299                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2300                 $path  =~ s/ /\+/g;
2301                 $owner =~ s/ /\+/g;
2303                 print "$path $owner\n";
2304         }
2307 sub git_summary {
2308         my $descr = git_get_project_description($project) || "none";
2309         my $head = git_get_head_hash($project);
2310         my %co = parse_commit($head);
2311         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2313         my $owner = git_get_project_owner($project);
2315         my $refs = git_get_references();
2316         git_header_html();
2317         git_print_page_nav('summary','', $head);
2319         print "<div class=\"title\">&nbsp;</div>\n";
2320         print "<table cellspacing=\"0\">\n" .
2321               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2322               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2323               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2324         # use per project git URL list in $projectroot/$project/cloneurl
2325         # or make project git URL from git base URL and project name
2326         my $url_tag = "URL";
2327         my @url_list = git_get_project_url_list($project);
2328         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2329         foreach my $git_url (@url_list) {
2330                 next unless $git_url;
2331                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2332                 $url_tag = "";
2333         }
2334         print "</table>\n";
2336         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2337                 git_get_head_hash($project)
2338                 or die_error(undef, "Open git-rev-list failed");
2339         my @revlist = map { chomp; $_ } <$fd>;
2340         close $fd;
2341         git_print_header_div('shortlog');
2342         git_shortlog_body(\@revlist, 0, 15, $refs,
2343                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2345         my $taglist = git_get_refs_list("refs/tags");
2346         if (defined @$taglist) {
2347                 git_print_header_div('tags');
2348                 git_tags_body($taglist, 0, 15,
2349                               $cgi->a({-href => href(action=>"tags")}, "..."));
2350         }
2352         my $headlist = git_get_refs_list("refs/heads");
2353         if (defined @$headlist) {
2354                 git_print_header_div('heads');
2355                 git_heads_body($headlist, $head, 0, 15,
2356                                $cgi->a({-href => href(action=>"heads")}, "..."));
2357         }
2359         git_footer_html();
2362 sub git_tag {
2363         my $head = git_get_head_hash($project);
2364         git_header_html();
2365         git_print_page_nav('','', $head,undef,$head);
2366         my %tag = parse_tag($hash);
2367         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2368         print "<div class=\"title_text\">\n" .
2369               "<table cellspacing=\"0\">\n" .
2370               "<tr>\n" .
2371               "<td>object</td>\n" .
2372               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2373                                $tag{'object'}) . "</td>\n" .
2374               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2375                                               $tag{'type'}) . "</td>\n" .
2376               "</tr>\n";
2377         if (defined($tag{'author'})) {
2378                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2379                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2380                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2381                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2382                         "</td></tr>\n";
2383         }
2384         print "</table>\n\n" .
2385               "</div>\n";
2386         print "<div class=\"page_body\">";
2387         my $comment = $tag{'comment'};
2388         foreach my $line (@$comment) {
2389                 print esc_html($line) . "<br/>\n";
2390         }
2391         print "</div>\n";
2392         git_footer_html();
2395 sub git_blame2 {
2396         my $fd;
2397         my $ftype;
2399         my ($have_blame) = gitweb_check_feature('blame');
2400         if (!$have_blame) {
2401                 die_error('403 Permission denied', "Permission denied");
2402         }
2403         die_error('404 Not Found', "File name not defined") if (!$file_name);
2404         $hash_base ||= git_get_head_hash($project);
2405         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2406         my %co = parse_commit($hash_base)
2407                 or die_error(undef, "Reading commit failed");
2408         if (!defined $hash) {
2409                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2410                         or die_error(undef, "Error looking up file");
2411         }
2412         $ftype = git_get_type($hash);
2413         if ($ftype !~ "blob") {
2414                 die_error("400 Bad Request", "Object is not a blob");
2415         }
2416         open ($fd, "-|", git_cmd(), "blame", '-l', $file_name, $hash_base)
2417                 or die_error(undef, "Open git-blame failed");
2418         git_header_html();
2419         my $formats_nav =
2420                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2421                         "blob") .
2422                 " | " .
2423                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2424                         "head");
2425         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2426         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2427         git_print_page_path($file_name, $ftype, $hash_base);
2428         my @rev_color = (qw(light2 dark2));
2429         my $num_colors = scalar(@rev_color);
2430         my $current_color = 0;
2431         my $last_rev;
2432         print <<HTML;
2433 <div class="page_body">
2434 <table class="blame">
2435 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2436 HTML
2437         while (<$fd>) {
2438                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2439                 my $full_rev = $1;
2440                 my $rev = substr($full_rev, 0, 8);
2441                 my $lineno = $2;
2442                 my $data = $3;
2444                 if (!defined $last_rev) {
2445                         $last_rev = $full_rev;
2446                 } elsif ($last_rev ne $full_rev) {
2447                         $last_rev = $full_rev;
2448                         $current_color = ++$current_color % $num_colors;
2449                 }
2450                 print "<tr class=\"$rev_color[$current_color]\">\n";
2451                 print "<td class=\"sha1\">" .
2452                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2453                                 esc_html($rev)) . "</td>\n";
2454                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2455                       esc_html($lineno) . "</a></td>\n";
2456                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2457                 print "</tr>\n";
2458         }
2459         print "</table>\n";
2460         print "</div>";
2461         close $fd
2462                 or print "Reading blob failed\n";
2463         git_footer_html();
2466 sub git_blame {
2467         my $fd;
2469         my ($have_blame) = gitweb_check_feature('blame');
2470         if (!$have_blame) {
2471                 die_error('403 Permission denied', "Permission denied");
2472         }
2473         die_error('404 Not Found', "File name not defined") if (!$file_name);
2474         $hash_base ||= git_get_head_hash($project);
2475         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2476         my %co = parse_commit($hash_base)
2477                 or die_error(undef, "Reading commit failed");
2478         if (!defined $hash) {
2479                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2480                         or die_error(undef, "Error lookup file");
2481         }
2482         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2483                 or die_error(undef, "Open git-annotate failed");
2484         git_header_html();
2485         my $formats_nav =
2486                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2487                         "blob") .
2488                 " | " .
2489                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2490                         "head");
2491         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2492         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2493         git_print_page_path($file_name, 'blob', $hash_base);
2494         print "<div class=\"page_body\">\n";
2495         print <<HTML;
2496 <table class="blame">
2497   <tr>
2498     <th>Commit</th>
2499     <th>Age</th>
2500     <th>Author</th>
2501     <th>Line</th>
2502     <th>Data</th>
2503   </tr>
2504 HTML
2505         my @line_class = (qw(light dark));
2506         my $line_class_len = scalar (@line_class);
2507         my $line_class_num = $#line_class;
2508         while (my $line = <$fd>) {
2509                 my $long_rev;
2510                 my $short_rev;
2511                 my $author;
2512                 my $time;
2513                 my $lineno;
2514                 my $data;
2515                 my $age;
2516                 my $age_str;
2517                 my $age_class;
2519                 chomp $line;
2520                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2522                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2523                         $long_rev = $1;
2524                         $author   = $2;
2525                         $time     = $3;
2526                         $lineno   = $4;
2527                         $data     = $5;
2528                 } else {
2529                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2530                         next;
2531                 }
2532                 $short_rev  = substr ($long_rev, 0, 8);
2533                 $age        = time () - $time;
2534                 $age_str    = age_string ($age);
2535                 $age_str    =~ s/ /&nbsp;/g;
2536                 $age_class  = age_class($age);
2537                 $author     = esc_html ($author);
2538                 $author     =~ s/ /&nbsp;/g;
2540                 $data = untabify($data);
2541                 $data = esc_html ($data);
2543                 print <<HTML;
2544   <tr class="$line_class[$line_class_num]">
2545     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2546     <td class="$age_class">$age_str</td>
2547     <td>$author</td>
2548     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2549     <td class="pre">$data</td>
2550   </tr>
2551 HTML
2552         } # while (my $line = <$fd>)
2553         print "</table>\n\n";
2554         close $fd
2555                 or print "Reading blob failed.\n";
2556         print "</div>";
2557         git_footer_html();
2560 sub git_tags {
2561         my $head = git_get_head_hash($project);
2562         git_header_html();
2563         git_print_page_nav('','', $head,undef,$head);
2564         git_print_header_div('summary', $project);
2566         my $taglist = git_get_refs_list("refs/tags");
2567         if (defined @$taglist) {
2568                 git_tags_body($taglist);
2569         }
2570         git_footer_html();
2573 sub git_heads {
2574         my $head = git_get_head_hash($project);
2575         git_header_html();
2576         git_print_page_nav('','', $head,undef,$head);
2577         git_print_header_div('summary', $project);
2579         my $taglist = git_get_refs_list("refs/heads");
2580         if (defined @$taglist) {
2581                 git_heads_body($taglist, $head);
2582         }
2583         git_footer_html();
2586 sub git_blob_plain {
2587         my $expires;
2589         if (!defined $hash) {
2590                 if (defined $file_name) {
2591                         my $base = $hash_base || git_get_head_hash($project);
2592                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2593                                 or die_error(undef, "Error lookup file");
2594                 } else {
2595                         die_error(undef, "No file name defined");
2596                 }
2597         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2598                 # blobs defined by non-textual hash id's can be cached
2599                 $expires = "+1d";
2600         }
2602         my $type = shift;
2603         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2604                 or die_error(undef, "Couldn't cat $file_name, $hash");
2606         $type ||= blob_mimetype($fd, $file_name);
2608         # save as filename, even when no $file_name is given
2609         my $save_as = "$hash";
2610         if (defined $file_name) {
2611                 $save_as = $file_name;
2612         } elsif ($type =~ m/^text\//) {
2613                 $save_as .= '.txt';
2614         }
2616         print $cgi->header(
2617                 -type => "$type",
2618                 -expires=>$expires,
2619                 -content_disposition => "inline; filename=\"$save_as\"");
2620         undef $/;
2621         binmode STDOUT, ':raw';
2622         print <$fd>;
2623         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2624         $/ = "\n";
2625         close $fd;
2628 sub git_blob {
2629         my $expires;
2631         if (!defined $hash) {
2632                 if (defined $file_name) {
2633                         my $base = $hash_base || git_get_head_hash($project);
2634                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2635                                 or die_error(undef, "Error lookup file");
2636                 } else {
2637                         die_error(undef, "No file name defined");
2638                 }
2639         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2640                 # blobs defined by non-textual hash id's can be cached
2641                 $expires = "+1d";
2642         }
2644         my ($have_blame) = gitweb_check_feature('blame');
2645         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2646                 or die_error(undef, "Couldn't cat $file_name, $hash");
2647         my $mimetype = blob_mimetype($fd, $file_name);
2648         if ($mimetype !~ m/^text\//) {
2649                 close $fd;
2650                 return git_blob_plain($mimetype);
2651         }
2652         git_header_html(undef, $expires);
2653         my $formats_nav = '';
2654         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2655                 if (defined $file_name) {
2656                         if ($have_blame) {
2657                                 $formats_nav .=
2658                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2659                                                                hash=>$hash, file_name=>$file_name)},
2660                                                 "blame") .
2661                                         " | ";
2662                         }
2663                         $formats_nav .=
2664                                 $cgi->a({-href => href(action=>"blob_plain",
2665                                                        hash=>$hash, file_name=>$file_name)},
2666                                         "plain") .
2667                                 " | " .
2668                                 $cgi->a({-href => href(action=>"blob",
2669                                                        hash_base=>"HEAD", file_name=>$file_name)},
2670                                         "head");
2671                 } else {
2672                         $formats_nav .=
2673                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2674                 }
2675                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2676                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2677         } else {
2678                 print "<div class=\"page_nav\">\n" .
2679                       "<br/><br/></div>\n" .
2680                       "<div class=\"title\">$hash</div>\n";
2681         }
2682         git_print_page_path($file_name, "blob", $hash_base);
2683         print "<div class=\"page_body\">\n";
2684         my $nr;
2685         while (my $line = <$fd>) {
2686                 chomp $line;
2687                 $nr++;
2688                 $line = untabify($line);
2689                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2690                        $nr, $nr, $nr, esc_html($line);
2691         }
2692         close $fd
2693                 or print "Reading blob failed.\n";
2694         print "</div>";
2695         git_footer_html();
2698 sub git_tree {
2699         if (!defined $hash) {
2700                 $hash = git_get_head_hash($project);
2701                 if (defined $file_name) {
2702                         my $base = $hash_base || $hash;
2703                         $hash = git_get_hash_by_path($base, $file_name, "tree");
2704                 }
2705                 if (!defined $hash_base) {
2706                         $hash_base = $hash;
2707                 }
2708         }
2709         $/ = "\0";
2710         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2711                 or die_error(undef, "Open git-ls-tree failed");
2712         my @entries = map { chomp; $_ } <$fd>;
2713         close $fd or die_error(undef, "Reading tree failed");
2714         $/ = "\n";
2716         my $refs = git_get_references();
2717         my $ref = format_ref_marker($refs, $hash_base);
2718         git_header_html();
2719         my $base = "";
2720         my ($have_blame) = gitweb_check_feature('blame');
2721         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2722                 git_print_page_nav('tree','', $hash_base);
2723                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2724         } else {
2725                 undef $hash_base;
2726                 print "<div class=\"page_nav\">\n";
2727                 print "<br/><br/></div>\n";
2728                 print "<div class=\"title\">$hash</div>\n";
2729         }
2730         if (defined $file_name) {
2731                 $base = esc_html("$file_name/");
2732         }
2733         git_print_page_path($file_name, 'tree', $hash_base);
2734         print "<div class=\"page_body\">\n";
2735         print "<table cellspacing=\"0\">\n";
2736         my $alternate = 0;
2737         foreach my $line (@entries) {
2738                 my %t = parse_ls_tree_line($line, -z => 1);
2740                 if ($alternate) {
2741                         print "<tr class=\"dark\">\n";
2742                 } else {
2743                         print "<tr class=\"light\">\n";
2744                 }
2745                 $alternate ^= 1;
2747                 git_print_tree_entry(\%t, $base, $hash_base, $have_blame);
2749                 print "</tr>\n";
2750         }
2751         print "</table>\n" .
2752               "</div>";
2753         git_footer_html();
2756 sub git_snapshot {
2758         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2759         my $have_snapshot = (defined $ctype && defined $suffix);
2760         if (!$have_snapshot) {
2761                 die_error('403 Permission denied', "Permission denied");
2762         }
2764         if (!defined $hash) {
2765                 $hash = git_get_head_hash($project);
2766         }
2768         my $filename = basename($project) . "-$hash.tar.$suffix";
2770         print $cgi->header(-type => 'application/x-tar',
2771                            -content_encoding => $ctype,
2772                            -content_disposition => "inline; filename=\"$filename\"",
2773                            -status => '200 OK');
2775         my $git_command = git_cmd_str();
2776         open my $fd, "-|", "$git_command tar-tree $hash \'$project\' | $command" or
2777                 die_error(undef, "Execute git-tar-tree failed.");
2778         binmode STDOUT, ':raw';
2779         print <$fd>;
2780         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2781         close $fd;
2785 sub git_log {
2786         my $head = git_get_head_hash($project);
2787         if (!defined $hash) {
2788                 $hash = $head;
2789         }
2790         if (!defined $page) {
2791                 $page = 0;
2792         }
2793         my $refs = git_get_references();
2795         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2796         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2797                 or die_error(undef, "Open git-rev-list failed");
2798         my @revlist = map { chomp; $_ } <$fd>;
2799         close $fd;
2801         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2803         git_header_html();
2804         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2806         if (!@revlist) {
2807                 my %co = parse_commit($hash);
2809                 git_print_header_div('summary', $project);
2810                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2811         }
2812         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2813                 my $commit = $revlist[$i];
2814                 my $ref = format_ref_marker($refs, $commit);
2815                 my %co = parse_commit($commit);
2816                 next if !%co;
2817                 my %ad = parse_date($co{'author_epoch'});
2818                 git_print_header_div('commit',
2819                                "<span class=\"age\">$co{'age_string'}</span>" .
2820                                esc_html($co{'title'}) . $ref,
2821                                $commit);
2822                 print "<div class=\"title_text\">\n" .
2823                       "<div class=\"log_link\">\n" .
2824                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2825                       " | " .
2826                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2827                       "<br/>\n" .
2828                       "</div>\n" .
2829                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2830                       "</div>\n";
2832                 print "<div class=\"log_body\">\n";
2833                 git_print_simplified_log($co{'comment'});
2834                 print "</div>\n";
2835         }
2836         git_footer_html();
2839 sub git_commit {
2840         my %co = parse_commit($hash);
2841         if (!%co) {
2842                 die_error(undef, "Unknown commit object");
2843         }
2844         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2845         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2847         my $parent = $co{'parent'};
2848         if (!defined $parent) {
2849                 $parent = "--root";
2850         }
2851         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2852                 or die_error(undef, "Open git-diff-tree failed");
2853         my @difftree = map { chomp; $_ } <$fd>;
2854         close $fd or die_error(undef, "Reading git-diff-tree failed");
2856         # non-textual hash id's can be cached
2857         my $expires;
2858         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2859                 $expires = "+1d";
2860         }
2861         my $refs = git_get_references();
2862         my $ref = format_ref_marker($refs, $co{'id'});
2864         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2865         my $have_snapshot = (defined $ctype && defined $suffix);
2867         my $formats_nav = '';
2868         if (defined $file_name && defined $co{'parent'}) {
2869                 my $parent = $co{'parent'};
2870                 $formats_nav .=
2871                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2872                                 "blame");
2873         }
2874         git_header_html(undef, $expires);
2875         git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2876                            $hash, $co{'tree'}, $hash,
2877                            $formats_nav);
2879         if (defined $co{'parent'}) {
2880                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2881         } else {
2882                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2883         }
2884         print "<div class=\"title_text\">\n" .
2885               "<table cellspacing=\"0\">\n";
2886         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2887               "<tr>" .
2888               "<td></td><td> $ad{'rfc2822'}";
2889         if ($ad{'hour_local'} < 6) {
2890                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2891                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2892         } else {
2893                 printf(" (%02d:%02d %s)",
2894                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2895         }
2896         print "</td>" .
2897               "</tr>\n";
2898         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2899         print "<tr><td></td><td> $cd{'rfc2822'}" .
2900               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2901               "</td></tr>\n";
2902         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2903         print "<tr>" .
2904               "<td>tree</td>" .
2905               "<td class=\"sha1\">" .
2906               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2907                        class => "list"}, $co{'tree'}) .
2908               "</td>" .
2909               "<td class=\"link\">" .
2910               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2911                       "tree");
2912         if ($have_snapshot) {
2913                 print " | " .
2914                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2915         }
2916         print "</td>" .
2917               "</tr>\n";
2918         my $parents = $co{'parents'};
2919         foreach my $par (@$parents) {
2920                 print "<tr>" .
2921                       "<td>parent</td>" .
2922                       "<td class=\"sha1\">" .
2923                       $cgi->a({-href => href(action=>"commit", hash=>$par),
2924                                class => "list"}, $par) .
2925                       "</td>" .
2926                       "<td class=\"link\">" .
2927                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2928                       " | " .
2929                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
2930                       "</td>" .
2931                       "</tr>\n";
2932         }
2933         print "</table>".
2934               "</div>\n";
2936         print "<div class=\"page_body\">\n";
2937         git_print_log($co{'comment'});
2938         print "</div>\n";
2940         git_difftree_body(\@difftree, $hash, $parent);
2942         git_footer_html();
2945 sub git_blobdiff {
2946         my $format = shift || 'html';
2948         my $fd;
2949         my @difftree;
2950         my %diffinfo;
2951         my $expires;
2953         # preparing $fd and %diffinfo for git_patchset_body
2954         # new style URI
2955         if (defined $hash_base && defined $hash_parent_base) {
2956                 if (defined $file_name) {
2957                         # read raw output
2958                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
2959                                 "--", $file_name
2960                                 or die_error(undef, "Open git-diff-tree failed");
2961                         @difftree = map { chomp; $_ } <$fd>;
2962                         close $fd
2963                                 or die_error(undef, "Reading git-diff-tree failed");
2964                         @difftree
2965                                 or die_error('404 Not Found', "Blob diff not found");
2967                 } elsif (defined $hash &&
2968                          $hash =~ /[0-9a-fA-F]{40}/) {
2969                         # try to find filename from $hash
2971                         # read filtered raw output
2972                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
2973                                 or die_error(undef, "Open git-diff-tree failed");
2974                         @difftree =
2975                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
2976                                 # $hash == to_id
2977                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
2978                                 map { chomp; $_ } <$fd>;
2979                         close $fd
2980                                 or die_error(undef, "Reading git-diff-tree failed");
2981                         @difftree
2982                                 or die_error('404 Not Found', "Blob diff not found");
2984                 } else {
2985                         die_error('404 Not Found', "Missing one of the blob diff parameters");
2986                 }
2988                 if (@difftree > 1) {
2989                         die_error('404 Not Found', "Ambiguous blob diff specification");
2990                 }
2992                 %diffinfo = parse_difftree_raw_line($difftree[0]);
2993                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
2994                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
2996                 $hash_parent ||= $diffinfo{'from_id'};
2997                 $hash        ||= $diffinfo{'to_id'};
2999                 # non-textual hash id's can be cached
3000                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3001                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3002                         $expires = '+1d';
3003                 }
3005                 # open patch output
3006                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3007                         '-p', $hash_parent_base, $hash_base,
3008                         "--", $file_name
3009                         or die_error(undef, "Open git-diff-tree failed");
3010         }
3012         # old/legacy style URI
3013         if (!%diffinfo && # if new style URI failed
3014             defined $hash && defined $hash_parent) {
3015                 # fake git-diff-tree raw output
3016                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3017                 $diffinfo{'from_id'} = $hash_parent;
3018                 $diffinfo{'to_id'}   = $hash;
3019                 if (defined $file_name) {
3020                         if (defined $file_parent) {
3021                                 $diffinfo{'status'} = '2';
3022                                 $diffinfo{'from_file'} = $file_parent;
3023                                 $diffinfo{'to_file'}   = $file_name;
3024                         } else { # assume not renamed
3025                                 $diffinfo{'status'} = '1';
3026                                 $diffinfo{'from_file'} = $file_name;
3027                                 $diffinfo{'to_file'}   = $file_name;
3028                         }
3029                 } else { # no filename given
3030                         $diffinfo{'status'} = '2';
3031                         $diffinfo{'from_file'} = $hash_parent;
3032                         $diffinfo{'to_file'}   = $hash;
3033                 }
3035                 # non-textual hash id's can be cached
3036                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3037                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3038                         $expires = '+1d';
3039                 }
3041                 # open patch output
3042                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3043                         or die_error(undef, "Open git-diff failed");
3044         } else  {
3045                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3046                         unless %diffinfo;
3047         }
3049         # header
3050         if ($format eq 'html') {
3051                 my $formats_nav =
3052                         $cgi->a({-href => href(action=>"blobdiff_plain",
3053                                                hash=>$hash, hash_parent=>$hash_parent,
3054                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3055                                                file_name=>$file_name, file_parent=>$file_parent)},
3056                                 "plain");
3057                 git_header_html(undef, $expires);
3058                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3059                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3060                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3061                 } else {
3062                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3063                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3064                 }
3065                 if (defined $file_name) {
3066                         git_print_page_path($file_name, "blob", $hash_base);
3067                 } else {
3068                         print "<div class=\"page_path\"></div>\n";
3069                 }
3071         } elsif ($format eq 'plain') {
3072                 print $cgi->header(
3073                         -type => 'text/plain',
3074                         -charset => 'utf-8',
3075                         -expires => $expires,
3076                         -content_disposition => qq(inline; filename="${file_name}.patch"));
3078                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3080         } else {
3081                 die_error(undef, "Unknown blobdiff format");
3082         }
3084         # patch
3085         if ($format eq 'html') {
3086                 print "<div class=\"page_body\">\n";
3088                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3089                 close $fd;
3091                 print "</div>\n"; # class="page_body"
3092                 git_footer_html();
3094         } else {
3095                 while (my $line = <$fd>) {
3096                         $line =~ s!a/($hash|$hash_parent)!a/$diffinfo{'from_file'}!g;
3097                         $line =~ s!b/($hash|$hash_parent)!b/$diffinfo{'to_file'}!g;
3099                         print $line;
3101                         last if $line =~ m!^\+\+\+!;
3102                 }
3103                 local $/ = undef;
3104                 print <$fd>;
3105                 close $fd;
3106         }
3109 sub git_blobdiff_plain {
3110         git_blobdiff('plain');
3113 sub git_commitdiff {
3114         my $format = shift || 'html';
3115         my %co = parse_commit($hash);
3116         if (!%co) {
3117                 die_error(undef, "Unknown commit object");
3118         }
3119         if (!defined $hash_parent) {
3120                 $hash_parent = $co{'parent'} || '--root';
3121         }
3123         # read commitdiff
3124         my $fd;
3125         my @difftree;
3126         if ($format eq 'html') {
3127                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3128                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3129                         or die_error(undef, "Open git-diff-tree failed");
3131                 while (chomp(my $line = <$fd>)) {
3132                         # empty line ends raw part of diff-tree output
3133                         last unless $line;
3134                         push @difftree, $line;
3135                 }
3137         } elsif ($format eq 'plain') {
3138                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3139                         '-p', $hash_parent, $hash
3140                         or die_error(undef, "Open git-diff-tree failed");
3142         } else {
3143                 die_error(undef, "Unknown commitdiff format");
3144         }
3146         # non-textual hash id's can be cached
3147         my $expires;
3148         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3149                 $expires = "+1d";
3150         }
3152         # write commit message
3153         if ($format eq 'html') {
3154                 my $refs = git_get_references();
3155                 my $ref = format_ref_marker($refs, $co{'id'});
3156                 my $formats_nav =
3157                         $cgi->a({-href => href(action=>"commitdiff_plain",
3158                                                hash=>$hash, hash_parent=>$hash_parent)},
3159                                 "plain");
3161                 git_header_html(undef, $expires);
3162                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3163                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3164                 git_print_authorship(\%co);
3165                 print "<div class=\"page_body\">\n";
3166                 print "<div class=\"log\">\n";
3167                 git_print_simplified_log($co{'comment'}, 1); # skip title
3168                 print "</div>\n"; # class="log"
3170         } elsif ($format eq 'plain') {
3171                 my $refs = git_get_references("tags");
3172                 my $tagname = git_get_rev_name_tags($hash);
3173                 my $filename = basename($project) . "-$hash.patch";
3175                 print $cgi->header(
3176                         -type => 'text/plain',
3177                         -charset => 'utf-8',
3178                         -expires => $expires,
3179                         -content_disposition => qq(inline; filename="$filename"));
3180                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3181                 print <<TEXT;
3182 From: $co{'author'}
3183 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3184 Subject: $co{'title'}
3185 TEXT
3186                 print "X-Git-Tag: $tagname\n" if $tagname;
3187                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3189                 foreach my $line (@{$co{'comment'}}) {
3190                         print "$line\n";
3191                 }
3192                 print "---\n\n";
3193         }
3195         # write patch
3196         if ($format eq 'html') {
3197                 git_difftree_body(\@difftree, $hash, $hash_parent);
3198                 print "<br/>\n";
3200                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3201                 close $fd;
3202                 print "</div>\n"; # class="page_body"
3203                 git_footer_html();
3205         } elsif ($format eq 'plain') {
3206                 local $/ = undef;
3207                 print <$fd>;
3208                 close $fd
3209                         or print "Reading git-diff-tree failed\n";
3210         }
3213 sub git_commitdiff_plain {
3214         git_commitdiff('plain');
3217 sub git_history {
3218         if (!defined $hash_base) {
3219                 $hash_base = git_get_head_hash($project);
3220         }
3221         if (!defined $page) {
3222                 $page = 0;
3223         }
3224         my $ftype;
3225         my %co = parse_commit($hash_base);
3226         if (!%co) {
3227                 die_error(undef, "Unknown commit object");
3228         }
3230         my $refs = git_get_references();
3231         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3233         if (!defined $hash && defined $file_name) {
3234                 $hash = git_get_hash_by_path($hash_base, $file_name);
3235         }
3236         if (defined $hash) {
3237                 $ftype = git_get_type($hash);
3238         }
3240         open my $fd, "-|",
3241                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3242                         or die_error(undef, "Open git-rev-list-failed");
3243         my @revlist = map { chomp; $_ } <$fd>;
3244         close $fd
3245                 or die_error(undef, "Reading git-rev-list failed");
3247         my $paging_nav = '';
3248         if ($page > 0) {
3249                 $paging_nav .=
3250                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3251                                                file_name=>$file_name)},
3252                                 "first");
3253                 $paging_nav .= " &sdot; " .
3254                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3255                                                file_name=>$file_name, page=>$page-1),
3256                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3257         } else {
3258                 $paging_nav .= "first";
3259                 $paging_nav .= " &sdot; prev";
3260         }
3261         if ($#revlist >= (100 * ($page+1)-1)) {
3262                 $paging_nav .= " &sdot; " .
3263                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3264                                                file_name=>$file_name, page=>$page+1),
3265                                  -accesskey => "n", -title => "Alt-n"}, "next");
3266         } else {
3267                 $paging_nav .= " &sdot; next";
3268         }
3269         my $next_link = '';
3270         if ($#revlist >= (100 * ($page+1)-1)) {
3271                 $next_link =
3272                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3273                                                file_name=>$file_name, page=>$page+1),
3274                                  -title => "Alt-n"}, "next");
3275         }
3277         git_header_html();
3278         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3279         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3280         git_print_page_path($file_name, $ftype, $hash_base);
3282         git_history_body(\@revlist, ($page * 100), $#revlist,
3283                          $refs, $hash_base, $ftype, $next_link);
3285         git_footer_html();
3288 sub git_search {
3289         if (!defined $searchtext) {
3290                 die_error(undef, "Text field empty");
3291         }
3292         if (!defined $hash) {
3293                 $hash = git_get_head_hash($project);
3294         }
3295         my %co = parse_commit($hash);
3296         if (!%co) {
3297                 die_error(undef, "Unknown commit object");
3298         }
3300         my $commit_search = 1;
3301         my $author_search = 0;
3302         my $committer_search = 0;
3303         my $pickaxe_search = 0;
3304         if ($searchtext =~ s/^author\\://i) {
3305                 $author_search = 1;
3306         } elsif ($searchtext =~ s/^committer\\://i) {
3307                 $committer_search = 1;
3308         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3309                 $commit_search = 0;
3310                 $pickaxe_search = 1;
3312                 # pickaxe may take all resources of your box and run for several minutes
3313                 # with every query - so decide by yourself how public you make this feature
3314                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3315                 if (!$have_pickaxe) {
3316                         die_error('403 Permission denied', "Permission denied");
3317                 }
3318         }
3319         git_header_html();
3320         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3321         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3323         print "<table cellspacing=\"0\">\n";
3324         my $alternate = 0;
3325         if ($commit_search) {
3326                 $/ = "\0";
3327                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3328                 while (my $commit_text = <$fd>) {
3329                         if (!grep m/$searchtext/i, $commit_text) {
3330                                 next;
3331                         }
3332                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3333                                 next;
3334                         }
3335                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3336                                 next;
3337                         }
3338                         my @commit_lines = split "\n", $commit_text;
3339                         my %co = parse_commit(undef, \@commit_lines);
3340                         if (!%co) {
3341                                 next;
3342                         }
3343                         if ($alternate) {
3344                                 print "<tr class=\"dark\">\n";
3345                         } else {
3346                                 print "<tr class=\"light\">\n";
3347                         }
3348                         $alternate ^= 1;
3349                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3350                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3351                               "<td>" .
3352                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3353                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3354                         my $comment = $co{'comment'};
3355                         foreach my $line (@$comment) {
3356                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3357                                         my $lead = esc_html($1) || "";
3358                                         $lead = chop_str($lead, 30, 10);
3359                                         my $match = esc_html($2) || "";
3360                                         my $trail = esc_html($3) || "";
3361                                         $trail = chop_str($trail, 30, 10);
3362                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3363                                         print chop_str($text, 80, 5) . "<br/>\n";
3364                                 }
3365                         }
3366                         print "</td>\n" .
3367                               "<td class=\"link\">" .
3368                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3369                               " | " .
3370                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3371                         print "</td>\n" .
3372                               "</tr>\n";
3373                 }
3374                 close $fd;
3375         }
3377         if ($pickaxe_search) {
3378                 $/ = "\n";
3379                 my $git_command = git_cmd_str();
3380                 open my $fd, "-|", "$git_command rev-list $hash | " .
3381                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3382                 undef %co;
3383                 my @files;
3384                 while (my $line = <$fd>) {
3385                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3386                                 my %set;
3387                                 $set{'file'} = $6;
3388                                 $set{'from_id'} = $3;
3389                                 $set{'to_id'} = $4;
3390                                 $set{'id'} = $set{'to_id'};
3391                                 if ($set{'id'} =~ m/0{40}/) {
3392                                         $set{'id'} = $set{'from_id'};
3393                                 }
3394                                 if ($set{'id'} =~ m/0{40}/) {
3395                                         next;
3396                                 }
3397                                 push @files, \%set;
3398                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3399                                 if (%co) {
3400                                         if ($alternate) {
3401                                                 print "<tr class=\"dark\">\n";
3402                                         } else {
3403                                                 print "<tr class=\"light\">\n";
3404                                         }
3405                                         $alternate ^= 1;
3406                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3407                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3408                                               "<td>" .
3409                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3410                                                       -class => "list subject"},
3411                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3412                                         while (my $setref = shift @files) {
3413                                                 my %set = %$setref;
3414                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3415                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3416                                                               -class => "list"},
3417                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3418                                                       "<br/>\n";
3419                                         }
3420                                         print "</td>\n" .
3421                                               "<td class=\"link\">" .
3422                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3423                                               " | " .
3424                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3425                                         print "</td>\n" .
3426                                               "</tr>\n";
3427                                 }
3428                                 %co = parse_commit($1);
3429                         }
3430                 }
3431                 close $fd;
3432         }
3433         print "</table>\n";
3434         git_footer_html();
3437 sub git_shortlog {
3438         my $head = git_get_head_hash($project);
3439         if (!defined $hash) {
3440                 $hash = $head;
3441         }
3442         if (!defined $page) {
3443                 $page = 0;
3444         }
3445         my $refs = git_get_references();
3447         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3448         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3449                 or die_error(undef, "Open git-rev-list failed");
3450         my @revlist = map { chomp; $_ } <$fd>;
3451         close $fd;
3453         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3454         my $next_link = '';
3455         if ($#revlist >= (100 * ($page+1)-1)) {
3456                 $next_link =
3457                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3458                                  -title => "Alt-n"}, "next");
3459         }
3462         git_header_html();
3463         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3464         git_print_header_div('summary', $project);
3466         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3468         git_footer_html();
3471 ## ......................................................................
3472 ## feeds (RSS, OPML)
3474 sub git_rss {
3475         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3476         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3477                 or die_error(undef, "Open git-rev-list failed");
3478         my @revlist = map { chomp; $_ } <$fd>;
3479         close $fd or die_error(undef, "Reading git-rev-list failed");
3480         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3481         print <<XML;
3482 <?xml version="1.0" encoding="utf-8"?>
3483 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3484 <channel>
3485 <title>$project $my_uri $my_url</title>
3486 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3487 <description>$project log</description>
3488 <language>en</language>
3489 XML
3491         for (my $i = 0; $i <= $#revlist; $i++) {
3492                 my $commit = $revlist[$i];
3493                 my %co = parse_commit($commit);
3494                 # we read 150, we always show 30 and the ones more recent than 48 hours
3495                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3496                         last;
3497                 }
3498                 my %cd = parse_date($co{'committer_epoch'});
3499                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3500                         $co{'parent'}, $co{'id'}
3501                         or next;
3502                 my @difftree = map { chomp; $_ } <$fd>;
3503                 close $fd
3504                         or next;
3505                 print "<item>\n" .
3506                       "<title>" .
3507                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3508                       "</title>\n" .
3509                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3510                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3511                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3512                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3513                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3514                       "<content:encoded>" .
3515                       "<![CDATA[\n";
3516                 my $comment = $co{'comment'};
3517                 foreach my $line (@$comment) {
3518                         $line = decode("utf8", $line, Encode::FB_DEFAULT);
3519                         print "$line<br/>\n";
3520                 }
3521                 print "<br/>\n";
3522                 foreach my $line (@difftree) {
3523                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3524                                 next;
3525                         }
3526                         my $file = validate_input(unquote($7));
3527                         $file = decode("utf8", $file, Encode::FB_DEFAULT);
3528                         print "$file<br/>\n";
3529                 }
3530                 print "]]>\n" .
3531                       "</content:encoded>\n" .
3532                       "</item>\n";
3533         }
3534         print "</channel></rss>";
3537 sub git_opml {
3538         my @list = git_get_projects_list();
3540         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3541         print <<XML;
3542 <?xml version="1.0" encoding="utf-8"?>
3543 <opml version="1.0">
3544 <head>
3545   <title>$site_name Git OPML Export</title>
3546 </head>
3547 <body>
3548 <outline text="git RSS feeds">
3549 XML
3551         foreach my $pr (@list) {
3552                 my %proj = %$pr;
3553                 my $head = git_get_head_hash($proj{'path'});
3554                 if (!defined $head) {
3555                         next;
3556                 }
3557                 $git_dir = "$projectroot/$proj{'path'}";
3558                 my %co = parse_commit($head);
3559                 if (!%co) {
3560                         next;
3561                 }
3563                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3564                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3565                 my $html = "$my_url?p=$proj{'path'};a=summary";
3566                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3567         }
3568         print <<XML;
3569 </outline>
3570 </body>
3571 </opml>
3572 XML