Code

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