Code

gitweb: Even more support for PATH_INFO based URLs
[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 $actions{$action}->();
356 exit;
358 ## ======================================================================
359 ## action links
361 sub href(%) {
362         my %params = @_;
364         my @mapping = (
365                 project => "p",
366                 action => "a",
367                 file_name => "f",
368                 file_parent => "fp",
369                 hash => "h",
370                 hash_parent => "hp",
371                 hash_base => "hb",
372                 hash_parent_base => "hpb",
373                 page => "pg",
374                 order => "o",
375                 searchtext => "s",
376         );
377         my %mapping = @mapping;
379         $params{'project'} = $project unless exists $params{'project'};
381         my @result = ();
382         for (my $i = 0; $i < @mapping; $i += 2) {
383                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
384                 if (defined $params{$name}) {
385                         push @result, $symbol . "=" . esc_param($params{$name});
386                 }
387         }
388         return "$my_uri?" . join(';', @result);
392 ## ======================================================================
393 ## validation, quoting/unquoting and escaping
395 sub validate_input {
396         my $input = shift;
398         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
399                 return $input;
400         }
401         if ($input =~ m/(^|\/)(|\.|\.\.)($|\/)/) {
402                 return undef;
403         }
404         if ($input =~ m/[^a-zA-Z0-9_\x80-\xff\ \t\.\/\-\+\#\~\%]/) {
405                 return undef;
406         }
407         return $input;
410 # quote unsafe chars, but keep the slash, even when it's not
411 # correct, but quoted slashes look too horrible in bookmarks
412 sub esc_param {
413         my $str = shift;
414         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
415         $str =~ s/\+/%2B/g;
416         $str =~ s/ /\+/g;
417         return $str;
420 # replace invalid utf8 character with SUBSTITUTION sequence
421 sub esc_html {
422         my $str = shift;
423         $str = decode("utf8", $str, Encode::FB_DEFAULT);
424         $str = escapeHTML($str);
425         $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
426         return $str;
429 # git may return quoted and escaped filenames
430 sub unquote {
431         my $str = shift;
432         if ($str =~ m/^"(.*)"$/) {
433                 $str = $1;
434                 $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
435         }
436         return $str;
439 # escape tabs (convert tabs to spaces)
440 sub untabify {
441         my $line = shift;
443         while ((my $pos = index($line, "\t")) != -1) {
444                 if (my $count = (8 - ($pos % 8))) {
445                         my $spaces = ' ' x $count;
446                         $line =~ s/\t/$spaces/;
447                 }
448         }
450         return $line;
453 sub project_in_list {
454         my $project = shift;
455         my @list = git_get_projects_list();
456         return @list && scalar(grep { $_->{'path'} eq $project } @list);
459 ## ----------------------------------------------------------------------
460 ## HTML aware string manipulation
462 sub chop_str {
463         my $str = shift;
464         my $len = shift;
465         my $add_len = shift || 10;
467         # allow only $len chars, but don't cut a word if it would fit in $add_len
468         # if it doesn't fit, cut it if it's still longer than the dots we would add
469         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
470         my $body = $1;
471         my $tail = $2;
472         if (length($tail) > 4) {
473                 $tail = " ...";
474                 $body =~ s/&[^;]*$//; # remove chopped character entities
475         }
476         return "$body$tail";
479 ## ----------------------------------------------------------------------
480 ## functions returning short strings
482 # CSS class for given age value (in seconds)
483 sub age_class {
484         my $age = shift;
486         if ($age < 60*60*2) {
487                 return "age0";
488         } elsif ($age < 60*60*24*2) {
489                 return "age1";
490         } else {
491                 return "age2";
492         }
495 # convert age in seconds to "nn units ago" string
496 sub age_string {
497         my $age = shift;
498         my $age_str;
500         if ($age > 60*60*24*365*2) {
501                 $age_str = (int $age/60/60/24/365);
502                 $age_str .= " years ago";
503         } elsif ($age > 60*60*24*(365/12)*2) {
504                 $age_str = int $age/60/60/24/(365/12);
505                 $age_str .= " months ago";
506         } elsif ($age > 60*60*24*7*2) {
507                 $age_str = int $age/60/60/24/7;
508                 $age_str .= " weeks ago";
509         } elsif ($age > 60*60*24*2) {
510                 $age_str = int $age/60/60/24;
511                 $age_str .= " days ago";
512         } elsif ($age > 60*60*2) {
513                 $age_str = int $age/60/60;
514                 $age_str .= " hours ago";
515         } elsif ($age > 60*2) {
516                 $age_str = int $age/60;
517                 $age_str .= " min ago";
518         } elsif ($age > 2) {
519                 $age_str = int $age;
520                 $age_str .= " sec ago";
521         } else {
522                 $age_str .= " right now";
523         }
524         return $age_str;
527 # convert file mode in octal to symbolic file mode string
528 sub mode_str {
529         my $mode = oct shift;
531         if (S_ISDIR($mode & S_IFMT)) {
532                 return 'drwxr-xr-x';
533         } elsif (S_ISLNK($mode)) {
534                 return 'lrwxrwxrwx';
535         } elsif (S_ISREG($mode)) {
536                 # git cares only about the executable bit
537                 if ($mode & S_IXUSR) {
538                         return '-rwxr-xr-x';
539                 } else {
540                         return '-rw-r--r--';
541                 };
542         } else {
543                 return '----------';
544         }
547 # convert file mode in octal to file type string
548 sub file_type {
549         my $mode = shift;
551         if ($mode !~ m/^[0-7]+$/) {
552                 return $mode;
553         } else {
554                 $mode = oct $mode;
555         }
557         if (S_ISDIR($mode & S_IFMT)) {
558                 return "directory";
559         } elsif (S_ISLNK($mode)) {
560                 return "symlink";
561         } elsif (S_ISREG($mode)) {
562                 return "file";
563         } else {
564                 return "unknown";
565         }
568 ## ----------------------------------------------------------------------
569 ## functions returning short HTML fragments, or transforming HTML fragments
570 ## which don't beling to other sections
572 # format line of commit message or tag comment
573 sub format_log_line_html {
574         my $line = shift;
576         $line = esc_html($line);
577         $line =~ s/ /&nbsp;/g;
578         if ($line =~ m/([0-9a-fA-F]{40})/) {
579                 my $hash_text = $1;
580                 if (git_get_type($hash_text) eq "commit") {
581                         my $link =
582                                 $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
583                                         -class => "text"}, $hash_text);
584                         $line =~ s/$hash_text/$link/;
585                 }
586         }
587         return $line;
590 # format marker of refs pointing to given object
591 sub format_ref_marker {
592         my ($refs, $id) = @_;
593         my $markers = '';
595         if (defined $refs->{$id}) {
596                 foreach my $ref (@{$refs->{$id}}) {
597                         my ($type, $name) = qw();
598                         # e.g. tags/v2.6.11 or heads/next
599                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
600                                 $type = $1;
601                                 $name = $2;
602                         } else {
603                                 $type = "ref";
604                                 $name = $ref;
605                         }
607                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
608                 }
609         }
611         if ($markers) {
612                 return ' <span class="refs">'. $markers . '</span>';
613         } else {
614                 return "";
615         }
618 # format, perhaps shortened and with markers, title line
619 sub format_subject_html {
620         my ($long, $short, $href, $extra) = @_;
621         $extra = '' unless defined($extra);
623         if (length($short) < length($long)) {
624                 return $cgi->a({-href => $href, -class => "list subject",
625                                 -title => $long},
626                        esc_html($short) . $extra);
627         } else {
628                 return $cgi->a({-href => $href, -class => "list subject"},
629                        esc_html($long)  . $extra);
630         }
633 sub format_diff_line {
634         my $line = shift;
635         my $char = substr($line, 0, 1);
636         my $diff_class = "";
638         chomp $line;
640         if ($char eq '+') {
641                 $diff_class = " add";
642         } elsif ($char eq "-") {
643                 $diff_class = " rem";
644         } elsif ($char eq "@") {
645                 $diff_class = " chunk_header";
646         } elsif ($char eq "\\") {
647                 $diff_class = " incomplete";
648         }
649         $line = untabify($line);
650         return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
653 ## ----------------------------------------------------------------------
654 ## git utility subroutines, invoking git commands
656 # returns path to the core git executable and the --git-dir parameter as list
657 sub git_cmd {
658         return $GIT, '--git-dir='.$git_dir;
661 # returns path to the core git executable and the --git-dir parameter as string
662 sub git_cmd_str {
663         return join(' ', git_cmd());
666 # get HEAD ref of given project as hash
667 sub git_get_head_hash {
668         my $project = shift;
669         my $o_git_dir = $git_dir;
670         my $retval = undef;
671         $git_dir = "$projectroot/$project";
672         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
673                 my $head = <$fd>;
674                 close $fd;
675                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
676                         $retval = $1;
677                 }
678         }
679         if (defined $o_git_dir) {
680                 $git_dir = $o_git_dir;
681         }
682         return $retval;
685 # get type of given object
686 sub git_get_type {
687         my $hash = shift;
689         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
690         my $type = <$fd>;
691         close $fd or return;
692         chomp $type;
693         return $type;
696 sub git_get_project_config {
697         my ($key, $type) = @_;
699         return unless ($key);
700         $key =~ s/^gitweb\.//;
701         return if ($key =~ m/\W/);
703         my @x = (git_cmd(), 'repo-config');
704         if (defined $type) { push @x, $type; }
705         push @x, "--get";
706         push @x, "gitweb.$key";
707         my $val = qx(@x);
708         chomp $val;
709         return ($val);
712 # get hash of given path at given ref
713 sub git_get_hash_by_path {
714         my $base = shift;
715         my $path = shift || return undef;
717         my $tree = $base;
719         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
720                 or die_error(undef, "Open git-ls-tree failed");
721         my $line = <$fd>;
722         close $fd or return undef;
724         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
725         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
726         return $3;
729 ## ......................................................................
730 ## git utility functions, directly accessing git repository
732 sub git_get_project_description {
733         my $path = shift;
735         open my $fd, "$projectroot/$path/description" or return undef;
736         my $descr = <$fd>;
737         close $fd;
738         chomp $descr;
739         return $descr;
742 sub git_get_project_url_list {
743         my $path = shift;
745         open my $fd, "$projectroot/$path/cloneurl" or return undef;
746         my @git_project_url_list = map { chomp; $_ } <$fd>;
747         close $fd;
749         return wantarray ? @git_project_url_list : \@git_project_url_list;
752 sub git_get_projects_list {
753         my @list;
755         if (-d $projects_list) {
756                 # search in directory
757                 my $dir = $projects_list;
758                 my $pfxlen = length("$dir");
760                 File::Find::find({
761                         follow_fast => 1, # follow symbolic links
762                         dangling_symlinks => 0, # ignore dangling symlinks, silently
763                         wanted => sub {
764                                 # skip project-list toplevel, if we get it.
765                                 return if (m!^[/.]$!);
766                                 # only directories can be git repositories
767                                 return unless (-d $_);
769                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
770                                 # we check related file in $projectroot
771                                 if (-e "$projectroot/$subdir/HEAD" && (!$export_ok ||
772                                     -e "$projectroot/$subdir/$export_ok")) {
773                                         push @list, { path => $subdir };
774                                         $File::Find::prune = 1;
775                                 }
776                         },
777                 }, "$dir");
779         } elsif (-f $projects_list) {
780                 # read from file(url-encoded):
781                 # 'git%2Fgit.git Linus+Torvalds'
782                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
783                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
784                 open my ($fd), $projects_list or return undef;
785                 while (my $line = <$fd>) {
786                         chomp $line;
787                         my ($path, $owner) = split ' ', $line;
788                         $path = unescape($path);
789                         $owner = unescape($owner);
790                         if (!defined $path) {
791                                 next;
792                         }
793                         if (-e "$projectroot/$path/HEAD" && (!$export_ok ||
794                             -e "$projectroot/$path/$export_ok")) {
795                                 my $pr = {
796                                         path => $path,
797                                         owner => decode("utf8", $owner, Encode::FB_DEFAULT),
798                                 };
799                                 push @list, $pr
800                         }
801                 }
802                 close $fd;
803         }
804         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
805         return @list;
808 sub git_get_project_owner {
809         my $project = shift;
810         my $owner;
812         return undef unless $project;
814         # read from file (url-encoded):
815         # 'git%2Fgit.git Linus+Torvalds'
816         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
817         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
818         if (-f $projects_list) {
819                 open (my $fd , $projects_list);
820                 while (my $line = <$fd>) {
821                         chomp $line;
822                         my ($pr, $ow) = split ' ', $line;
823                         $pr = unescape($pr);
824                         $ow = unescape($ow);
825                         if ($pr eq $project) {
826                                 $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
827                                 last;
828                         }
829                 }
830                 close $fd;
831         }
832         if (!defined $owner) {
833                 $owner = get_file_owner("$projectroot/$project");
834         }
836         return $owner;
839 sub git_get_references {
840         my $type = shift || "";
841         my %refs;
842         my $fd;
843         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
844         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
845         if (-f "$projectroot/$project/info/refs") {
846                 open $fd, "$projectroot/$project/info/refs"
847                         or return;
848         } else {
849                 open $fd, "-|", git_cmd(), "ls-remote", "."
850                         or return;
851         }
853         while (my $line = <$fd>) {
854                 chomp $line;
855                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
856                         if (defined $refs{$1}) {
857                                 push @{$refs{$1}}, $2;
858                         } else {
859                                 $refs{$1} = [ $2 ];
860                         }
861                 }
862         }
863         close $fd or return;
864         return \%refs;
867 sub git_get_rev_name_tags {
868         my $hash = shift || return undef;
870         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
871                 or return;
872         my $name_rev = <$fd>;
873         close $fd;
875         if ($name_rev =~ m|^$hash tags/(.*)$|) {
876                 return $1;
877         } else {
878                 # catches also '$hash undefined' output
879                 return undef;
880         }
883 ## ----------------------------------------------------------------------
884 ## parse to hash functions
886 sub parse_date {
887         my $epoch = shift;
888         my $tz = shift || "-0000";
890         my %date;
891         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
892         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
893         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
894         $date{'hour'} = $hour;
895         $date{'minute'} = $min;
896         $date{'mday'} = $mday;
897         $date{'day'} = $days[$wday];
898         $date{'month'} = $months[$mon];
899         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
900                            $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
901         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
902                              $mday, $months[$mon], $hour ,$min;
904         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
905         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
906         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
907         $date{'hour_local'} = $hour;
908         $date{'minute_local'} = $min;
909         $date{'tz_local'} = $tz;
910         return %date;
913 sub parse_tag {
914         my $tag_id = shift;
915         my %tag;
916         my @comment;
918         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
919         $tag{'id'} = $tag_id;
920         while (my $line = <$fd>) {
921                 chomp $line;
922                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
923                         $tag{'object'} = $1;
924                 } elsif ($line =~ m/^type (.+)$/) {
925                         $tag{'type'} = $1;
926                 } elsif ($line =~ m/^tag (.+)$/) {
927                         $tag{'name'} = $1;
928                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
929                         $tag{'author'} = $1;
930                         $tag{'epoch'} = $2;
931                         $tag{'tz'} = $3;
932                 } elsif ($line =~ m/--BEGIN/) {
933                         push @comment, $line;
934                         last;
935                 } elsif ($line eq "") {
936                         last;
937                 }
938         }
939         push @comment, <$fd>;
940         $tag{'comment'} = \@comment;
941         close $fd or return;
942         if (!defined $tag{'name'}) {
943                 return
944         };
945         return %tag
948 sub parse_commit {
949         my $commit_id = shift;
950         my $commit_text = shift;
952         my @commit_lines;
953         my %co;
955         if (defined $commit_text) {
956                 @commit_lines = @$commit_text;
957         } else {
958                 $/ = "\0";
959                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
960                         or return;
961                 @commit_lines = split '\n', <$fd>;
962                 close $fd or return;
963                 $/ = "\n";
964                 pop @commit_lines;
965         }
966         my $header = shift @commit_lines;
967         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
968                 return;
969         }
970         ($co{'id'}, my @parents) = split ' ', $header;
971         $co{'parents'} = \@parents;
972         $co{'parent'} = $parents[0];
973         while (my $line = shift @commit_lines) {
974                 last if $line eq "\n";
975                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
976                         $co{'tree'} = $1;
977                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
978                         $co{'author'} = $1;
979                         $co{'author_epoch'} = $2;
980                         $co{'author_tz'} = $3;
981                         if ($co{'author'} =~ m/^([^<]+) </) {
982                                 $co{'author_name'} = $1;
983                         } else {
984                                 $co{'author_name'} = $co{'author'};
985                         }
986                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
987                         $co{'committer'} = $1;
988                         $co{'committer_epoch'} = $2;
989                         $co{'committer_tz'} = $3;
990                         $co{'committer_name'} = $co{'committer'};
991                         $co{'committer_name'} =~ s/ <.*//;
992                 }
993         }
994         if (!defined $co{'tree'}) {
995                 return;
996         };
998         foreach my $title (@commit_lines) {
999                 $title =~ s/^    //;
1000                 if ($title ne "") {
1001                         $co{'title'} = chop_str($title, 80, 5);
1002                         # remove leading stuff of merges to make the interesting part visible
1003                         if (length($title) > 50) {
1004                                 $title =~ s/^Automatic //;
1005                                 $title =~ s/^merge (of|with) /Merge ... /i;
1006                                 if (length($title) > 50) {
1007                                         $title =~ s/(http|rsync):\/\///;
1008                                 }
1009                                 if (length($title) > 50) {
1010                                         $title =~ s/(master|www|rsync)\.//;
1011                                 }
1012                                 if (length($title) > 50) {
1013                                         $title =~ s/kernel.org:?//;
1014                                 }
1015                                 if (length($title) > 50) {
1016                                         $title =~ s/\/pub\/scm//;
1017                                 }
1018                         }
1019                         $co{'title_short'} = chop_str($title, 50, 5);
1020                         last;
1021                 }
1022         }
1023         # remove added spaces
1024         foreach my $line (@commit_lines) {
1025                 $line =~ s/^    //;
1026         }
1027         $co{'comment'} = \@commit_lines;
1029         my $age = time - $co{'committer_epoch'};
1030         $co{'age'} = $age;
1031         $co{'age_string'} = age_string($age);
1032         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1033         if ($age > 60*60*24*7*2) {
1034                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1035                 $co{'age_string_age'} = $co{'age_string'};
1036         } else {
1037                 $co{'age_string_date'} = $co{'age_string'};
1038                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1039         }
1040         return %co;
1043 # parse ref from ref_file, given by ref_id, with given type
1044 sub parse_ref {
1045         my $ref_file = shift;
1046         my $ref_id = shift;
1047         my $type = shift || git_get_type($ref_id);
1048         my %ref_item;
1050         $ref_item{'type'} = $type;
1051         $ref_item{'id'} = $ref_id;
1052         $ref_item{'epoch'} = 0;
1053         $ref_item{'age'} = "unknown";
1054         if ($type eq "tag") {
1055                 my %tag = parse_tag($ref_id);
1056                 $ref_item{'comment'} = $tag{'comment'};
1057                 if ($tag{'type'} eq "commit") {
1058                         my %co = parse_commit($tag{'object'});
1059                         $ref_item{'epoch'} = $co{'committer_epoch'};
1060                         $ref_item{'age'} = $co{'age_string'};
1061                 } elsif (defined($tag{'epoch'})) {
1062                         my $age = time - $tag{'epoch'};
1063                         $ref_item{'epoch'} = $tag{'epoch'};
1064                         $ref_item{'age'} = age_string($age);
1065                 }
1066                 $ref_item{'reftype'} = $tag{'type'};
1067                 $ref_item{'name'} = $tag{'name'};
1068                 $ref_item{'refid'} = $tag{'object'};
1069         } elsif ($type eq "commit"){
1070                 my %co = parse_commit($ref_id);
1071                 $ref_item{'reftype'} = "commit";
1072                 $ref_item{'name'} = $ref_file;
1073                 $ref_item{'title'} = $co{'title'};
1074                 $ref_item{'refid'} = $ref_id;
1075                 $ref_item{'epoch'} = $co{'committer_epoch'};
1076                 $ref_item{'age'} = $co{'age_string'};
1077         } else {
1078                 $ref_item{'reftype'} = $type;
1079                 $ref_item{'name'} = $ref_file;
1080                 $ref_item{'refid'} = $ref_id;
1081         }
1083         return %ref_item;
1086 # parse line of git-diff-tree "raw" output
1087 sub parse_difftree_raw_line {
1088         my $line = shift;
1089         my %res;
1091         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1092         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1093         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1094                 $res{'from_mode'} = $1;
1095                 $res{'to_mode'} = $2;
1096                 $res{'from_id'} = $3;
1097                 $res{'to_id'} = $4;
1098                 $res{'status'} = $5;
1099                 $res{'similarity'} = $6;
1100                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1101                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1102                 } else {
1103                         $res{'file'} = unquote($7);
1104                 }
1105         }
1106         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1107         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1108                 $res{'commit'} = $1;
1109         }
1111         return wantarray ? %res : \%res;
1114 # parse line of git-ls-tree output
1115 sub parse_ls_tree_line ($;%) {
1116         my $line = shift;
1117         my %opts = @_;
1118         my %res;
1120         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1121         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1123         $res{'mode'} = $1;
1124         $res{'type'} = $2;
1125         $res{'hash'} = $3;
1126         if ($opts{'-z'}) {
1127                 $res{'name'} = $4;
1128         } else {
1129                 $res{'name'} = unquote($4);
1130         }
1132         return wantarray ? %res : \%res;
1135 ## ......................................................................
1136 ## parse to array of hashes functions
1138 sub git_get_refs_list {
1139         my $ref_dir = shift;
1140         my @reflist;
1142         my @refs;
1143         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1144                 or return;
1145         while (my $line = <$fd>) {
1146                 chomp $line;
1147                 if ($line =~ m/^([0-9a-fA-F]{40})\t$ref_dir\/?([^\^]+)$/) {
1148                         push @refs, { hash => $1, name => $2 };
1149                 } elsif ($line =~ m/^[0-9a-fA-F]{40}\t$ref_dir\/?(.*)\^\{\}$/ &&
1150                          $1 eq $refs[-1]{'name'}) {
1151                         # most likely a tag is followed by its peeled
1152                         # (deref) one, and when that happens we know the
1153                         # previous one was of type 'tag'.
1154                         $refs[-1]{'type'} = "tag";
1155                 }
1156         }
1157         close $fd;
1159         foreach my $ref (@refs) {
1160                 my $ref_file = $ref->{'name'};
1161                 my $ref_id   = $ref->{'hash'};
1163                 my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1164                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
1166                 push @reflist, \%ref_item;
1167         }
1168         # sort refs by age
1169         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1170         return \@reflist;
1173 ## ----------------------------------------------------------------------
1174 ## filesystem-related functions
1176 sub get_file_owner {
1177         my $path = shift;
1179         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1180         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1181         if (!defined $gcos) {
1182                 return undef;
1183         }
1184         my $owner = $gcos;
1185         $owner =~ s/[,;].*$//;
1186         return decode("utf8", $owner, Encode::FB_DEFAULT);
1189 ## ......................................................................
1190 ## mimetype related functions
1192 sub mimetype_guess_file {
1193         my $filename = shift;
1194         my $mimemap = shift;
1195         -r $mimemap or return undef;
1197         my %mimemap;
1198         open(MIME, $mimemap) or return undef;
1199         while (<MIME>) {
1200                 next if m/^#/; # skip comments
1201                 my ($mime, $exts) = split(/\t+/);
1202                 if (defined $exts) {
1203                         my @exts = split(/\s+/, $exts);
1204                         foreach my $ext (@exts) {
1205                                 $mimemap{$ext} = $mime;
1206                         }
1207                 }
1208         }
1209         close(MIME);
1211         $filename =~ /\.([^.]*)$/;
1212         return $mimemap{$1};
1215 sub mimetype_guess {
1216         my $filename = shift;
1217         my $mime;
1218         $filename =~ /\./ or return undef;
1220         if ($mimetypes_file) {
1221                 my $file = $mimetypes_file;
1222                 if ($file !~ m!^/!) { # if it is relative path
1223                         # it is relative to project
1224                         $file = "$projectroot/$project/$file";
1225                 }
1226                 $mime = mimetype_guess_file($filename, $file);
1227         }
1228         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1229         return $mime;
1232 sub blob_mimetype {
1233         my $fd = shift;
1234         my $filename = shift;
1236         if ($filename) {
1237                 my $mime = mimetype_guess($filename);
1238                 $mime and return $mime;
1239         }
1241         # just in case
1242         return $default_blob_plain_mimetype unless $fd;
1244         if (-T $fd) {
1245                 return 'text/plain' .
1246                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1247         } elsif (! $filename) {
1248                 return 'application/octet-stream';
1249         } elsif ($filename =~ m/\.png$/i) {
1250                 return 'image/png';
1251         } elsif ($filename =~ m/\.gif$/i) {
1252                 return 'image/gif';
1253         } elsif ($filename =~ m/\.jpe?g$/i) {
1254                 return 'image/jpeg';
1255         } else {
1256                 return 'application/octet-stream';
1257         }
1260 ## ======================================================================
1261 ## functions printing HTML: header, footer, error page
1263 sub git_header_html {
1264         my $status = shift || "200 OK";
1265         my $expires = shift;
1267         my $title = "$site_name git";
1268         if (defined $project) {
1269                 $title .= " - $project";
1270                 if (defined $action) {
1271                         $title .= "/$action";
1272                         if (defined $file_name) {
1273                                 $title .= " - $file_name";
1274                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1275                                         $title .= "/";
1276                                 }
1277                         }
1278                 }
1279         }
1280         my $content_type;
1281         # require explicit support from the UA if we are to send the page as
1282         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1283         # we have to do this because MSIE sometimes globs '*/*', pretending to
1284         # support xhtml+xml but choking when it gets what it asked for.
1285         if (defined $cgi->http('HTTP_ACCEPT') &&
1286             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1287             $cgi->Accept('application/xhtml+xml') != 0) {
1288                 $content_type = 'application/xhtml+xml';
1289         } else {
1290                 $content_type = 'text/html';
1291         }
1292         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1293                            -status=> $status, -expires => $expires);
1294         print <<EOF;
1295 <?xml version="1.0" encoding="utf-8"?>
1296 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1297 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1298 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1299 <!-- git core binaries version $git_version -->
1300 <head>
1301 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1302 <meta name="generator" content="gitweb/$version git/$git_version"/>
1303 <meta name="robots" content="index, nofollow"/>
1304 <title>$title</title>
1305 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1306 EOF
1307         if (defined $project) {
1308                 printf('<link rel="alternate" title="%s log" '.
1309                        'href="%s" type="application/rss+xml"/>'."\n",
1310                        esc_param($project), href(action=>"rss"));
1311         } else {
1312                 printf('<link rel="alternate" title="%s projects list" '.
1313                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1314                        $site_name, href(project=>undef, action=>"project_index"));
1315                 printf('<link rel="alternate" title="%s projects logs" '.
1316                        'href="%s" type="text/x-opml"/>'."\n",
1317                        $site_name, href(project=>undef, action=>"opml"));
1318         }
1319         if (defined $favicon) {
1320                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1321         }
1323         print "</head>\n" .
1324               "<body>\n" .
1325               "<div class=\"page_header\">\n" .
1326               "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1327               "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1328               "</a>\n";
1329         print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1330         if (defined $project) {
1331                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1332                 if (defined $action) {
1333                         print " / $action";
1334                 }
1335                 print "\n";
1336                 if (!defined $searchtext) {
1337                         $searchtext = "";
1338                 }
1339                 my $search_hash;
1340                 if (defined $hash_base) {
1341                         $search_hash = $hash_base;
1342                 } elsif (defined $hash) {
1343                         $search_hash = $hash;
1344                 } else {
1345                         $search_hash = "HEAD";
1346                 }
1347                 $cgi->param("a", "search");
1348                 $cgi->param("h", $search_hash);
1349                 print $cgi->startform(-method => "get", -action => $my_uri) .
1350                       "<div class=\"search\">\n" .
1351                       $cgi->hidden(-name => "p") . "\n" .
1352                       $cgi->hidden(-name => "a") . "\n" .
1353                       $cgi->hidden(-name => "h") . "\n" .
1354                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1355                       "</div>" .
1356                       $cgi->end_form() . "\n";
1357         }
1358         print "</div>\n";
1361 sub git_footer_html {
1362         print "<div class=\"page_footer\">\n";
1363         if (defined $project) {
1364                 my $descr = git_get_project_description($project);
1365                 if (defined $descr) {
1366                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1367                 }
1368                 print $cgi->a({-href => href(action=>"rss"),
1369                               -class => "rss_logo"}, "RSS") . "\n";
1370         } else {
1371                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1372                               -class => "rss_logo"}, "OPML") . " ";
1373                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1374                               -class => "rss_logo"}, "TXT") . "\n";
1375         }
1376         print "</div>\n" .
1377               "</body>\n" .
1378               "</html>";
1381 sub die_error {
1382         my $status = shift || "403 Forbidden";
1383         my $error = shift || "Malformed query, file missing or permission denied";
1385         git_header_html($status);
1386         print <<EOF;
1387 <div class="page_body">
1388 <br /><br />
1389 $status - $error
1390 <br />
1391 </div>
1392 EOF
1393         git_footer_html();
1394         exit;
1397 ## ----------------------------------------------------------------------
1398 ## functions printing or outputting HTML: navigation
1400 sub git_print_page_nav {
1401         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1402         $extra = '' if !defined $extra; # pager or formats
1404         my @navs = qw(summary shortlog log commit commitdiff tree);
1405         if ($suppress) {
1406                 @navs = grep { $_ ne $suppress } @navs;
1407         }
1409         my %arg = map { $_ => {action=>$_} } @navs;
1410         if (defined $head) {
1411                 for (qw(commit commitdiff)) {
1412                         $arg{$_}{hash} = $head;
1413                 }
1414                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1415                         for (qw(shortlog log)) {
1416                                 $arg{$_}{hash} = $head;
1417                         }
1418                 }
1419         }
1420         $arg{tree}{hash} = $treehead if defined $treehead;
1421         $arg{tree}{hash_base} = $treebase if defined $treebase;
1423         print "<div class=\"page_nav\">\n" .
1424                 (join " | ",
1425                  map { $_ eq $current ?
1426                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1427                  } @navs);
1428         print "<br/>\n$extra<br/>\n" .
1429               "</div>\n";
1432 sub format_paging_nav {
1433         my ($action, $hash, $head, $page, $nrevs) = @_;
1434         my $paging_nav;
1437         if ($hash ne $head || $page) {
1438                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1439         } else {
1440                 $paging_nav .= "HEAD";
1441         }
1443         if ($page > 0) {
1444                 $paging_nav .= " &sdot; " .
1445                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1446                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1447         } else {
1448                 $paging_nav .= " &sdot; prev";
1449         }
1451         if ($nrevs >= (100 * ($page+1)-1)) {
1452                 $paging_nav .= " &sdot; " .
1453                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1454                                  -accesskey => "n", -title => "Alt-n"}, "next");
1455         } else {
1456                 $paging_nav .= " &sdot; next";
1457         }
1459         return $paging_nav;
1462 ## ......................................................................
1463 ## functions printing or outputting HTML: div
1465 sub git_print_header_div {
1466         my ($action, $title, $hash, $hash_base) = @_;
1467         my %args = ();
1469         $args{action} = $action;
1470         $args{hash} = $hash if $hash;
1471         $args{hash_base} = $hash_base if $hash_base;
1473         print "<div class=\"header\">\n" .
1474               $cgi->a({-href => href(%args), -class => "title"},
1475               $title ? $title : $action) .
1476               "\n</div>\n";
1479 #sub git_print_authorship (\%) {
1480 sub git_print_authorship {
1481         my $co = shift;
1483         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1484         print "<div class=\"author_date\">" .
1485               esc_html($co->{'author_name'}) .
1486               " [$ad{'rfc2822'}";
1487         if ($ad{'hour_local'} < 6) {
1488                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1489                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1490         } else {
1491                 printf(" (%02d:%02d %s)",
1492                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1493         }
1494         print "]</div>\n";
1497 sub git_print_page_path {
1498         my $name = shift;
1499         my $type = shift;
1500         my $hb = shift;
1502         if (!defined $name) {
1503                 print "<div class=\"page_path\">/</div>\n";
1504         } else {
1505                 my @dirname = split '/', $name;
1506                 my $basename = pop @dirname;
1507                 my $fullname = '';
1509                 print "<div class=\"page_path\">";
1510                 foreach my $dir (@dirname) {
1511                         $fullname .= $dir . '/';
1512                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1513                                                      hash_base=>$hb),
1514                                       -title => $fullname}, esc_html($dir));
1515                         print "/";
1516                 }
1517                 if (defined $type && $type eq 'blob') {
1518                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1519                                                      hash_base=>$hb),
1520                                       -title => $name}, esc_html($basename));
1521                 } elsif (defined $type && $type eq 'tree') {
1522                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1523                                                      hash_base=>$hb),
1524                                       -title => $name}, esc_html($basename));
1525                         print "/";
1526                 } else {
1527                         print esc_html($basename);
1528                 }
1529                 print "<br/></div>\n";
1530         }
1533 # sub git_print_log (\@;%) {
1534 sub git_print_log ($;%) {
1535         my $log = shift;
1536         my %opts = @_;
1538         if ($opts{'-remove_title'}) {
1539                 # remove title, i.e. first line of log
1540                 shift @$log;
1541         }
1542         # remove leading empty lines
1543         while (defined $log->[0] && $log->[0] eq "") {
1544                 shift @$log;
1545         }
1547         # print log
1548         my $signoff = 0;
1549         my $empty = 0;
1550         foreach my $line (@$log) {
1551                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1552                         $signoff = 1;
1553                         $empty = 0;
1554                         if (! $opts{'-remove_signoff'}) {
1555                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1556                                 next;
1557                         } else {
1558                                 # remove signoff lines
1559                                 next;
1560                         }
1561                 } else {
1562                         $signoff = 0;
1563                 }
1565                 # print only one empty line
1566                 # do not print empty line after signoff
1567                 if ($line eq "") {
1568                         next if ($empty || $signoff);
1569                         $empty = 1;
1570                 } else {
1571                         $empty = 0;
1572                 }
1574                 print format_log_line_html($line) . "<br/>\n";
1575         }
1577         if ($opts{'-final_empty_line'}) {
1578                 # end with single empty line
1579                 print "<br/>\n" unless $empty;
1580         }
1583 sub git_print_simplified_log {
1584         my $log = shift;
1585         my $remove_title = shift;
1587         git_print_log($log,
1588                 -final_empty_line=> 1,
1589                 -remove_title => $remove_title);
1592 # print tree entry (row of git_tree), but without encompassing <tr> element
1593 sub git_print_tree_entry {
1594         my ($t, $basedir, $hash_base, $have_blame) = @_;
1596         my %base_key = ();
1597         $base_key{hash_base} = $hash_base if defined $hash_base;
1599         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1600         if ($t->{'type'} eq "blob") {
1601                 print "<td class=\"list\">" .
1602                       $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1603                                              file_name=>"$basedir$t->{'name'}", %base_key),
1604                               -class => "list"}, esc_html($t->{'name'})) .
1605                       "</td>\n" .
1606                       "<td class=\"link\">" .
1607                       $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1608                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1609                               "blob");
1610                 if ($have_blame) {
1611                         print " | " .
1612                                 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1613                                                        file_name=>"$basedir$t->{'name'}", %base_key)},
1614                                         "blame");
1615                 }
1616                 if (defined $hash_base) {
1617                         print " | " .
1618                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1619                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1620                                       "history");
1621                 }
1622                 print " | " .
1623                       $cgi->a({-href => href(action=>"blob_plain",
1624                                              hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1625                               "raw") .
1626                       "</td>\n";
1628         } elsif ($t->{'type'} eq "tree") {
1629                 print "<td class=\"list\">" .
1630                       $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1631                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1632                               esc_html($t->{'name'})) .
1633                       "</td>\n" .
1634                       "<td class=\"link\">" .
1635                       $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1636                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1637                               "tree");
1638                 if (defined $hash_base) {
1639                         print " | " .
1640                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1641                                                      file_name=>"$basedir$t->{'name'}")},
1642                                       "history");
1643                 }
1644                 print "</td>\n";
1645         }
1648 ## ......................................................................
1649 ## functions printing large fragments of HTML
1651 sub git_difftree_body {
1652         my ($difftree, $hash, $parent) = @_;
1654         print "<div class=\"list_head\">\n";
1655         if ($#{$difftree} > 10) {
1656                 print(($#{$difftree} + 1) . " files changed:\n");
1657         }
1658         print "</div>\n";
1660         print "<table class=\"diff_tree\">\n";
1661         my $alternate = 0;
1662         my $patchno = 0;
1663         foreach my $line (@{$difftree}) {
1664                 my %diff = parse_difftree_raw_line($line);
1666                 if ($alternate) {
1667                         print "<tr class=\"dark\">\n";
1668                 } else {
1669                         print "<tr class=\"light\">\n";
1670                 }
1671                 $alternate ^= 1;
1673                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1674                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1675                 if ($diff{'to_mode'} ne ('0' x 6)) {
1676                         $to_mode_oct = oct $diff{'to_mode'};
1677                         if (S_ISREG($to_mode_oct)) { # only for regular file
1678                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1679                         }
1680                         $to_file_type = file_type($diff{'to_mode'});
1681                 }
1682                 if ($diff{'from_mode'} ne ('0' x 6)) {
1683                         $from_mode_oct = oct $diff{'from_mode'};
1684                         if (S_ISREG($to_mode_oct)) { # only for regular file
1685                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1686                         }
1687                         $from_file_type = file_type($diff{'from_mode'});
1688                 }
1690                 if ($diff{'status'} eq "A") { # created
1691                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1692                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1693                         $mode_chng   .= "]</span>";
1694                         print "<td>" .
1695                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1696                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1697                                       -class => "list"}, esc_html($diff{'file'})) .
1698                               "</td>\n" .
1699                               "<td>$mode_chng</td>\n" .
1700                               "<td class=\"link\">" .
1701                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1702                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1703                                       "blob");
1704                         if ($action eq 'commitdiff') {
1705                                 # link to patch
1706                                 $patchno++;
1707                                 print " | " .
1708                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1709                         }
1710                         print "</td>\n";
1712                 } elsif ($diff{'status'} eq "D") { # deleted
1713                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1714                         print "<td>" .
1715                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1716                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1717                                        -class => "list"}, esc_html($diff{'file'})) .
1718                               "</td>\n" .
1719                               "<td>$mode_chng</td>\n" .
1720                               "<td class=\"link\">" .
1721                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1722                                                      hash_base=>$parent, file_name=>$diff{'file'})},
1723                                       "blob") .
1724                               " | ";
1725                         if ($action eq 'commitdiff') {
1726                                 # link to patch
1727                                 $patchno++;
1728                                 print " | " .
1729                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1730                         }
1731                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1732                                                      file_name=>$diff{'file'})},
1733                                       "history") .
1734                               "</td>\n";
1736                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1737                         my $mode_chnge = "";
1738                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1739                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1740                                 if ($from_file_type != $to_file_type) {
1741                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1742                                 }
1743                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1744                                         if ($from_mode_str && $to_mode_str) {
1745                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1746                                         } elsif ($to_mode_str) {
1747                                                 $mode_chnge .= " mode: $to_mode_str";
1748                                         }
1749                                 }
1750                                 $mode_chnge .= "]</span>\n";
1751                         }
1752                         print "<td>";
1753                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1754                                 print $cgi->a({-href => href(action=>"blobdiff",
1755                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1756                                                              hash_base=>$hash, hash_parent_base=>$parent,
1757                                                              file_name=>$diff{'file'}),
1758                                               -class => "list"}, esc_html($diff{'file'}));
1759                         } else { # only mode changed
1760                                 print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1761                                                              hash_base=>$hash, file_name=>$diff{'file'}),
1762                                               -class => "list"}, esc_html($diff{'file'}));
1763                         }
1764                         print "</td>\n" .
1765                               "<td>$mode_chnge</td>\n" .
1766                               "<td class=\"link\">" .
1767                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1768                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1769                                       "blob");
1770                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1771                                 if ($action eq 'commitdiff') {
1772                                         # link to patch
1773                                         $patchno++;
1774                                         print " | " .
1775                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1776                                 } else {
1777                                         print " | " .
1778                                                 $cgi->a({-href => href(action=>"blobdiff",
1779                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1780                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1781                                                                        file_name=>$diff{'file'})},
1782                                                         "diff");
1783                                 }
1784                         }
1785                         print " | " .
1786                                 $cgi->a({-href => href(action=>"history",
1787                                                        hash_base=>$hash, file_name=>$diff{'file'})},
1788                                         "history");
1789                         print "</td>\n";
1791                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1792                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1793                         my $nstatus = $status_name{$diff{'status'}};
1794                         my $mode_chng = "";
1795                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1796                                 # mode also for directories, so we cannot use $to_mode_str
1797                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1798                         }
1799                         print "<td>" .
1800                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1801                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1802                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1803                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1804                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1805                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1806                                       -class => "list"}, esc_html($diff{'from_file'})) .
1807                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1808                               "<td class=\"link\">" .
1809                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1810                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1811                                       "blob");
1812                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1813                                 if ($action eq 'commitdiff') {
1814                                         # link to patch
1815                                         $patchno++;
1816                                         print " | " .
1817                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1818                                 } else {
1819                                         print " | " .
1820                                                 $cgi->a({-href => href(action=>"blobdiff",
1821                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1822                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1823                                                                        file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1824                                                         "diff");
1825                                 }
1826                         }
1827                         print "</td>\n";
1829                 } # we should not encounter Unmerged (U) or Unknown (X) status
1830                 print "</tr>\n";
1831         }
1832         print "</table>\n";
1835 sub git_patchset_body {
1836         my ($fd, $difftree, $hash, $hash_parent) = @_;
1838         my $patch_idx = 0;
1839         my $in_header = 0;
1840         my $patch_found = 0;
1841         my $diffinfo;
1843         print "<div class=\"patchset\">\n";
1845         LINE:
1846         while (my $patch_line = <$fd>) {
1847                 chomp $patch_line;
1849                 if ($patch_line =~ m/^diff /) { # "git diff" header
1850                         # beginning of patch (in patchset)
1851                         if ($patch_found) {
1852                                 # close previous patch
1853                                 print "</div>\n"; # class="patch"
1854                         } else {
1855                                 # first patch in patchset
1856                                 $patch_found = 1;
1857                         }
1858                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1860                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1861                                 $diffinfo = $difftree->[$patch_idx];
1862                         } else {
1863                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1864                         }
1865                         $patch_idx++;
1867                         # for now, no extended header, hence we skip empty patches
1868                         # companion to  next LINE if $in_header;
1869                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1870                                 $in_header = 1;
1871                                 next LINE;
1872                         }
1874                         if ($diffinfo->{'status'} eq "A") { # added
1875                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1876                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1877                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1878                                               $diffinfo->{'to_id'}) . "(new)" .
1879                                       "</div>\n"; # class="diff_info"
1881                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1882                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1883                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1884                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1885                                               $diffinfo->{'from_id'}) . "(deleted)" .
1886                                       "</div>\n"; # class="diff_info"
1888                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1889                                  $diffinfo->{'status'} eq "C" || # copied
1890                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1891                                 print "<div class=\"diff_info\">" .
1892                                       file_type($diffinfo->{'from_mode'}) . ":" .
1893                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1894                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1895                                               $diffinfo->{'from_id'}) .
1896                                       " -> " .
1897                                       file_type($diffinfo->{'to_mode'}) . ":" .
1898                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1899                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1900                                               $diffinfo->{'to_id'});
1901                                 print "</div>\n"; # class="diff_info"
1903                         } else { # modified, mode changed, ...
1904                                 print "<div class=\"diff_info\">" .
1905                                       file_type($diffinfo->{'from_mode'}) . ":" .
1906                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1907                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1908                                               $diffinfo->{'from_id'}) .
1909                                       " -> " .
1910                                       file_type($diffinfo->{'to_mode'}) . ":" .
1911                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1912                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1913                                               $diffinfo->{'to_id'});
1914                                 print "</div>\n"; # class="diff_info"
1915                         }
1917                         #print "<div class=\"diff extended_header\">\n";
1918                         $in_header = 1;
1919                         next LINE;
1920                 } # start of patch in patchset
1923                 if ($in_header && $patch_line =~ m/^---/) {
1924                         #print "</div>\n"; # class="diff extended_header"
1925                         $in_header = 0;
1927                         my $file = $diffinfo->{'from_file'};
1928                         $file  ||= $diffinfo->{'file'};
1929                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1930                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
1931                                         -class => "list"}, esc_html($file));
1932                         $patch_line =~ s|a/.*$|a/$file|g;
1933                         print "<div class=\"diff from_file\">$patch_line</div>\n";
1935                         $patch_line = <$fd>;
1936                         chomp $patch_line;
1938                         #$patch_line =~ m/^+++/;
1939                         $file    = $diffinfo->{'to_file'};
1940                         $file  ||= $diffinfo->{'file'};
1941                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1942                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
1943                                         -class => "list"}, esc_html($file));
1944                         $patch_line =~ s|b/.*|b/$file|g;
1945                         print "<div class=\"diff to_file\">$patch_line</div>\n";
1947                         next LINE;
1948                 }
1949                 next LINE if $in_header;
1951                 print format_diff_line($patch_line);
1952         }
1953         print "</div>\n" if $patch_found; # class="patch"
1955         print "</div>\n"; # class="patchset"
1958 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1960 sub git_shortlog_body {
1961         # uses global variable $project
1962         my ($revlist, $from, $to, $refs, $extra) = @_;
1964         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
1965         my $have_snapshot = (defined $ctype && defined $suffix);
1967         $from = 0 unless defined $from;
1968         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1970         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1971         my $alternate = 0;
1972         for (my $i = $from; $i <= $to; $i++) {
1973                 my $commit = $revlist->[$i];
1974                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1975                 my $ref = format_ref_marker($refs, $commit);
1976                 my %co = parse_commit($commit);
1977                 if ($alternate) {
1978                         print "<tr class=\"dark\">\n";
1979                 } else {
1980                         print "<tr class=\"light\">\n";
1981                 }
1982                 $alternate ^= 1;
1983                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1984                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1985                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1986                       "<td>";
1987                 print format_subject_html($co{'title'}, $co{'title_short'},
1988                                           href(action=>"commit", hash=>$commit), $ref);
1989                 print "</td>\n" .
1990                       "<td class=\"link\">" .
1991                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1992                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
1993                 if ($have_snapshot) {
1994                         print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
1995                 }
1996                 print "</td>\n" .
1997                       "</tr>\n";
1998         }
1999         if (defined $extra) {
2000                 print "<tr>\n" .
2001                       "<td colspan=\"4\">$extra</td>\n" .
2002                       "</tr>\n";
2003         }
2004         print "</table>\n";
2007 sub git_history_body {
2008         # Warning: assumes constant type (blob or tree) during history
2009         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2011         $from = 0 unless defined $from;
2012         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2014         print "<table class=\"history\" cellspacing=\"0\">\n";
2015         my $alternate = 0;
2016         for (my $i = $from; $i <= $to; $i++) {
2017                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2018                         next;
2019                 }
2021                 my $commit = $1;
2022                 my %co = parse_commit($commit);
2023                 if (!%co) {
2024                         next;
2025                 }
2027                 my $ref = format_ref_marker($refs, $commit);
2029                 if ($alternate) {
2030                         print "<tr class=\"dark\">\n";
2031                 } else {
2032                         print "<tr class=\"light\">\n";
2033                 }
2034                 $alternate ^= 1;
2035                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2036                       # shortlog uses      chop_str($co{'author_name'}, 10)
2037                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2038                       "<td>";
2039                 # originally git_history used chop_str($co{'title'}, 50)
2040                 print format_subject_html($co{'title'}, $co{'title_short'},
2041                                           href(action=>"commit", hash=>$commit), $ref);
2042                 print "</td>\n" .
2043                       "<td class=\"link\">" .
2044                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2045                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2046                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
2048                 if ($ftype eq 'blob') {
2049                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2050                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2051                         if (defined $blob_current && defined $blob_parent &&
2052                                         $blob_current ne $blob_parent) {
2053                                 print " | " .
2054                                         $cgi->a({-href => href(action=>"blobdiff",
2055                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2056                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2057                                                                file_name=>$file_name)},
2058                                                 "diff to current");
2059                         }
2060                 }
2061                 print "</td>\n" .
2062                       "</tr>\n";
2063         }
2064         if (defined $extra) {
2065                 print "<tr>\n" .
2066                       "<td colspan=\"4\">$extra</td>\n" .
2067                       "</tr>\n";
2068         }
2069         print "</table>\n";
2072 sub git_tags_body {
2073         # uses global variable $project
2074         my ($taglist, $from, $to, $extra) = @_;
2075         $from = 0 unless defined $from;
2076         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2078         print "<table class=\"tags\" cellspacing=\"0\">\n";
2079         my $alternate = 0;
2080         for (my $i = $from; $i <= $to; $i++) {
2081                 my $entry = $taglist->[$i];
2082                 my %tag = %$entry;
2083                 my $comment_lines = $tag{'comment'};
2084                 my $comment = shift @$comment_lines;
2085                 my $comment_short;
2086                 if (defined $comment) {
2087                         $comment_short = chop_str($comment, 30, 5);
2088                 }
2089                 if ($alternate) {
2090                         print "<tr class=\"dark\">\n";
2091                 } else {
2092                         print "<tr class=\"light\">\n";
2093                 }
2094                 $alternate ^= 1;
2095                 print "<td><i>$tag{'age'}</i></td>\n" .
2096                       "<td>" .
2097                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2098                                -class => "list name"}, esc_html($tag{'name'})) .
2099                       "</td>\n" .
2100                       "<td>";
2101                 if (defined $comment) {
2102                         print format_subject_html($comment, $comment_short,
2103                                                   href(action=>"tag", hash=>$tag{'id'}));
2104                 }
2105                 print "</td>\n" .
2106                       "<td class=\"selflink\">";
2107                 if ($tag{'type'} eq "tag") {
2108                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2109                 } else {
2110                         print "&nbsp;";
2111                 }
2112                 print "</td>\n" .
2113                       "<td class=\"link\">" . " | " .
2114                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2115                 if ($tag{'reftype'} eq "commit") {
2116                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2117                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2118                 } elsif ($tag{'reftype'} eq "blob") {
2119                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2120                 }
2121                 print "</td>\n" .
2122                       "</tr>";
2123         }
2124         if (defined $extra) {
2125                 print "<tr>\n" .
2126                       "<td colspan=\"5\">$extra</td>\n" .
2127                       "</tr>\n";
2128         }
2129         print "</table>\n";
2132 sub git_heads_body {
2133         # uses global variable $project
2134         my ($taglist, $head, $from, $to, $extra) = @_;
2135         $from = 0 unless defined $from;
2136         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2138         print "<table class=\"heads\" cellspacing=\"0\">\n";
2139         my $alternate = 0;
2140         for (my $i = $from; $i <= $to; $i++) {
2141                 my $entry = $taglist->[$i];
2142                 my %tag = %$entry;
2143                 my $curr = $tag{'id'} eq $head;
2144                 if ($alternate) {
2145                         print "<tr class=\"dark\">\n";
2146                 } else {
2147                         print "<tr class=\"light\">\n";
2148                 }
2149                 $alternate ^= 1;
2150                 print "<td><i>$tag{'age'}</i></td>\n" .
2151                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2152                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2153                                -class => "list name"},esc_html($tag{'name'})) .
2154                       "</td>\n" .
2155                       "<td class=\"link\">" .
2156                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2157                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
2158                       "</td>\n" .
2159                       "</tr>";
2160         }
2161         if (defined $extra) {
2162                 print "<tr>\n" .
2163                       "<td colspan=\"3\">$extra</td>\n" .
2164                       "</tr>\n";
2165         }
2166         print "</table>\n";
2169 ## ======================================================================
2170 ## ======================================================================
2171 ## actions
2173 sub git_project_list {
2174         my $order = $cgi->param('o');
2175         if (defined $order && $order !~ m/project|descr|owner|age/) {
2176                 die_error(undef, "Unknown order parameter");
2177         }
2179         my @list = git_get_projects_list();
2180         my @projects;
2181         if (!@list) {
2182                 die_error(undef, "No projects found");
2183         }
2184         foreach my $pr (@list) {
2185                 my $head = git_get_head_hash($pr->{'path'});
2186                 if (!defined $head) {
2187                         next;
2188                 }
2189                 $git_dir = "$projectroot/$pr->{'path'}";
2190                 my %co = parse_commit($head);
2191                 if (!%co) {
2192                         next;
2193                 }
2194                 $pr->{'commit'} = \%co;
2195                 if (!defined $pr->{'descr'}) {
2196                         my $descr = git_get_project_description($pr->{'path'}) || "";
2197                         $pr->{'descr'} = chop_str($descr, 25, 5);
2198                 }
2199                 if (!defined $pr->{'owner'}) {
2200                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2201                 }
2202                 push @projects, $pr;
2203         }
2205         git_header_html();
2206         if (-f $home_text) {
2207                 print "<div class=\"index_include\">\n";
2208                 open (my $fd, $home_text);
2209                 print <$fd>;
2210                 close $fd;
2211                 print "</div>\n";
2212         }
2213         print "<table class=\"project_list\">\n" .
2214               "<tr>\n";
2215         $order ||= "project";
2216         if ($order eq "project") {
2217                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2218                 print "<th>Project</th>\n";
2219         } else {
2220                 print "<th>" .
2221                       $cgi->a({-href => href(project=>undef, order=>'project'),
2222                                -class => "header"}, "Project") .
2223                       "</th>\n";
2224         }
2225         if ($order eq "descr") {
2226                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2227                 print "<th>Description</th>\n";
2228         } else {
2229                 print "<th>" .
2230                       $cgi->a({-href => href(project=>undef, order=>'descr'),
2231                                -class => "header"}, "Description") .
2232                       "</th>\n";
2233         }
2234         if ($order eq "owner") {
2235                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2236                 print "<th>Owner</th>\n";
2237         } else {
2238                 print "<th>" .
2239                       $cgi->a({-href => href(project=>undef, order=>'owner'),
2240                                -class => "header"}, "Owner") .
2241                       "</th>\n";
2242         }
2243         if ($order eq "age") {
2244                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2245                 print "<th>Last Change</th>\n";
2246         } else {
2247                 print "<th>" .
2248                       $cgi->a({-href => href(project=>undef, order=>'age'),
2249                                -class => "header"}, "Last Change") .
2250                       "</th>\n";
2251         }
2252         print "<th></th>\n" .
2253               "</tr>\n";
2254         my $alternate = 0;
2255         foreach my $pr (@projects) {
2256                 if ($alternate) {
2257                         print "<tr class=\"dark\">\n";
2258                 } else {
2259                         print "<tr class=\"light\">\n";
2260                 }
2261                 $alternate ^= 1;
2262                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2263                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2264                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2265                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2266                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2267                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2268                       "<td class=\"link\">" .
2269                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2270                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2271                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
2272                       "</td>\n" .
2273                       "</tr>\n";
2274         }
2275         print "</table>\n";
2276         git_footer_html();
2279 sub git_project_index {
2280         my @projects = git_get_projects_list();
2282         print $cgi->header(
2283                 -type => 'text/plain',
2284                 -charset => 'utf-8',
2285                 -content_disposition => qq(inline; filename="index.aux"));
2287         foreach my $pr (@projects) {
2288                 if (!exists $pr->{'owner'}) {
2289                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2290                 }
2292                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2293                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2294                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2295                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2296                 $path  =~ s/ /\+/g;
2297                 $owner =~ s/ /\+/g;
2299                 print "$path $owner\n";
2300         }
2303 sub git_summary {
2304         my $descr = git_get_project_description($project) || "none";
2305         my $head = git_get_head_hash($project);
2306         my %co = parse_commit($head);
2307         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2309         my $owner = git_get_project_owner($project);
2311         my $refs = git_get_references();
2312         git_header_html();
2313         git_print_page_nav('summary','', $head);
2315         print "<div class=\"title\">&nbsp;</div>\n";
2316         print "<table cellspacing=\"0\">\n" .
2317               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2318               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2319               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2320         # use per project git URL list in $projectroot/$project/cloneurl
2321         # or make project git URL from git base URL and project name
2322         my $url_tag = "URL";
2323         my @url_list = git_get_project_url_list($project);
2324         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2325         foreach my $git_url (@url_list) {
2326                 next unless $git_url;
2327                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2328                 $url_tag = "";
2329         }
2330         print "</table>\n";
2332         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2333                 git_get_head_hash($project)
2334                 or die_error(undef, "Open git-rev-list failed");
2335         my @revlist = map { chomp; $_ } <$fd>;
2336         close $fd;
2337         git_print_header_div('shortlog');
2338         git_shortlog_body(\@revlist, 0, 15, $refs,
2339                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2341         my $taglist = git_get_refs_list("refs/tags");
2342         if (defined @$taglist) {
2343                 git_print_header_div('tags');
2344                 git_tags_body($taglist, 0, 15,
2345                               $cgi->a({-href => href(action=>"tags")}, "..."));
2346         }
2348         my $headlist = git_get_refs_list("refs/heads");
2349         if (defined @$headlist) {
2350                 git_print_header_div('heads');
2351                 git_heads_body($headlist, $head, 0, 15,
2352                                $cgi->a({-href => href(action=>"heads")}, "..."));
2353         }
2355         git_footer_html();
2358 sub git_tag {
2359         my $head = git_get_head_hash($project);
2360         git_header_html();
2361         git_print_page_nav('','', $head,undef,$head);
2362         my %tag = parse_tag($hash);
2363         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2364         print "<div class=\"title_text\">\n" .
2365               "<table cellspacing=\"0\">\n" .
2366               "<tr>\n" .
2367               "<td>object</td>\n" .
2368               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2369                                $tag{'object'}) . "</td>\n" .
2370               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2371                                               $tag{'type'}) . "</td>\n" .
2372               "</tr>\n";
2373         if (defined($tag{'author'})) {
2374                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2375                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2376                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2377                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2378                         "</td></tr>\n";
2379         }
2380         print "</table>\n\n" .
2381               "</div>\n";
2382         print "<div class=\"page_body\">";
2383         my $comment = $tag{'comment'};
2384         foreach my $line (@$comment) {
2385                 print esc_html($line) . "<br/>\n";
2386         }
2387         print "</div>\n";
2388         git_footer_html();
2391 sub git_blame2 {
2392         my $fd;
2393         my $ftype;
2395         my ($have_blame) = gitweb_check_feature('blame');
2396         if (!$have_blame) {
2397                 die_error('403 Permission denied', "Permission denied");
2398         }
2399         die_error('404 Not Found', "File name not defined") if (!$file_name);
2400         $hash_base ||= git_get_head_hash($project);
2401         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2402         my %co = parse_commit($hash_base)
2403                 or die_error(undef, "Reading commit failed");
2404         if (!defined $hash) {
2405                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2406                         or die_error(undef, "Error looking up file");
2407         }
2408         $ftype = git_get_type($hash);
2409         if ($ftype !~ "blob") {
2410                 die_error("400 Bad Request", "Object is not a blob");
2411         }
2412         open ($fd, "-|", git_cmd(), "blame", '-l', $file_name, $hash_base)
2413                 or die_error(undef, "Open git-blame failed");
2414         git_header_html();
2415         my $formats_nav =
2416                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2417                         "blob") .
2418                 " | " .
2419                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2420                         "head");
2421         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2422         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2423         git_print_page_path($file_name, $ftype, $hash_base);
2424         my @rev_color = (qw(light2 dark2));
2425         my $num_colors = scalar(@rev_color);
2426         my $current_color = 0;
2427         my $last_rev;
2428         print <<HTML;
2429 <div class="page_body">
2430 <table class="blame">
2431 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2432 HTML
2433         while (<$fd>) {
2434                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2435                 my $full_rev = $1;
2436                 my $rev = substr($full_rev, 0, 8);
2437                 my $lineno = $2;
2438                 my $data = $3;
2440                 if (!defined $last_rev) {
2441                         $last_rev = $full_rev;
2442                 } elsif ($last_rev ne $full_rev) {
2443                         $last_rev = $full_rev;
2444                         $current_color = ++$current_color % $num_colors;
2445                 }
2446                 print "<tr class=\"$rev_color[$current_color]\">\n";
2447                 print "<td class=\"sha1\">" .
2448                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2449                                 esc_html($rev)) . "</td>\n";
2450                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2451                       esc_html($lineno) . "</a></td>\n";
2452                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2453                 print "</tr>\n";
2454         }
2455         print "</table>\n";
2456         print "</div>";
2457         close $fd
2458                 or print "Reading blob failed\n";
2459         git_footer_html();
2462 sub git_blame {
2463         my $fd;
2465         my ($have_blame) = gitweb_check_feature('blame');
2466         if (!$have_blame) {
2467                 die_error('403 Permission denied', "Permission denied");
2468         }
2469         die_error('404 Not Found', "File name not defined") if (!$file_name);
2470         $hash_base ||= git_get_head_hash($project);
2471         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2472         my %co = parse_commit($hash_base)
2473                 or die_error(undef, "Reading commit failed");
2474         if (!defined $hash) {
2475                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2476                         or die_error(undef, "Error lookup file");
2477         }
2478         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2479                 or die_error(undef, "Open git-annotate failed");
2480         git_header_html();
2481         my $formats_nav =
2482                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2483                         "blob") .
2484                 " | " .
2485                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2486                         "head");
2487         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2488         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2489         git_print_page_path($file_name, 'blob', $hash_base);
2490         print "<div class=\"page_body\">\n";
2491         print <<HTML;
2492 <table class="blame">
2493   <tr>
2494     <th>Commit</th>
2495     <th>Age</th>
2496     <th>Author</th>
2497     <th>Line</th>
2498     <th>Data</th>
2499   </tr>
2500 HTML
2501         my @line_class = (qw(light dark));
2502         my $line_class_len = scalar (@line_class);
2503         my $line_class_num = $#line_class;
2504         while (my $line = <$fd>) {
2505                 my $long_rev;
2506                 my $short_rev;
2507                 my $author;
2508                 my $time;
2509                 my $lineno;
2510                 my $data;
2511                 my $age;
2512                 my $age_str;
2513                 my $age_class;
2515                 chomp $line;
2516                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2518                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2519                         $long_rev = $1;
2520                         $author   = $2;
2521                         $time     = $3;
2522                         $lineno   = $4;
2523                         $data     = $5;
2524                 } else {
2525                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2526                         next;
2527                 }
2528                 $short_rev  = substr ($long_rev, 0, 8);
2529                 $age        = time () - $time;
2530                 $age_str    = age_string ($age);
2531                 $age_str    =~ s/ /&nbsp;/g;
2532                 $age_class  = age_class($age);
2533                 $author     = esc_html ($author);
2534                 $author     =~ s/ /&nbsp;/g;
2536                 $data = untabify($data);
2537                 $data = esc_html ($data);
2539                 print <<HTML;
2540   <tr class="$line_class[$line_class_num]">
2541     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2542     <td class="$age_class">$age_str</td>
2543     <td>$author</td>
2544     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2545     <td class="pre">$data</td>
2546   </tr>
2547 HTML
2548         } # while (my $line = <$fd>)
2549         print "</table>\n\n";
2550         close $fd
2551                 or print "Reading blob failed.\n";
2552         print "</div>";
2553         git_footer_html();
2556 sub git_tags {
2557         my $head = git_get_head_hash($project);
2558         git_header_html();
2559         git_print_page_nav('','', $head,undef,$head);
2560         git_print_header_div('summary', $project);
2562         my $taglist = git_get_refs_list("refs/tags");
2563         if (defined @$taglist) {
2564                 git_tags_body($taglist);
2565         }
2566         git_footer_html();
2569 sub git_heads {
2570         my $head = git_get_head_hash($project);
2571         git_header_html();
2572         git_print_page_nav('','', $head,undef,$head);
2573         git_print_header_div('summary', $project);
2575         my $taglist = git_get_refs_list("refs/heads");
2576         if (defined @$taglist) {
2577                 git_heads_body($taglist, $head);
2578         }
2579         git_footer_html();
2582 sub git_blob_plain {
2583         my $expires;
2585         if (!defined $hash) {
2586                 if (defined $file_name) {
2587                         my $base = $hash_base || git_get_head_hash($project);
2588                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2589                                 or die_error(undef, "Error lookup file");
2590                 } else {
2591                         die_error(undef, "No file name defined");
2592                 }
2593         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2594                 # blobs defined by non-textual hash id's can be cached
2595                 $expires = "+1d";
2596         }
2598         my $type = shift;
2599         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2600                 or die_error(undef, "Couldn't cat $file_name, $hash");
2602         $type ||= blob_mimetype($fd, $file_name);
2604         # save as filename, even when no $file_name is given
2605         my $save_as = "$hash";
2606         if (defined $file_name) {
2607                 $save_as = $file_name;
2608         } elsif ($type =~ m/^text\//) {
2609                 $save_as .= '.txt';
2610         }
2612         print $cgi->header(
2613                 -type => "$type",
2614                 -expires=>$expires,
2615                 -content_disposition => "inline; filename=\"$save_as\"");
2616         undef $/;
2617         binmode STDOUT, ':raw';
2618         print <$fd>;
2619         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2620         $/ = "\n";
2621         close $fd;
2624 sub git_blob {
2625         my $expires;
2627         if (!defined $hash) {
2628                 if (defined $file_name) {
2629                         my $base = $hash_base || git_get_head_hash($project);
2630                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2631                                 or die_error(undef, "Error lookup file");
2632                 } else {
2633                         die_error(undef, "No file name defined");
2634                 }
2635         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2636                 # blobs defined by non-textual hash id's can be cached
2637                 $expires = "+1d";
2638         }
2640         my ($have_blame) = gitweb_check_feature('blame');
2641         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2642                 or die_error(undef, "Couldn't cat $file_name, $hash");
2643         my $mimetype = blob_mimetype($fd, $file_name);
2644         if ($mimetype !~ m/^text\//) {
2645                 close $fd;
2646                 return git_blob_plain($mimetype);
2647         }
2648         git_header_html(undef, $expires);
2649         my $formats_nav = '';
2650         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2651                 if (defined $file_name) {
2652                         if ($have_blame) {
2653                                 $formats_nav .=
2654                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2655                                                                hash=>$hash, file_name=>$file_name)},
2656                                                 "blame") .
2657                                         " | ";
2658                         }
2659                         $formats_nav .=
2660                                 $cgi->a({-href => href(action=>"blob_plain",
2661                                                        hash=>$hash, file_name=>$file_name)},
2662                                         "plain") .
2663                                 " | " .
2664                                 $cgi->a({-href => href(action=>"blob",
2665                                                        hash_base=>"HEAD", file_name=>$file_name)},
2666                                         "head");
2667                 } else {
2668                         $formats_nav .=
2669                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2670                 }
2671                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2672                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2673         } else {
2674                 print "<div class=\"page_nav\">\n" .
2675                       "<br/><br/></div>\n" .
2676                       "<div class=\"title\">$hash</div>\n";
2677         }
2678         git_print_page_path($file_name, "blob", $hash_base);
2679         print "<div class=\"page_body\">\n";
2680         my $nr;
2681         while (my $line = <$fd>) {
2682                 chomp $line;
2683                 $nr++;
2684                 $line = untabify($line);
2685                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2686                        $nr, $nr, $nr, esc_html($line);
2687         }
2688         close $fd
2689                 or print "Reading blob failed.\n";
2690         print "</div>";
2691         git_footer_html();
2694 sub git_tree {
2695         if (!defined $hash) {
2696                 $hash = git_get_head_hash($project);
2697                 if (defined $file_name) {
2698                         my $base = $hash_base || $hash;
2699                         $hash = git_get_hash_by_path($base, $file_name, "tree");
2700                 }
2701                 if (!defined $hash_base) {
2702                         $hash_base = $hash;
2703                 }
2704         }
2705         $/ = "\0";
2706         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2707                 or die_error(undef, "Open git-ls-tree failed");
2708         my @entries = map { chomp; $_ } <$fd>;
2709         close $fd or die_error(undef, "Reading tree failed");
2710         $/ = "\n";
2712         my $refs = git_get_references();
2713         my $ref = format_ref_marker($refs, $hash_base);
2714         git_header_html();
2715         my $base = "";
2716         my ($have_blame) = gitweb_check_feature('blame');
2717         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2718                 git_print_page_nav('tree','', $hash_base);
2719                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2720         } else {
2721                 undef $hash_base;
2722                 print "<div class=\"page_nav\">\n";
2723                 print "<br/><br/></div>\n";
2724                 print "<div class=\"title\">$hash</div>\n";
2725         }
2726         if (defined $file_name) {
2727                 $base = esc_html("$file_name/");
2728         }
2729         git_print_page_path($file_name, 'tree', $hash_base);
2730         print "<div class=\"page_body\">\n";
2731         print "<table cellspacing=\"0\">\n";
2732         my $alternate = 0;
2733         foreach my $line (@entries) {
2734                 my %t = parse_ls_tree_line($line, -z => 1);
2736                 if ($alternate) {
2737                         print "<tr class=\"dark\">\n";
2738                 } else {
2739                         print "<tr class=\"light\">\n";
2740                 }
2741                 $alternate ^= 1;
2743                 git_print_tree_entry(\%t, $base, $hash_base, $have_blame);
2745                 print "</tr>\n";
2746         }
2747         print "</table>\n" .
2748               "</div>";
2749         git_footer_html();
2752 sub git_snapshot {
2754         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2755         my $have_snapshot = (defined $ctype && defined $suffix);
2756         if (!$have_snapshot) {
2757                 die_error('403 Permission denied', "Permission denied");
2758         }
2760         if (!defined $hash) {
2761                 $hash = git_get_head_hash($project);
2762         }
2764         my $filename = basename($project) . "-$hash.tar.$suffix";
2766         print $cgi->header(-type => 'application/x-tar',
2767                            -content_encoding => $ctype,
2768                            -content_disposition => "inline; filename=\"$filename\"",
2769                            -status => '200 OK');
2771         my $git_command = git_cmd_str();
2772         open my $fd, "-|", "$git_command tar-tree $hash \'$project\' | $command" or
2773                 die_error(undef, "Execute git-tar-tree failed.");
2774         binmode STDOUT, ':raw';
2775         print <$fd>;
2776         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2777         close $fd;
2781 sub git_log {
2782         my $head = git_get_head_hash($project);
2783         if (!defined $hash) {
2784                 $hash = $head;
2785         }
2786         if (!defined $page) {
2787                 $page = 0;
2788         }
2789         my $refs = git_get_references();
2791         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2792         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2793                 or die_error(undef, "Open git-rev-list failed");
2794         my @revlist = map { chomp; $_ } <$fd>;
2795         close $fd;
2797         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2799         git_header_html();
2800         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2802         if (!@revlist) {
2803                 my %co = parse_commit($hash);
2805                 git_print_header_div('summary', $project);
2806                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2807         }
2808         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2809                 my $commit = $revlist[$i];
2810                 my $ref = format_ref_marker($refs, $commit);
2811                 my %co = parse_commit($commit);
2812                 next if !%co;
2813                 my %ad = parse_date($co{'author_epoch'});
2814                 git_print_header_div('commit',
2815                                "<span class=\"age\">$co{'age_string'}</span>" .
2816                                esc_html($co{'title'}) . $ref,
2817                                $commit);
2818                 print "<div class=\"title_text\">\n" .
2819                       "<div class=\"log_link\">\n" .
2820                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2821                       " | " .
2822                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2823                       "<br/>\n" .
2824                       "</div>\n" .
2825                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2826                       "</div>\n";
2828                 print "<div class=\"log_body\">\n";
2829                 git_print_simplified_log($co{'comment'});
2830                 print "</div>\n";
2831         }
2832         git_footer_html();
2835 sub git_commit {
2836         my %co = parse_commit($hash);
2837         if (!%co) {
2838                 die_error(undef, "Unknown commit object");
2839         }
2840         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2841         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2843         my $parent = $co{'parent'};
2844         if (!defined $parent) {
2845                 $parent = "--root";
2846         }
2847         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2848                 or die_error(undef, "Open git-diff-tree failed");
2849         my @difftree = map { chomp; $_ } <$fd>;
2850         close $fd or die_error(undef, "Reading git-diff-tree failed");
2852         # non-textual hash id's can be cached
2853         my $expires;
2854         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2855                 $expires = "+1d";
2856         }
2857         my $refs = git_get_references();
2858         my $ref = format_ref_marker($refs, $co{'id'});
2860         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2861         my $have_snapshot = (defined $ctype && defined $suffix);
2863         my $formats_nav = '';
2864         if (defined $file_name && defined $co{'parent'}) {
2865                 my $parent = $co{'parent'};
2866                 $formats_nav .=
2867                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2868                                 "blame");
2869         }
2870         git_header_html(undef, $expires);
2871         git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2872                            $hash, $co{'tree'}, $hash,
2873                            $formats_nav);
2875         if (defined $co{'parent'}) {
2876                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2877         } else {
2878                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2879         }
2880         print "<div class=\"title_text\">\n" .
2881               "<table cellspacing=\"0\">\n";
2882         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2883               "<tr>" .
2884               "<td></td><td> $ad{'rfc2822'}";
2885         if ($ad{'hour_local'} < 6) {
2886                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2887                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2888         } else {
2889                 printf(" (%02d:%02d %s)",
2890                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2891         }
2892         print "</td>" .
2893               "</tr>\n";
2894         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2895         print "<tr><td></td><td> $cd{'rfc2822'}" .
2896               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2897               "</td></tr>\n";
2898         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2899         print "<tr>" .
2900               "<td>tree</td>" .
2901               "<td class=\"sha1\">" .
2902               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2903                        class => "list"}, $co{'tree'}) .
2904               "</td>" .
2905               "<td class=\"link\">" .
2906               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2907                       "tree");
2908         if ($have_snapshot) {
2909                 print " | " .
2910                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2911         }
2912         print "</td>" .
2913               "</tr>\n";
2914         my $parents = $co{'parents'};
2915         foreach my $par (@$parents) {
2916                 print "<tr>" .
2917                       "<td>parent</td>" .
2918                       "<td class=\"sha1\">" .
2919                       $cgi->a({-href => href(action=>"commit", hash=>$par),
2920                                class => "list"}, $par) .
2921                       "</td>" .
2922                       "<td class=\"link\">" .
2923                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2924                       " | " .
2925                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
2926                       "</td>" .
2927                       "</tr>\n";
2928         }
2929         print "</table>".
2930               "</div>\n";
2932         print "<div class=\"page_body\">\n";
2933         git_print_log($co{'comment'});
2934         print "</div>\n";
2936         git_difftree_body(\@difftree, $hash, $parent);
2938         git_footer_html();
2941 sub git_blobdiff {
2942         my $format = shift || 'html';
2944         my $fd;
2945         my @difftree;
2946         my %diffinfo;
2947         my $expires;
2949         # preparing $fd and %diffinfo for git_patchset_body
2950         # new style URI
2951         if (defined $hash_base && defined $hash_parent_base) {
2952                 if (defined $file_name) {
2953                         # read raw output
2954                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
2955                                 "--", $file_name
2956                                 or die_error(undef, "Open git-diff-tree failed");
2957                         @difftree = map { chomp; $_ } <$fd>;
2958                         close $fd
2959                                 or die_error(undef, "Reading git-diff-tree failed");
2960                         @difftree
2961                                 or die_error('404 Not Found', "Blob diff not found");
2963                 } elsif (defined $hash &&
2964                          $hash =~ /[0-9a-fA-F]{40}/) {
2965                         # try to find filename from $hash
2967                         # read filtered raw output
2968                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
2969                                 or die_error(undef, "Open git-diff-tree failed");
2970                         @difftree =
2971                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
2972                                 # $hash == to_id
2973                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
2974                                 map { chomp; $_ } <$fd>;
2975                         close $fd
2976                                 or die_error(undef, "Reading git-diff-tree failed");
2977                         @difftree
2978                                 or die_error('404 Not Found', "Blob diff not found");
2980                 } else {
2981                         die_error('404 Not Found', "Missing one of the blob diff parameters");
2982                 }
2984                 if (@difftree > 1) {
2985                         die_error('404 Not Found', "Ambiguous blob diff specification");
2986                 }
2988                 %diffinfo = parse_difftree_raw_line($difftree[0]);
2989                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
2990                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
2992                 $hash_parent ||= $diffinfo{'from_id'};
2993                 $hash        ||= $diffinfo{'to_id'};
2995                 # non-textual hash id's can be cached
2996                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
2997                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
2998                         $expires = '+1d';
2999                 }
3001                 # open patch output
3002                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3003                         '-p', $hash_parent_base, $hash_base,
3004                         "--", $file_name
3005                         or die_error(undef, "Open git-diff-tree failed");
3006         }
3008         # old/legacy style URI
3009         if (!%diffinfo && # if new style URI failed
3010             defined $hash && defined $hash_parent) {
3011                 # fake git-diff-tree raw output
3012                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3013                 $diffinfo{'from_id'} = $hash_parent;
3014                 $diffinfo{'to_id'}   = $hash;
3015                 if (defined $file_name) {
3016                         if (defined $file_parent) {
3017                                 $diffinfo{'status'} = '2';
3018                                 $diffinfo{'from_file'} = $file_parent;
3019                                 $diffinfo{'to_file'}   = $file_name;
3020                         } else { # assume not renamed
3021                                 $diffinfo{'status'} = '1';
3022                                 $diffinfo{'from_file'} = $file_name;
3023                                 $diffinfo{'to_file'}   = $file_name;
3024                         }
3025                 } else { # no filename given
3026                         $diffinfo{'status'} = '2';
3027                         $diffinfo{'from_file'} = $hash_parent;
3028                         $diffinfo{'to_file'}   = $hash;
3029                 }
3031                 # non-textual hash id's can be cached
3032                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3033                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3034                         $expires = '+1d';
3035                 }
3037                 # open patch output
3038                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3039                         or die_error(undef, "Open git-diff failed");
3040         } else  {
3041                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3042                         unless %diffinfo;
3043         }
3045         # header
3046         if ($format eq 'html') {
3047                 my $formats_nav =
3048                         $cgi->a({-href => href(action=>"blobdiff_plain",
3049                                                hash=>$hash, hash_parent=>$hash_parent,
3050                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3051                                                file_name=>$file_name, file_parent=>$file_parent)},
3052                                 "plain");
3053                 git_header_html(undef, $expires);
3054                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3055                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3056                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3057                 } else {
3058                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3059                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3060                 }
3061                 if (defined $file_name) {
3062                         git_print_page_path($file_name, "blob", $hash_base);
3063                 } else {
3064                         print "<div class=\"page_path\"></div>\n";
3065                 }
3067         } elsif ($format eq 'plain') {
3068                 print $cgi->header(
3069                         -type => 'text/plain',
3070                         -charset => 'utf-8',
3071                         -expires => $expires,
3072                         -content_disposition => qq(inline; filename="${file_name}.patch"));
3074                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3076         } else {
3077                 die_error(undef, "Unknown blobdiff format");
3078         }
3080         # patch
3081         if ($format eq 'html') {
3082                 print "<div class=\"page_body\">\n";
3084                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3085                 close $fd;
3087                 print "</div>\n"; # class="page_body"
3088                 git_footer_html();
3090         } else {
3091                 while (my $line = <$fd>) {
3092                         $line =~ s!a/($hash|$hash_parent)!a/$diffinfo{'from_file'}!g;
3093                         $line =~ s!b/($hash|$hash_parent)!b/$diffinfo{'to_file'}!g;
3095                         print $line;
3097                         last if $line =~ m!^\+\+\+!;
3098                 }
3099                 local $/ = undef;
3100                 print <$fd>;
3101                 close $fd;
3102         }
3105 sub git_blobdiff_plain {
3106         git_blobdiff('plain');
3109 sub git_commitdiff {
3110         my $format = shift || 'html';
3111         my %co = parse_commit($hash);
3112         if (!%co) {
3113                 die_error(undef, "Unknown commit object");
3114         }
3115         if (!defined $hash_parent) {
3116                 $hash_parent = $co{'parent'} || '--root';
3117         }
3119         # read commitdiff
3120         my $fd;
3121         my @difftree;
3122         if ($format eq 'html') {
3123                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3124                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3125                         or die_error(undef, "Open git-diff-tree failed");
3127                 while (chomp(my $line = <$fd>)) {
3128                         # empty line ends raw part of diff-tree output
3129                         last unless $line;
3130                         push @difftree, $line;
3131                 }
3133         } elsif ($format eq 'plain') {
3134                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3135                         '-p', $hash_parent, $hash
3136                         or die_error(undef, "Open git-diff-tree failed");
3138         } else {
3139                 die_error(undef, "Unknown commitdiff format");
3140         }
3142         # non-textual hash id's can be cached
3143         my $expires;
3144         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3145                 $expires = "+1d";
3146         }
3148         # write commit message
3149         if ($format eq 'html') {
3150                 my $refs = git_get_references();
3151                 my $ref = format_ref_marker($refs, $co{'id'});
3152                 my $formats_nav =
3153                         $cgi->a({-href => href(action=>"commitdiff_plain",
3154                                                hash=>$hash, hash_parent=>$hash_parent)},
3155                                 "plain");
3157                 git_header_html(undef, $expires);
3158                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3159                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3160                 git_print_authorship(\%co);
3161                 print "<div class=\"page_body\">\n";
3162                 print "<div class=\"log\">\n";
3163                 git_print_simplified_log($co{'comment'}, 1); # skip title
3164                 print "</div>\n"; # class="log"
3166         } elsif ($format eq 'plain') {
3167                 my $refs = git_get_references("tags");
3168                 my $tagname = git_get_rev_name_tags($hash);
3169                 my $filename = basename($project) . "-$hash.patch";
3171                 print $cgi->header(
3172                         -type => 'text/plain',
3173                         -charset => 'utf-8',
3174                         -expires => $expires,
3175                         -content_disposition => qq(inline; filename="$filename"));
3176                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3177                 print <<TEXT;
3178 From: $co{'author'}
3179 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3180 Subject: $co{'title'}
3181 TEXT
3182                 print "X-Git-Tag: $tagname\n" if $tagname;
3183                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3185                 foreach my $line (@{$co{'comment'}}) {
3186                         print "$line\n";
3187                 }
3188                 print "---\n\n";
3189         }
3191         # write patch
3192         if ($format eq 'html') {
3193                 git_difftree_body(\@difftree, $hash, $hash_parent);
3194                 print "<br/>\n";
3196                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3197                 close $fd;
3198                 print "</div>\n"; # class="page_body"
3199                 git_footer_html();
3201         } elsif ($format eq 'plain') {
3202                 local $/ = undef;
3203                 print <$fd>;
3204                 close $fd
3205                         or print "Reading git-diff-tree failed\n";
3206         }
3209 sub git_commitdiff_plain {
3210         git_commitdiff('plain');
3213 sub git_history {
3214         if (!defined $hash_base) {
3215                 $hash_base = git_get_head_hash($project);
3216         }
3217         if (!defined $page) {
3218                 $page = 0;
3219         }
3220         my $ftype;
3221         my %co = parse_commit($hash_base);
3222         if (!%co) {
3223                 die_error(undef, "Unknown commit object");
3224         }
3226         my $refs = git_get_references();
3227         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3229         if (!defined $hash && defined $file_name) {
3230                 $hash = git_get_hash_by_path($hash_base, $file_name);
3231         }
3232         if (defined $hash) {
3233                 $ftype = git_get_type($hash);
3234         }
3236         open my $fd, "-|",
3237                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3238                         or die_error(undef, "Open git-rev-list-failed");
3239         my @revlist = map { chomp; $_ } <$fd>;
3240         close $fd
3241                 or die_error(undef, "Reading git-rev-list failed");
3243         my $paging_nav = '';
3244         if ($page > 0) {
3245                 $paging_nav .=
3246                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3247                                                file_name=>$file_name)},
3248                                 "first");
3249                 $paging_nav .= " &sdot; " .
3250                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3251                                                file_name=>$file_name, page=>$page-1),
3252                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3253         } else {
3254                 $paging_nav .= "first";
3255                 $paging_nav .= " &sdot; prev";
3256         }
3257         if ($#revlist >= (100 * ($page+1)-1)) {
3258                 $paging_nav .= " &sdot; " .
3259                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3260                                                file_name=>$file_name, page=>$page+1),
3261                                  -accesskey => "n", -title => "Alt-n"}, "next");
3262         } else {
3263                 $paging_nav .= " &sdot; next";
3264         }
3265         my $next_link = '';
3266         if ($#revlist >= (100 * ($page+1)-1)) {
3267                 $next_link =
3268                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3269                                                file_name=>$file_name, page=>$page+1),
3270                                  -title => "Alt-n"}, "next");
3271         }
3273         git_header_html();
3274         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3275         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3276         git_print_page_path($file_name, $ftype, $hash_base);
3278         git_history_body(\@revlist, ($page * 100), $#revlist,
3279                          $refs, $hash_base, $ftype, $next_link);
3281         git_footer_html();
3284 sub git_search {
3285         if (!defined $searchtext) {
3286                 die_error(undef, "Text field empty");
3287         }
3288         if (!defined $hash) {
3289                 $hash = git_get_head_hash($project);
3290         }
3291         my %co = parse_commit($hash);
3292         if (!%co) {
3293                 die_error(undef, "Unknown commit object");
3294         }
3296         my $commit_search = 1;
3297         my $author_search = 0;
3298         my $committer_search = 0;
3299         my $pickaxe_search = 0;
3300         if ($searchtext =~ s/^author\\://i) {
3301                 $author_search = 1;
3302         } elsif ($searchtext =~ s/^committer\\://i) {
3303                 $committer_search = 1;
3304         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3305                 $commit_search = 0;
3306                 $pickaxe_search = 1;
3308                 # pickaxe may take all resources of your box and run for several minutes
3309                 # with every query - so decide by yourself how public you make this feature
3310                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3311                 if (!$have_pickaxe) {
3312                         die_error('403 Permission denied', "Permission denied");
3313                 }
3314         }
3315         git_header_html();
3316         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3317         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3319         print "<table cellspacing=\"0\">\n";
3320         my $alternate = 0;
3321         if ($commit_search) {
3322                 $/ = "\0";
3323                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3324                 while (my $commit_text = <$fd>) {
3325                         if (!grep m/$searchtext/i, $commit_text) {
3326                                 next;
3327                         }
3328                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3329                                 next;
3330                         }
3331                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3332                                 next;
3333                         }
3334                         my @commit_lines = split "\n", $commit_text;
3335                         my %co = parse_commit(undef, \@commit_lines);
3336                         if (!%co) {
3337                                 next;
3338                         }
3339                         if ($alternate) {
3340                                 print "<tr class=\"dark\">\n";
3341                         } else {
3342                                 print "<tr class=\"light\">\n";
3343                         }
3344                         $alternate ^= 1;
3345                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3346                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3347                               "<td>" .
3348                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3349                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3350                         my $comment = $co{'comment'};
3351                         foreach my $line (@$comment) {
3352                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3353                                         my $lead = esc_html($1) || "";
3354                                         $lead = chop_str($lead, 30, 10);
3355                                         my $match = esc_html($2) || "";
3356                                         my $trail = esc_html($3) || "";
3357                                         $trail = chop_str($trail, 30, 10);
3358                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3359                                         print chop_str($text, 80, 5) . "<br/>\n";
3360                                 }
3361                         }
3362                         print "</td>\n" .
3363                               "<td class=\"link\">" .
3364                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3365                               " | " .
3366                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3367                         print "</td>\n" .
3368                               "</tr>\n";
3369                 }
3370                 close $fd;
3371         }
3373         if ($pickaxe_search) {
3374                 $/ = "\n";
3375                 my $git_command = git_cmd_str();
3376                 open my $fd, "-|", "$git_command rev-list $hash | " .
3377                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3378                 undef %co;
3379                 my @files;
3380                 while (my $line = <$fd>) {
3381                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3382                                 my %set;
3383                                 $set{'file'} = $6;
3384                                 $set{'from_id'} = $3;
3385                                 $set{'to_id'} = $4;
3386                                 $set{'id'} = $set{'to_id'};
3387                                 if ($set{'id'} =~ m/0{40}/) {
3388                                         $set{'id'} = $set{'from_id'};
3389                                 }
3390                                 if ($set{'id'} =~ m/0{40}/) {
3391                                         next;
3392                                 }
3393                                 push @files, \%set;
3394                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3395                                 if (%co) {
3396                                         if ($alternate) {
3397                                                 print "<tr class=\"dark\">\n";
3398                                         } else {
3399                                                 print "<tr class=\"light\">\n";
3400                                         }
3401                                         $alternate ^= 1;
3402                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3403                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3404                                               "<td>" .
3405                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3406                                                       -class => "list subject"},
3407                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3408                                         while (my $setref = shift @files) {
3409                                                 my %set = %$setref;
3410                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3411                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3412                                                               -class => "list"},
3413                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3414                                                       "<br/>\n";
3415                                         }
3416                                         print "</td>\n" .
3417                                               "<td class=\"link\">" .
3418                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3419                                               " | " .
3420                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3421                                         print "</td>\n" .
3422                                               "</tr>\n";
3423                                 }
3424                                 %co = parse_commit($1);
3425                         }
3426                 }
3427                 close $fd;
3428         }
3429         print "</table>\n";
3430         git_footer_html();
3433 sub git_shortlog {
3434         my $head = git_get_head_hash($project);
3435         if (!defined $hash) {
3436                 $hash = $head;
3437         }
3438         if (!defined $page) {
3439                 $page = 0;
3440         }
3441         my $refs = git_get_references();
3443         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3444         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3445                 or die_error(undef, "Open git-rev-list failed");
3446         my @revlist = map { chomp; $_ } <$fd>;
3447         close $fd;
3449         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3450         my $next_link = '';
3451         if ($#revlist >= (100 * ($page+1)-1)) {
3452                 $next_link =
3453                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3454                                  -title => "Alt-n"}, "next");
3455         }
3458         git_header_html();
3459         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3460         git_print_header_div('summary', $project);
3462         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3464         git_footer_html();
3467 ## ......................................................................
3468 ## feeds (RSS, OPML)
3470 sub git_rss {
3471         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3472         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3473                 or die_error(undef, "Open git-rev-list failed");
3474         my @revlist = map { chomp; $_ } <$fd>;
3475         close $fd or die_error(undef, "Reading git-rev-list failed");
3476         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3477         print <<XML;
3478 <?xml version="1.0" encoding="utf-8"?>
3479 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3480 <channel>
3481 <title>$project $my_uri $my_url</title>
3482 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3483 <description>$project log</description>
3484 <language>en</language>
3485 XML
3487         for (my $i = 0; $i <= $#revlist; $i++) {
3488                 my $commit = $revlist[$i];
3489                 my %co = parse_commit($commit);
3490                 # we read 150, we always show 30 and the ones more recent than 48 hours
3491                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3492                         last;
3493                 }
3494                 my %cd = parse_date($co{'committer_epoch'});
3495                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3496                         $co{'parent'}, $co{'id'}
3497                         or next;
3498                 my @difftree = map { chomp; $_ } <$fd>;
3499                 close $fd
3500                         or next;
3501                 print "<item>\n" .
3502                       "<title>" .
3503                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3504                       "</title>\n" .
3505                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3506                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3507                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3508                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3509                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3510                       "<content:encoded>" .
3511                       "<![CDATA[\n";
3512                 my $comment = $co{'comment'};
3513                 foreach my $line (@$comment) {
3514                         $line = decode("utf8", $line, Encode::FB_DEFAULT);
3515                         print "$line<br/>\n";
3516                 }
3517                 print "<br/>\n";
3518                 foreach my $line (@difftree) {
3519                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3520                                 next;
3521                         }
3522                         my $file = validate_input(unquote($7));
3523                         $file = decode("utf8", $file, Encode::FB_DEFAULT);
3524                         print "$file<br/>\n";
3525                 }
3526                 print "]]>\n" .
3527                       "</content:encoded>\n" .
3528                       "</item>\n";
3529         }
3530         print "</channel></rss>";
3533 sub git_opml {
3534         my @list = git_get_projects_list();
3536         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3537         print <<XML;
3538 <?xml version="1.0" encoding="utf-8"?>
3539 <opml version="1.0">
3540 <head>
3541   <title>$site_name Git OPML Export</title>
3542 </head>
3543 <body>
3544 <outline text="git RSS feeds">
3545 XML
3547         foreach my $pr (@list) {
3548                 my %proj = %$pr;
3549                 my $head = git_get_head_hash($proj{'path'});
3550                 if (!defined $head) {
3551                         next;
3552                 }
3553                 $git_dir = "$projectroot/$proj{'path'}";
3554                 my %co = parse_commit($head);
3555                 if (!%co) {
3556                         next;
3557                 }
3559                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3560                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3561                 my $html = "$my_url?p=$proj{'path'};a=summary";
3562                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3563         }
3564         print <<XML;
3565 </outline>
3566 </body>
3567 </opml>
3568 XML