Code

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