Code

gitweb: Remove redundant "tree" link
[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                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1636                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1637                               esc_html($t->{'name'}));
1638                 print "</td>\n";
1639                 print "<td class=\"link\">";
1640                 if (defined $hash_base) {
1641                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1642                                                      file_name=>"$basedir$t->{'name'}")},
1643                                       "history");
1644                 }
1645                 print "</td>\n";
1646         }
1649 ## ......................................................................
1650 ## functions printing large fragments of HTML
1652 sub git_difftree_body {
1653         my ($difftree, $hash, $parent) = @_;
1655         print "<div class=\"list_head\">\n";
1656         if ($#{$difftree} > 10) {
1657                 print(($#{$difftree} + 1) . " files changed:\n");
1658         }
1659         print "</div>\n";
1661         print "<table class=\"diff_tree\">\n";
1662         my $alternate = 0;
1663         my $patchno = 0;
1664         foreach my $line (@{$difftree}) {
1665                 my %diff = parse_difftree_raw_line($line);
1667                 if ($alternate) {
1668                         print "<tr class=\"dark\">\n";
1669                 } else {
1670                         print "<tr class=\"light\">\n";
1671                 }
1672                 $alternate ^= 1;
1674                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1675                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1676                 if ($diff{'to_mode'} ne ('0' x 6)) {
1677                         $to_mode_oct = oct $diff{'to_mode'};
1678                         if (S_ISREG($to_mode_oct)) { # only for regular file
1679                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1680                         }
1681                         $to_file_type = file_type($diff{'to_mode'});
1682                 }
1683                 if ($diff{'from_mode'} ne ('0' x 6)) {
1684                         $from_mode_oct = oct $diff{'from_mode'};
1685                         if (S_ISREG($to_mode_oct)) { # only for regular file
1686                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1687                         }
1688                         $from_file_type = file_type($diff{'from_mode'});
1689                 }
1691                 if ($diff{'status'} eq "A") { # created
1692                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1693                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1694                         $mode_chng   .= "]</span>";
1695                         print "<td>" .
1696                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1697                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1698                                       -class => "list"}, esc_html($diff{'file'})) .
1699                               "</td>\n" .
1700                               "<td>$mode_chng</td>\n" .
1701                               "<td class=\"link\">" .
1702                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1703                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1704                                       "blob");
1705                         if ($action eq 'commitdiff') {
1706                                 # link to patch
1707                                 $patchno++;
1708                                 print " | " .
1709                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1710                         }
1711                         print "</td>\n";
1713                 } elsif ($diff{'status'} eq "D") { # deleted
1714                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1715                         print "<td>" .
1716                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1717                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1718                                        -class => "list"}, esc_html($diff{'file'})) .
1719                               "</td>\n" .
1720                               "<td>$mode_chng</td>\n" .
1721                               "<td class=\"link\">" .
1722                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1723                                                      hash_base=>$parent, file_name=>$diff{'file'})},
1724                                       "blob") .
1725                               " | ";
1726                         if ($action eq 'commitdiff') {
1727                                 # link to patch
1728                                 $patchno++;
1729                                 print " | " .
1730                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1731                         }
1732                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1733                                                      file_name=>$diff{'file'})},
1734                                       "history") .
1735                               "</td>\n";
1737                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1738                         my $mode_chnge = "";
1739                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1740                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1741                                 if ($from_file_type != $to_file_type) {
1742                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1743                                 }
1744                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1745                                         if ($from_mode_str && $to_mode_str) {
1746                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1747                                         } elsif ($to_mode_str) {
1748                                                 $mode_chnge .= " mode: $to_mode_str";
1749                                         }
1750                                 }
1751                                 $mode_chnge .= "]</span>\n";
1752                         }
1753                         print "<td>";
1754                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1755                                 print $cgi->a({-href => href(action=>"blobdiff",
1756                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1757                                                              hash_base=>$hash, hash_parent_base=>$parent,
1758                                                              file_name=>$diff{'file'}),
1759                                               -class => "list"}, esc_html($diff{'file'}));
1760                         } else { # only mode changed
1761                                 print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1762                                                              hash_base=>$hash, file_name=>$diff{'file'}),
1763                                               -class => "list"}, esc_html($diff{'file'}));
1764                         }
1765                         print "</td>\n" .
1766                               "<td>$mode_chnge</td>\n" .
1767                               "<td class=\"link\">" .
1768                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1769                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1770                                       "blob");
1771                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1772                                 if ($action eq 'commitdiff') {
1773                                         # link to patch
1774                                         $patchno++;
1775                                         print " | " .
1776                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1777                                 } else {
1778                                         print " | " .
1779                                                 $cgi->a({-href => href(action=>"blobdiff",
1780                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1781                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1782                                                                        file_name=>$diff{'file'})},
1783                                                         "diff");
1784                                 }
1785                         }
1786                         print " | " .
1787                                 $cgi->a({-href => href(action=>"history",
1788                                                        hash_base=>$hash, file_name=>$diff{'file'})},
1789                                         "history");
1790                         print "</td>\n";
1792                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1793                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1794                         my $nstatus = $status_name{$diff{'status'}};
1795                         my $mode_chng = "";
1796                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1797                                 # mode also for directories, so we cannot use $to_mode_str
1798                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1799                         }
1800                         print "<td>" .
1801                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1802                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1803                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1804                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1805                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1806                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1807                                       -class => "list"}, esc_html($diff{'from_file'})) .
1808                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1809                               "<td class=\"link\">" .
1810                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1811                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1812                                       "blob");
1813                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1814                                 if ($action eq 'commitdiff') {
1815                                         # link to patch
1816                                         $patchno++;
1817                                         print " | " .
1818                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1819                                 } else {
1820                                         print " | " .
1821                                                 $cgi->a({-href => href(action=>"blobdiff",
1822                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1823                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1824                                                                        file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1825                                                         "diff");
1826                                 }
1827                         }
1828                         print "</td>\n";
1830                 } # we should not encounter Unmerged (U) or Unknown (X) status
1831                 print "</tr>\n";
1832         }
1833         print "</table>\n";
1836 sub git_patchset_body {
1837         my ($fd, $difftree, $hash, $hash_parent) = @_;
1839         my $patch_idx = 0;
1840         my $in_header = 0;
1841         my $patch_found = 0;
1842         my $diffinfo;
1844         print "<div class=\"patchset\">\n";
1846         LINE:
1847         while (my $patch_line = <$fd>) {
1848                 chomp $patch_line;
1850                 if ($patch_line =~ m/^diff /) { # "git diff" header
1851                         # beginning of patch (in patchset)
1852                         if ($patch_found) {
1853                                 # close previous patch
1854                                 print "</div>\n"; # class="patch"
1855                         } else {
1856                                 # first patch in patchset
1857                                 $patch_found = 1;
1858                         }
1859                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1861                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1862                                 $diffinfo = $difftree->[$patch_idx];
1863                         } else {
1864                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1865                         }
1866                         $patch_idx++;
1868                         # for now, no extended header, hence we skip empty patches
1869                         # companion to  next LINE if $in_header;
1870                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1871                                 $in_header = 1;
1872                                 next LINE;
1873                         }
1875                         if ($diffinfo->{'status'} eq "A") { # added
1876                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1877                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1878                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1879                                               $diffinfo->{'to_id'}) . "(new)" .
1880                                       "</div>\n"; # class="diff_info"
1882                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1883                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1884                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1885                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1886                                               $diffinfo->{'from_id'}) . "(deleted)" .
1887                                       "</div>\n"; # class="diff_info"
1889                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1890                                  $diffinfo->{'status'} eq "C" || # copied
1891                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1892                                 print "<div class=\"diff_info\">" .
1893                                       file_type($diffinfo->{'from_mode'}) . ":" .
1894                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1895                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1896                                               $diffinfo->{'from_id'}) .
1897                                       " -> " .
1898                                       file_type($diffinfo->{'to_mode'}) . ":" .
1899                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1900                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1901                                               $diffinfo->{'to_id'});
1902                                 print "</div>\n"; # class="diff_info"
1904                         } else { # modified, mode changed, ...
1905                                 print "<div class=\"diff_info\">" .
1906                                       file_type($diffinfo->{'from_mode'}) . ":" .
1907                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1908                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1909                                               $diffinfo->{'from_id'}) .
1910                                       " -> " .
1911                                       file_type($diffinfo->{'to_mode'}) . ":" .
1912                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1913                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1914                                               $diffinfo->{'to_id'});
1915                                 print "</div>\n"; # class="diff_info"
1916                         }
1918                         #print "<div class=\"diff extended_header\">\n";
1919                         $in_header = 1;
1920                         next LINE;
1921                 } # start of patch in patchset
1924                 if ($in_header && $patch_line =~ m/^---/) {
1925                         #print "</div>\n"; # class="diff extended_header"
1926                         $in_header = 0;
1928                         my $file = $diffinfo->{'from_file'};
1929                         $file  ||= $diffinfo->{'file'};
1930                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1931                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
1932                                         -class => "list"}, esc_html($file));
1933                         $patch_line =~ s|a/.*$|a/$file|g;
1934                         print "<div class=\"diff from_file\">$patch_line</div>\n";
1936                         $patch_line = <$fd>;
1937                         chomp $patch_line;
1939                         #$patch_line =~ m/^+++/;
1940                         $file    = $diffinfo->{'to_file'};
1941                         $file  ||= $diffinfo->{'file'};
1942                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1943                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
1944                                         -class => "list"}, esc_html($file));
1945                         $patch_line =~ s|b/.*|b/$file|g;
1946                         print "<div class=\"diff to_file\">$patch_line</div>\n";
1948                         next LINE;
1949                 }
1950                 next LINE if $in_header;
1952                 print format_diff_line($patch_line);
1953         }
1954         print "</div>\n" if $patch_found; # class="patch"
1956         print "</div>\n"; # class="patchset"
1959 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1961 sub git_shortlog_body {
1962         # uses global variable $project
1963         my ($revlist, $from, $to, $refs, $extra) = @_;
1965         $from = 0 unless defined $from;
1966         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1968         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1969         my $alternate = 0;
1970         for (my $i = $from; $i <= $to; $i++) {
1971                 my $commit = $revlist->[$i];
1972                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1973                 my $ref = format_ref_marker($refs, $commit);
1974                 my %co = parse_commit($commit);
1975                 if ($alternate) {
1976                         print "<tr class=\"dark\">\n";
1977                 } else {
1978                         print "<tr class=\"light\">\n";
1979                 }
1980                 $alternate ^= 1;
1981                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1982                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1983                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1984                       "<td>";
1985                 print format_subject_html($co{'title'}, $co{'title_short'},
1986                                           href(action=>"commit", hash=>$commit), $ref);
1987                 print "</td>\n" .
1988                       "<td class=\"link\">" .
1989                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1990                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
1991                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
1992                 print "</td>\n" .
1993                       "</tr>\n";
1994         }
1995         if (defined $extra) {
1996                 print "<tr>\n" .
1997                       "<td colspan=\"4\">$extra</td>\n" .
1998                       "</tr>\n";
1999         }
2000         print "</table>\n";
2003 sub git_history_body {
2004         # Warning: assumes constant type (blob or tree) during history
2005         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2007         $from = 0 unless defined $from;
2008         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2010         print "<table class=\"history\" cellspacing=\"0\">\n";
2011         my $alternate = 0;
2012         for (my $i = $from; $i <= $to; $i++) {
2013                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2014                         next;
2015                 }
2017                 my $commit = $1;
2018                 my %co = parse_commit($commit);
2019                 if (!%co) {
2020                         next;
2021                 }
2023                 my $ref = format_ref_marker($refs, $commit);
2025                 if ($alternate) {
2026                         print "<tr class=\"dark\">\n";
2027                 } else {
2028                         print "<tr class=\"light\">\n";
2029                 }
2030                 $alternate ^= 1;
2031                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2032                       # shortlog uses      chop_str($co{'author_name'}, 10)
2033                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2034                       "<td>";
2035                 # originally git_history used chop_str($co{'title'}, 50)
2036                 print format_subject_html($co{'title'}, $co{'title_short'},
2037                                           href(action=>"commit", hash=>$commit), $ref);
2038                 print "</td>\n" .
2039                       "<td class=\"link\">" .
2040                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2041                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2042                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
2044                 if ($ftype eq 'blob') {
2045                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2046                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2047                         if (defined $blob_current && defined $blob_parent &&
2048                                         $blob_current ne $blob_parent) {
2049                                 print " | " .
2050                                         $cgi->a({-href => href(action=>"blobdiff",
2051                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2052                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2053                                                                file_name=>$file_name)},
2054                                                 "diff to current");
2055                         }
2056                 }
2057                 print "</td>\n" .
2058                       "</tr>\n";
2059         }
2060         if (defined $extra) {
2061                 print "<tr>\n" .
2062                       "<td colspan=\"4\">$extra</td>\n" .
2063                       "</tr>\n";
2064         }
2065         print "</table>\n";
2068 sub git_tags_body {
2069         # uses global variable $project
2070         my ($taglist, $from, $to, $extra) = @_;
2071         $from = 0 unless defined $from;
2072         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2074         print "<table class=\"tags\" cellspacing=\"0\">\n";
2075         my $alternate = 0;
2076         for (my $i = $from; $i <= $to; $i++) {
2077                 my $entry = $taglist->[$i];
2078                 my %tag = %$entry;
2079                 my $comment_lines = $tag{'comment'};
2080                 my $comment = shift @$comment_lines;
2081                 my $comment_short;
2082                 if (defined $comment) {
2083                         $comment_short = chop_str($comment, 30, 5);
2084                 }
2085                 if ($alternate) {
2086                         print "<tr class=\"dark\">\n";
2087                 } else {
2088                         print "<tr class=\"light\">\n";
2089                 }
2090                 $alternate ^= 1;
2091                 print "<td><i>$tag{'age'}</i></td>\n" .
2092                       "<td>" .
2093                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2094                                -class => "list name"}, esc_html($tag{'name'})) .
2095                       "</td>\n" .
2096                       "<td>";
2097                 if (defined $comment) {
2098                         print format_subject_html($comment, $comment_short,
2099                                                   href(action=>"tag", hash=>$tag{'id'}));
2100                 }
2101                 print "</td>\n" .
2102                       "<td class=\"selflink\">";
2103                 if ($tag{'type'} eq "tag") {
2104                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2105                 } else {
2106                         print "&nbsp;";
2107                 }
2108                 print "</td>\n" .
2109                       "<td class=\"link\">" . " | " .
2110                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2111                 if ($tag{'reftype'} eq "commit") {
2112                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2113                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2114                 } elsif ($tag{'reftype'} eq "blob") {
2115                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2116                 }
2117                 print "</td>\n" .
2118                       "</tr>";
2119         }
2120         if (defined $extra) {
2121                 print "<tr>\n" .
2122                       "<td colspan=\"5\">$extra</td>\n" .
2123                       "</tr>\n";
2124         }
2125         print "</table>\n";
2128 sub git_heads_body {
2129         # uses global variable $project
2130         my ($headlist, $head, $from, $to, $extra) = @_;
2131         $from = 0 unless defined $from;
2132         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2134         print "<table class=\"heads\" cellspacing=\"0\">\n";
2135         my $alternate = 0;
2136         for (my $i = $from; $i <= $to; $i++) {
2137                 my $entry = $headlist->[$i];
2138                 my %tag = %$entry;
2139                 my $curr = $tag{'id'} eq $head;
2140                 if ($alternate) {
2141                         print "<tr class=\"dark\">\n";
2142                 } else {
2143                         print "<tr class=\"light\">\n";
2144                 }
2145                 $alternate ^= 1;
2146                 print "<td><i>$tag{'age'}</i></td>\n" .
2147                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2148                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2149                                -class => "list name"},esc_html($tag{'name'})) .
2150                       "</td>\n" .
2151                       "<td class=\"link\">" .
2152                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2153                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") . " | " .
2154                       $cgi->a({-href => href(action=>"tree", hash=>$tag{'name'}, hash_base=>$tag{'name'})}, "tree") .
2155                       "</td>\n" .
2156                       "</tr>";
2157         }
2158         if (defined $extra) {
2159                 print "<tr>\n" .
2160                       "<td colspan=\"3\">$extra</td>\n" .
2161                       "</tr>\n";
2162         }
2163         print "</table>\n";
2166 ## ======================================================================
2167 ## ======================================================================
2168 ## actions
2170 sub git_project_list {
2171         my $order = $cgi->param('o');
2172         if (defined $order && $order !~ m/project|descr|owner|age/) {
2173                 die_error(undef, "Unknown order parameter");
2174         }
2176         my @list = git_get_projects_list();
2177         my @projects;
2178         if (!@list) {
2179                 die_error(undef, "No projects found");
2180         }
2181         foreach my $pr (@list) {
2182                 my $head = git_get_head_hash($pr->{'path'});
2183                 if (!defined $head) {
2184                         next;
2185                 }
2186                 $git_dir = "$projectroot/$pr->{'path'}";
2187                 my %co = parse_commit($head);
2188                 if (!%co) {
2189                         next;
2190                 }
2191                 $pr->{'commit'} = \%co;
2192                 if (!defined $pr->{'descr'}) {
2193                         my $descr = git_get_project_description($pr->{'path'}) || "";
2194                         $pr->{'descr'} = chop_str($descr, 25, 5);
2195                 }
2196                 if (!defined $pr->{'owner'}) {
2197                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2198                 }
2199                 push @projects, $pr;
2200         }
2202         git_header_html();
2203         if (-f $home_text) {
2204                 print "<div class=\"index_include\">\n";
2205                 open (my $fd, $home_text);
2206                 print <$fd>;
2207                 close $fd;
2208                 print "</div>\n";
2209         }
2210         print "<table class=\"project_list\">\n" .
2211               "<tr>\n";
2212         $order ||= "project";
2213         if ($order eq "project") {
2214                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2215                 print "<th>Project</th>\n";
2216         } else {
2217                 print "<th>" .
2218                       $cgi->a({-href => href(project=>undef, order=>'project'),
2219                                -class => "header"}, "Project") .
2220                       "</th>\n";
2221         }
2222         if ($order eq "descr") {
2223                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2224                 print "<th>Description</th>\n";
2225         } else {
2226                 print "<th>" .
2227                       $cgi->a({-href => href(project=>undef, order=>'descr'),
2228                                -class => "header"}, "Description") .
2229                       "</th>\n";
2230         }
2231         if ($order eq "owner") {
2232                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2233                 print "<th>Owner</th>\n";
2234         } else {
2235                 print "<th>" .
2236                       $cgi->a({-href => href(project=>undef, order=>'owner'),
2237                                -class => "header"}, "Owner") .
2238                       "</th>\n";
2239         }
2240         if ($order eq "age") {
2241                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2242                 print "<th>Last Change</th>\n";
2243         } else {
2244                 print "<th>" .
2245                       $cgi->a({-href => href(project=>undef, order=>'age'),
2246                                -class => "header"}, "Last Change") .
2247                       "</th>\n";
2248         }
2249         print "<th></th>\n" .
2250               "</tr>\n";
2251         my $alternate = 0;
2252         foreach my $pr (@projects) {
2253                 if ($alternate) {
2254                         print "<tr class=\"dark\">\n";
2255                 } else {
2256                         print "<tr class=\"light\">\n";
2257                 }
2258                 $alternate ^= 1;
2259                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2260                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2261                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2262                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2263                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2264                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2265                       "<td class=\"link\">" .
2266                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2267                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2268                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2269                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2270                       "</td>\n" .
2271                       "</tr>\n";
2272         }
2273         print "</table>\n";
2274         git_footer_html();
2277 sub git_project_index {
2278         my @projects = git_get_projects_list();
2280         print $cgi->header(
2281                 -type => 'text/plain',
2282                 -charset => 'utf-8',
2283                 -content_disposition => qq(inline; filename="index.aux"));
2285         foreach my $pr (@projects) {
2286                 if (!exists $pr->{'owner'}) {
2287                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2288                 }
2290                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2291                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2292                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2293                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2294                 $path  =~ s/ /\+/g;
2295                 $owner =~ s/ /\+/g;
2297                 print "$path $owner\n";
2298         }
2301 sub git_summary {
2302         my $descr = git_get_project_description($project) || "none";
2303         my $head = git_get_head_hash($project);
2304         my %co = parse_commit($head);
2305         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2307         my $owner = git_get_project_owner($project);
2309         my ($reflist, $refs) = git_get_refs_list();
2311         my @taglist;
2312         my @headlist;
2313         foreach my $ref (@$reflist) {
2314                 if ($ref->{'name'} =~ s!^heads/!!) {
2315                         push @headlist, $ref;
2316                 } else {
2317                         $ref->{'name'} =~ s!^tags/!!;
2318                         push @taglist, $ref;
2319                 }
2320         }
2322         git_header_html();
2323         git_print_page_nav('summary','', $head);
2325         print "<div class=\"title\">&nbsp;</div>\n";
2326         print "<table cellspacing=\"0\">\n" .
2327               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2328               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2329               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2330         # use per project git URL list in $projectroot/$project/cloneurl
2331         # or make project git URL from git base URL and project name
2332         my $url_tag = "URL";
2333         my @url_list = git_get_project_url_list($project);
2334         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2335         foreach my $git_url (@url_list) {
2336                 next unless $git_url;
2337                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2338                 $url_tag = "";
2339         }
2340         print "</table>\n";
2342         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2343                 git_get_head_hash($project)
2344                 or die_error(undef, "Open git-rev-list failed");
2345         my @revlist = map { chomp; $_ } <$fd>;
2346         close $fd;
2347         git_print_header_div('shortlog');
2348         git_shortlog_body(\@revlist, 0, 15, $refs,
2349                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2351         if (@taglist) {
2352                 git_print_header_div('tags');
2353                 git_tags_body(\@taglist, 0, 15,
2354                               $cgi->a({-href => href(action=>"tags")}, "..."));
2355         }
2357         if (@headlist) {
2358                 git_print_header_div('heads');
2359                 git_heads_body(\@headlist, $head, 0, 15,
2360                                $cgi->a({-href => href(action=>"heads")}, "..."));
2361         }
2363         git_footer_html();
2366 sub git_tag {
2367         my $head = git_get_head_hash($project);
2368         git_header_html();
2369         git_print_page_nav('','', $head,undef,$head);
2370         my %tag = parse_tag($hash);
2371         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2372         print "<div class=\"title_text\">\n" .
2373               "<table cellspacing=\"0\">\n" .
2374               "<tr>\n" .
2375               "<td>object</td>\n" .
2376               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2377                                $tag{'object'}) . "</td>\n" .
2378               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2379                                               $tag{'type'}) . "</td>\n" .
2380               "</tr>\n";
2381         if (defined($tag{'author'})) {
2382                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2383                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2384                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2385                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2386                         "</td></tr>\n";
2387         }
2388         print "</table>\n\n" .
2389               "</div>\n";
2390         print "<div class=\"page_body\">";
2391         my $comment = $tag{'comment'};
2392         foreach my $line (@$comment) {
2393                 print esc_html($line) . "<br/>\n";
2394         }
2395         print "</div>\n";
2396         git_footer_html();
2399 sub git_blame2 {
2400         my $fd;
2401         my $ftype;
2403         my ($have_blame) = gitweb_check_feature('blame');
2404         if (!$have_blame) {
2405                 die_error('403 Permission denied', "Permission denied");
2406         }
2407         die_error('404 Not Found', "File name not defined") if (!$file_name);
2408         $hash_base ||= git_get_head_hash($project);
2409         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2410         my %co = parse_commit($hash_base)
2411                 or die_error(undef, "Reading commit failed");
2412         if (!defined $hash) {
2413                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2414                         or die_error(undef, "Error looking up file");
2415         }
2416         $ftype = git_get_type($hash);
2417         if ($ftype !~ "blob") {
2418                 die_error("400 Bad Request", "Object is not a blob");
2419         }
2420         open ($fd, "-|", git_cmd(), "blame", '-l', '--', $file_name, $hash_base)
2421                 or die_error(undef, "Open git-blame failed");
2422         git_header_html();
2423         my $formats_nav =
2424                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2425                         "blob") .
2426                 " | " .
2427                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2428                         "history") .
2429                 " | " .
2430                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2431                         "HEAD");
2432         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2433         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2434         git_print_page_path($file_name, $ftype, $hash_base);
2435         my @rev_color = (qw(light2 dark2));
2436         my $num_colors = scalar(@rev_color);
2437         my $current_color = 0;
2438         my $last_rev;
2439         print <<HTML;
2440 <div class="page_body">
2441 <table class="blame">
2442 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2443 HTML
2444         while (<$fd>) {
2445                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2446                 my $full_rev = $1;
2447                 my $rev = substr($full_rev, 0, 8);
2448                 my $lineno = $2;
2449                 my $data = $3;
2451                 if (!defined $last_rev) {
2452                         $last_rev = $full_rev;
2453                 } elsif ($last_rev ne $full_rev) {
2454                         $last_rev = $full_rev;
2455                         $current_color = ++$current_color % $num_colors;
2456                 }
2457                 print "<tr class=\"$rev_color[$current_color]\">\n";
2458                 print "<td class=\"sha1\">" .
2459                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2460                                 esc_html($rev)) . "</td>\n";
2461                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2462                       esc_html($lineno) . "</a></td>\n";
2463                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2464                 print "</tr>\n";
2465         }
2466         print "</table>\n";
2467         print "</div>";
2468         close $fd
2469                 or print "Reading blob failed\n";
2470         git_footer_html();
2473 sub git_blame {
2474         my $fd;
2476         my ($have_blame) = gitweb_check_feature('blame');
2477         if (!$have_blame) {
2478                 die_error('403 Permission denied', "Permission denied");
2479         }
2480         die_error('404 Not Found', "File name not defined") if (!$file_name);
2481         $hash_base ||= git_get_head_hash($project);
2482         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2483         my %co = parse_commit($hash_base)
2484                 or die_error(undef, "Reading commit failed");
2485         if (!defined $hash) {
2486                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2487                         or die_error(undef, "Error lookup file");
2488         }
2489         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2490                 or die_error(undef, "Open git-annotate failed");
2491         git_header_html();
2492         my $formats_nav =
2493                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2494                         "blob") .
2495                 " | " .
2496                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2497                         "history") .
2498                 " | " .
2499                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2500                         "HEAD");
2501         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2502         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2503         git_print_page_path($file_name, 'blob', $hash_base);
2504         print "<div class=\"page_body\">\n";
2505         print <<HTML;
2506 <table class="blame">
2507   <tr>
2508     <th>Commit</th>
2509     <th>Age</th>
2510     <th>Author</th>
2511     <th>Line</th>
2512     <th>Data</th>
2513   </tr>
2514 HTML
2515         my @line_class = (qw(light dark));
2516         my $line_class_len = scalar (@line_class);
2517         my $line_class_num = $#line_class;
2518         while (my $line = <$fd>) {
2519                 my $long_rev;
2520                 my $short_rev;
2521                 my $author;
2522                 my $time;
2523                 my $lineno;
2524                 my $data;
2525                 my $age;
2526                 my $age_str;
2527                 my $age_class;
2529                 chomp $line;
2530                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2532                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2533                         $long_rev = $1;
2534                         $author   = $2;
2535                         $time     = $3;
2536                         $lineno   = $4;
2537                         $data     = $5;
2538                 } else {
2539                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2540                         next;
2541                 }
2542                 $short_rev  = substr ($long_rev, 0, 8);
2543                 $age        = time () - $time;
2544                 $age_str    = age_string ($age);
2545                 $age_str    =~ s/ /&nbsp;/g;
2546                 $age_class  = age_class($age);
2547                 $author     = esc_html ($author);
2548                 $author     =~ s/ /&nbsp;/g;
2550                 $data = untabify($data);
2551                 $data = esc_html ($data);
2553                 print <<HTML;
2554   <tr class="$line_class[$line_class_num]">
2555     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2556     <td class="$age_class">$age_str</td>
2557     <td>$author</td>
2558     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2559     <td class="pre">$data</td>
2560   </tr>
2561 HTML
2562         } # while (my $line = <$fd>)
2563         print "</table>\n\n";
2564         close $fd
2565                 or print "Reading blob failed.\n";
2566         print "</div>";
2567         git_footer_html();
2570 sub git_tags {
2571         my $head = git_get_head_hash($project);
2572         git_header_html();
2573         git_print_page_nav('','', $head,undef,$head);
2574         git_print_header_div('summary', $project);
2576         my ($taglist) = git_get_refs_list("tags");
2577         if (@$taglist) {
2578                 git_tags_body($taglist);
2579         }
2580         git_footer_html();
2583 sub git_heads {
2584         my $head = git_get_head_hash($project);
2585         git_header_html();
2586         git_print_page_nav('','', $head,undef,$head);
2587         git_print_header_div('summary', $project);
2589         my ($headlist) = git_get_refs_list("heads");
2590         if (@$headlist) {
2591                 git_heads_body($headlist, $head);
2592         }
2593         git_footer_html();
2596 sub git_blob_plain {
2597         my $expires;
2599         if (!defined $hash) {
2600                 if (defined $file_name) {
2601                         my $base = $hash_base || git_get_head_hash($project);
2602                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2603                                 or die_error(undef, "Error lookup file");
2604                 } else {
2605                         die_error(undef, "No file name defined");
2606                 }
2607         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2608                 # blobs defined by non-textual hash id's can be cached
2609                 $expires = "+1d";
2610         }
2612         my $type = shift;
2613         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2614                 or die_error(undef, "Couldn't cat $file_name, $hash");
2616         $type ||= blob_mimetype($fd, $file_name);
2618         # save as filename, even when no $file_name is given
2619         my $save_as = "$hash";
2620         if (defined $file_name) {
2621                 $save_as = $file_name;
2622         } elsif ($type =~ m/^text\//) {
2623                 $save_as .= '.txt';
2624         }
2626         print $cgi->header(
2627                 -type => "$type",
2628                 -expires=>$expires,
2629                 -content_disposition => "inline; filename=\"$save_as\"");
2630         undef $/;
2631         binmode STDOUT, ':raw';
2632         print <$fd>;
2633         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2634         $/ = "\n";
2635         close $fd;
2638 sub git_blob {
2639         my $expires;
2641         if (!defined $hash) {
2642                 if (defined $file_name) {
2643                         my $base = $hash_base || git_get_head_hash($project);
2644                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2645                                 or die_error(undef, "Error lookup file");
2646                 } else {
2647                         die_error(undef, "No file name defined");
2648                 }
2649         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2650                 # blobs defined by non-textual hash id's can be cached
2651                 $expires = "+1d";
2652         }
2654         my ($have_blame) = gitweb_check_feature('blame');
2655         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2656                 or die_error(undef, "Couldn't cat $file_name, $hash");
2657         my $mimetype = blob_mimetype($fd, $file_name);
2658         if ($mimetype !~ m/^text\//) {
2659                 close $fd;
2660                 return git_blob_plain($mimetype);
2661         }
2662         git_header_html(undef, $expires);
2663         my $formats_nav = '';
2664         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2665                 if (defined $file_name) {
2666                         if ($have_blame) {
2667                                 $formats_nav .=
2668                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2669                                                                hash=>$hash, file_name=>$file_name)},
2670                                                 "blame") .
2671                                         " | ";
2672                         }
2673                         $formats_nav .=
2674                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2675                                                        hash=>$hash, file_name=>$file_name)},
2676                                         "history") .
2677                                 " | " .
2678                                 $cgi->a({-href => href(action=>"blob_plain",
2679                                                        hash=>$hash, file_name=>$file_name)},
2680                                         "raw") .
2681                                 " | " .
2682                                 $cgi->a({-href => href(action=>"blob",
2683                                                        hash_base=>"HEAD", file_name=>$file_name)},
2684                                         "HEAD");
2685                 } else {
2686                         $formats_nav .=
2687                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
2688                 }
2689                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2690                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2691         } else {
2692                 print "<div class=\"page_nav\">\n" .
2693                       "<br/><br/></div>\n" .
2694                       "<div class=\"title\">$hash</div>\n";
2695         }
2696         git_print_page_path($file_name, "blob", $hash_base);
2697         print "<div class=\"page_body\">\n";
2698         my $nr;
2699         while (my $line = <$fd>) {
2700                 chomp $line;
2701                 $nr++;
2702                 $line = untabify($line);
2703                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2704                        $nr, $nr, $nr, esc_html($line);
2705         }
2706         close $fd
2707                 or print "Reading blob failed.\n";
2708         print "</div>";
2709         git_footer_html();
2712 sub git_tree {
2713         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2714         my $have_snapshot = (defined $ctype && defined $suffix);
2716         if (!defined $hash) {
2717                 $hash = git_get_head_hash($project);
2718                 if (defined $file_name) {
2719                         my $base = $hash_base || $hash;
2720                         $hash = git_get_hash_by_path($base, $file_name, "tree");
2721                 }
2722                 if (!defined $hash_base) {
2723                         $hash_base = $hash;
2724                 }
2725         }
2726         $/ = "\0";
2727         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2728                 or die_error(undef, "Open git-ls-tree failed");
2729         my @entries = map { chomp; $_ } <$fd>;
2730         close $fd or die_error(undef, "Reading tree failed");
2731         $/ = "\n";
2733         my $refs = git_get_references();
2734         my $ref = format_ref_marker($refs, $hash_base);
2735         git_header_html();
2736         my $base = "";
2737         my ($have_blame) = gitweb_check_feature('blame');
2738         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2739                 my @views_nav = ();
2740                 if (defined $file_name) {
2741                         push @views_nav,
2742                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2743                                                        hash=>$hash, file_name=>$file_name)},
2744                                         "history"),
2745                                 $cgi->a({-href => href(action=>"tree",
2746                                                        hash_base=>"HEAD", file_name=>$file_name)},
2747                                         "HEAD"),
2748                 }
2749                 if ($have_snapshot) {
2750                         # FIXME: Should be available when we have no hash base as well.
2751                         push @views_nav,
2752                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
2753                                         "snapshot");
2754                 }
2755                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
2756                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2757         } else {
2758                 undef $hash_base;
2759                 print "<div class=\"page_nav\">\n";
2760                 print "<br/><br/></div>\n";
2761                 print "<div class=\"title\">$hash</div>\n";
2762         }
2763         if (defined $file_name) {
2764                 $base = esc_html("$file_name/");
2765         }
2766         git_print_page_path($file_name, 'tree', $hash_base);
2767         print "<div class=\"page_body\">\n";
2768         print "<table cellspacing=\"0\">\n";
2769         my $alternate = 0;
2770         foreach my $line (@entries) {
2771                 my %t = parse_ls_tree_line($line, -z => 1);
2773                 if ($alternate) {
2774                         print "<tr class=\"dark\">\n";
2775                 } else {
2776                         print "<tr class=\"light\">\n";
2777                 }
2778                 $alternate ^= 1;
2780                 git_print_tree_entry(\%t, $base, $hash_base, $have_blame);
2782                 print "</tr>\n";
2783         }
2784         print "</table>\n" .
2785               "</div>";
2786         git_footer_html();
2789 sub git_snapshot {
2791         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2792         my $have_snapshot = (defined $ctype && defined $suffix);
2793         if (!$have_snapshot) {
2794                 die_error('403 Permission denied', "Permission denied");
2795         }
2797         if (!defined $hash) {
2798                 $hash = git_get_head_hash($project);
2799         }
2801         my $filename = basename($project) . "-$hash.tar.$suffix";
2803         print $cgi->header(-type => 'application/x-tar',
2804                            -content_encoding => $ctype,
2805                            -content_disposition => "inline; filename=\"$filename\"",
2806                            -status => '200 OK');
2808         my $git_command = git_cmd_str();
2809         open my $fd, "-|", "$git_command tar-tree $hash \'$project\' | $command" or
2810                 die_error(undef, "Execute git-tar-tree failed.");
2811         binmode STDOUT, ':raw';
2812         print <$fd>;
2813         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2814         close $fd;
2818 sub git_log {
2819         my $head = git_get_head_hash($project);
2820         if (!defined $hash) {
2821                 $hash = $head;
2822         }
2823         if (!defined $page) {
2824                 $page = 0;
2825         }
2826         my $refs = git_get_references();
2828         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2829         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2830                 or die_error(undef, "Open git-rev-list failed");
2831         my @revlist = map { chomp; $_ } <$fd>;
2832         close $fd;
2834         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2836         git_header_html();
2837         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2839         if (!@revlist) {
2840                 my %co = parse_commit($hash);
2842                 git_print_header_div('summary', $project);
2843                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2844         }
2845         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2846                 my $commit = $revlist[$i];
2847                 my $ref = format_ref_marker($refs, $commit);
2848                 my %co = parse_commit($commit);
2849                 next if !%co;
2850                 my %ad = parse_date($co{'author_epoch'});
2851                 git_print_header_div('commit',
2852                                "<span class=\"age\">$co{'age_string'}</span>" .
2853                                esc_html($co{'title'}) . $ref,
2854                                $commit);
2855                 print "<div class=\"title_text\">\n" .
2856                       "<div class=\"log_link\">\n" .
2857                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2858                       " | " .
2859                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2860                       " | " .
2861                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
2862                       "<br/>\n" .
2863                       "</div>\n" .
2864                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2865                       "</div>\n";
2867                 print "<div class=\"log_body\">\n";
2868                 git_print_simplified_log($co{'comment'});
2869                 print "</div>\n";
2870         }
2871         git_footer_html();
2874 sub git_commit {
2875         my %co = parse_commit($hash);
2876         if (!%co) {
2877                 die_error(undef, "Unknown commit object");
2878         }
2879         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2880         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2882         my $parent = $co{'parent'};
2883         if (!defined $parent) {
2884                 $parent = "--root";
2885         }
2886         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2887                 or die_error(undef, "Open git-diff-tree failed");
2888         my @difftree = map { chomp; $_ } <$fd>;
2889         close $fd or die_error(undef, "Reading git-diff-tree failed");
2891         # non-textual hash id's can be cached
2892         my $expires;
2893         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2894                 $expires = "+1d";
2895         }
2896         my $refs = git_get_references();
2897         my $ref = format_ref_marker($refs, $co{'id'});
2899         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2900         my $have_snapshot = (defined $ctype && defined $suffix);
2902         my @views_nav = ();
2903         if (defined $file_name && defined $co{'parent'}) {
2904                 my $parent = $co{'parent'};
2905                 push @views_nav,
2906                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2907                                 "blame");
2908         }
2909         if (defined $co{'parent'}) {
2910                 push @views_nav,
2911                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash)}, "shortlog"),
2912                         $cgi->a({-href => href(action=>"log", hash=>$hash)}, "log");
2913         }
2914         git_header_html(undef, $expires);
2915         git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2916                            $hash, $co{'tree'}, $hash,
2917                            join (' | ', @views_nav));
2919         if (defined $co{'parent'}) {
2920                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2921         } else {
2922                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2923         }
2924         print "<div class=\"title_text\">\n" .
2925               "<table cellspacing=\"0\">\n";
2926         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2927               "<tr>" .
2928               "<td></td><td> $ad{'rfc2822'}";
2929         if ($ad{'hour_local'} < 6) {
2930                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2931                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2932         } else {
2933                 printf(" (%02d:%02d %s)",
2934                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2935         }
2936         print "</td>" .
2937               "</tr>\n";
2938         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2939         print "<tr><td></td><td> $cd{'rfc2822'}" .
2940               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2941               "</td></tr>\n";
2942         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2943         print "<tr>" .
2944               "<td>tree</td>" .
2945               "<td class=\"sha1\">" .
2946               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2947                        class => "list"}, $co{'tree'}) .
2948               "</td>" .
2949               "<td class=\"link\">" .
2950               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2951                       "tree");
2952         if ($have_snapshot) {
2953                 print " | " .
2954                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2955         }
2956         print "</td>" .
2957               "</tr>\n";
2958         my $parents = $co{'parents'};
2959         foreach my $par (@$parents) {
2960                 print "<tr>" .
2961                       "<td>parent</td>" .
2962                       "<td class=\"sha1\">" .
2963                       $cgi->a({-href => href(action=>"commit", hash=>$par),
2964                                class => "list"}, $par) .
2965                       "</td>" .
2966                       "<td class=\"link\">" .
2967                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2968                       " | " .
2969                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
2970                       "</td>" .
2971                       "</tr>\n";
2972         }
2973         print "</table>".
2974               "</div>\n";
2976         print "<div class=\"page_body\">\n";
2977         git_print_log($co{'comment'});
2978         print "</div>\n";
2980         git_difftree_body(\@difftree, $hash, $parent);
2982         git_footer_html();
2985 sub git_blobdiff {
2986         my $format = shift || 'html';
2988         my $fd;
2989         my @difftree;
2990         my %diffinfo;
2991         my $expires;
2993         # preparing $fd and %diffinfo for git_patchset_body
2994         # new style URI
2995         if (defined $hash_base && defined $hash_parent_base) {
2996                 if (defined $file_name) {
2997                         # read raw output
2998                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
2999                                 "--", $file_name
3000                                 or die_error(undef, "Open git-diff-tree failed");
3001                         @difftree = map { chomp; $_ } <$fd>;
3002                         close $fd
3003                                 or die_error(undef, "Reading git-diff-tree failed");
3004                         @difftree
3005                                 or die_error('404 Not Found', "Blob diff not found");
3007                 } elsif (defined $hash &&
3008                          $hash =~ /[0-9a-fA-F]{40}/) {
3009                         # try to find filename from $hash
3011                         # read filtered raw output
3012                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
3013                                 or die_error(undef, "Open git-diff-tree failed");
3014                         @difftree =
3015                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3016                                 # $hash == to_id
3017                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3018                                 map { chomp; $_ } <$fd>;
3019                         close $fd
3020                                 or die_error(undef, "Reading git-diff-tree failed");
3021                         @difftree
3022                                 or die_error('404 Not Found', "Blob diff not found");
3024                 } else {
3025                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3026                 }
3028                 if (@difftree > 1) {
3029                         die_error('404 Not Found', "Ambiguous blob diff specification");
3030                 }
3032                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3033                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3034                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3036                 $hash_parent ||= $diffinfo{'from_id'};
3037                 $hash        ||= $diffinfo{'to_id'};
3039                 # non-textual hash id's can be cached
3040                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3041                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3042                         $expires = '+1d';
3043                 }
3045                 # open patch output
3046                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3047                         '-p', $hash_parent_base, $hash_base,
3048                         "--", $file_name
3049                         or die_error(undef, "Open git-diff-tree failed");
3050         }
3052         # old/legacy style URI
3053         if (!%diffinfo && # if new style URI failed
3054             defined $hash && defined $hash_parent) {
3055                 # fake git-diff-tree raw output
3056                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3057                 $diffinfo{'from_id'} = $hash_parent;
3058                 $diffinfo{'to_id'}   = $hash;
3059                 if (defined $file_name) {
3060                         if (defined $file_parent) {
3061                                 $diffinfo{'status'} = '2';
3062                                 $diffinfo{'from_file'} = $file_parent;
3063                                 $diffinfo{'to_file'}   = $file_name;
3064                         } else { # assume not renamed
3065                                 $diffinfo{'status'} = '1';
3066                                 $diffinfo{'from_file'} = $file_name;
3067                                 $diffinfo{'to_file'}   = $file_name;
3068                         }
3069                 } else { # no filename given
3070                         $diffinfo{'status'} = '2';
3071                         $diffinfo{'from_file'} = $hash_parent;
3072                         $diffinfo{'to_file'}   = $hash;
3073                 }
3075                 # non-textual hash id's can be cached
3076                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3077                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3078                         $expires = '+1d';
3079                 }
3081                 # open patch output
3082                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3083                         or die_error(undef, "Open git-diff failed");
3084         } else  {
3085                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3086                         unless %diffinfo;
3087         }
3089         # header
3090         if ($format eq 'html') {
3091                 my $formats_nav =
3092                         $cgi->a({-href => href(action=>"blobdiff_plain",
3093                                                hash=>$hash, hash_parent=>$hash_parent,
3094                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3095                                                file_name=>$file_name, file_parent=>$file_parent)},
3096                                 "raw");
3097                 git_header_html(undef, $expires);
3098                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3099                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3100                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3101                 } else {
3102                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3103                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3104                 }
3105                 if (defined $file_name) {
3106                         git_print_page_path($file_name, "blob", $hash_base);
3107                 } else {
3108                         print "<div class=\"page_path\"></div>\n";
3109                 }
3111         } elsif ($format eq 'plain') {
3112                 print $cgi->header(
3113                         -type => 'text/plain',
3114                         -charset => 'utf-8',
3115                         -expires => $expires,
3116                         -content_disposition => qq(inline; filename=") . quotemeta($file_name) . qq(.patch"));
3118                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3120         } else {
3121                 die_error(undef, "Unknown blobdiff format");
3122         }
3124         # patch
3125         if ($format eq 'html') {
3126                 print "<div class=\"page_body\">\n";
3128                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3129                 close $fd;
3131                 print "</div>\n"; # class="page_body"
3132                 git_footer_html();
3134         } else {
3135                 while (my $line = <$fd>) {
3136                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_html($diffinfo{'from_file'})!eg;
3137                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_html($diffinfo{'to_file'})!eg;
3139                         print $line;
3141                         last if $line =~ m!^\+\+\+!;
3142                 }
3143                 local $/ = undef;
3144                 print <$fd>;
3145                 close $fd;
3146         }
3149 sub git_blobdiff_plain {
3150         git_blobdiff('plain');
3153 sub git_commitdiff {
3154         my $format = shift || 'html';
3155         my %co = parse_commit($hash);
3156         if (!%co) {
3157                 die_error(undef, "Unknown commit object");
3158         }
3159         if (!defined $hash_parent) {
3160                 $hash_parent = $co{'parent'} || '--root';
3161         }
3163         # read commitdiff
3164         my $fd;
3165         my @difftree;
3166         if ($format eq 'html') {
3167                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3168                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3169                         or die_error(undef, "Open git-diff-tree failed");
3171                 while (chomp(my $line = <$fd>)) {
3172                         # empty line ends raw part of diff-tree output
3173                         last unless $line;
3174                         push @difftree, $line;
3175                 }
3177         } elsif ($format eq 'plain') {
3178                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3179                         '-p', $hash_parent, $hash
3180                         or die_error(undef, "Open git-diff-tree failed");
3182         } else {
3183                 die_error(undef, "Unknown commitdiff format");
3184         }
3186         # non-textual hash id's can be cached
3187         my $expires;
3188         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3189                 $expires = "+1d";
3190         }
3192         # write commit message
3193         if ($format eq 'html') {
3194                 my $refs = git_get_references();
3195                 my $ref = format_ref_marker($refs, $co{'id'});
3196                 my $formats_nav =
3197                         $cgi->a({-href => href(action=>"commitdiff_plain",
3198                                                hash=>$hash, hash_parent=>$hash_parent)},
3199                                 "raw");
3201                 git_header_html(undef, $expires);
3202                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3203                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3204                 git_print_authorship(\%co);
3205                 print "<div class=\"page_body\">\n";
3206                 print "<div class=\"log\">\n";
3207                 git_print_simplified_log($co{'comment'}, 1); # skip title
3208                 print "</div>\n"; # class="log"
3210         } elsif ($format eq 'plain') {
3211                 my $refs = git_get_references("tags");
3212                 my $tagname = git_get_rev_name_tags($hash);
3213                 my $filename = basename($project) . "-$hash.patch";
3215                 print $cgi->header(
3216                         -type => 'text/plain',
3217                         -charset => 'utf-8',
3218                         -expires => $expires,
3219                         -content_disposition => qq(inline; filename="$filename"));
3220                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3221                 print <<TEXT;
3222 From: $co{'author'}
3223 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3224 Subject: $co{'title'}
3225 TEXT
3226                 print "X-Git-Tag: $tagname\n" if $tagname;
3227                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3229                 foreach my $line (@{$co{'comment'}}) {
3230                         print "$line\n";
3231                 }
3232                 print "---\n\n";
3233         }
3235         # write patch
3236         if ($format eq 'html') {
3237                 git_difftree_body(\@difftree, $hash, $hash_parent);
3238                 print "<br/>\n";
3240                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3241                 close $fd;
3242                 print "</div>\n"; # class="page_body"
3243                 git_footer_html();
3245         } elsif ($format eq 'plain') {
3246                 local $/ = undef;
3247                 print <$fd>;
3248                 close $fd
3249                         or print "Reading git-diff-tree failed\n";
3250         }
3253 sub git_commitdiff_plain {
3254         git_commitdiff('plain');
3257 sub git_history {
3258         if (!defined $hash_base) {
3259                 $hash_base = git_get_head_hash($project);
3260         }
3261         if (!defined $page) {
3262                 $page = 0;
3263         }
3264         my $ftype;
3265         my %co = parse_commit($hash_base);
3266         if (!%co) {
3267                 die_error(undef, "Unknown commit object");
3268         }
3270         my $refs = git_get_references();
3271         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3273         if (!defined $hash && defined $file_name) {
3274                 $hash = git_get_hash_by_path($hash_base, $file_name);
3275         }
3276         if (defined $hash) {
3277                 $ftype = git_get_type($hash);
3278         }
3280         open my $fd, "-|",
3281                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3282                         or die_error(undef, "Open git-rev-list-failed");
3283         my @revlist = map { chomp; $_ } <$fd>;
3284         close $fd
3285                 or die_error(undef, "Reading git-rev-list failed");
3287         my $paging_nav = '';
3288         if ($page > 0) {
3289                 $paging_nav .=
3290                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3291                                                file_name=>$file_name)},
3292                                 "first");
3293                 $paging_nav .= " &sdot; " .
3294                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3295                                                file_name=>$file_name, page=>$page-1),
3296                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3297         } else {
3298                 $paging_nav .= "first";
3299                 $paging_nav .= " &sdot; prev";
3300         }
3301         if ($#revlist >= (100 * ($page+1)-1)) {
3302                 $paging_nav .= " &sdot; " .
3303                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3304                                                file_name=>$file_name, page=>$page+1),
3305                                  -accesskey => "n", -title => "Alt-n"}, "next");
3306         } else {
3307                 $paging_nav .= " &sdot; next";
3308         }
3309         my $next_link = '';
3310         if ($#revlist >= (100 * ($page+1)-1)) {
3311                 $next_link =
3312                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3313                                                file_name=>$file_name, page=>$page+1),
3314                                  -title => "Alt-n"}, "next");
3315         }
3317         git_header_html();
3318         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3319         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3320         git_print_page_path($file_name, $ftype, $hash_base);
3322         git_history_body(\@revlist, ($page * 100), $#revlist,
3323                          $refs, $hash_base, $ftype, $next_link);
3325         git_footer_html();
3328 sub git_search {
3329         if (!defined $searchtext) {
3330                 die_error(undef, "Text field empty");
3331         }
3332         if (!defined $hash) {
3333                 $hash = git_get_head_hash($project);
3334         }
3335         my %co = parse_commit($hash);
3336         if (!%co) {
3337                 die_error(undef, "Unknown commit object");
3338         }
3340         my $commit_search = 1;
3341         my $author_search = 0;
3342         my $committer_search = 0;
3343         my $pickaxe_search = 0;
3344         if ($searchtext =~ s/^author\\://i) {
3345                 $author_search = 1;
3346         } elsif ($searchtext =~ s/^committer\\://i) {
3347                 $committer_search = 1;
3348         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3349                 $commit_search = 0;
3350                 $pickaxe_search = 1;
3352                 # pickaxe may take all resources of your box and run for several minutes
3353                 # with every query - so decide by yourself how public you make this feature
3354                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3355                 if (!$have_pickaxe) {
3356                         die_error('403 Permission denied', "Permission denied");
3357                 }
3358         }
3359         git_header_html();
3360         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3361         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3363         print "<table cellspacing=\"0\">\n";
3364         my $alternate = 0;
3365         if ($commit_search) {
3366                 $/ = "\0";
3367                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3368                 while (my $commit_text = <$fd>) {
3369                         if (!grep m/$searchtext/i, $commit_text) {
3370                                 next;
3371                         }
3372                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3373                                 next;
3374                         }
3375                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3376                                 next;
3377                         }
3378                         my @commit_lines = split "\n", $commit_text;
3379                         my %co = parse_commit(undef, \@commit_lines);
3380                         if (!%co) {
3381                                 next;
3382                         }
3383                         if ($alternate) {
3384                                 print "<tr class=\"dark\">\n";
3385                         } else {
3386                                 print "<tr class=\"light\">\n";
3387                         }
3388                         $alternate ^= 1;
3389                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3390                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3391                               "<td>" .
3392                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3393                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3394                         my $comment = $co{'comment'};
3395                         foreach my $line (@$comment) {
3396                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3397                                         my $lead = esc_html($1) || "";
3398                                         $lead = chop_str($lead, 30, 10);
3399                                         my $match = esc_html($2) || "";
3400                                         my $trail = esc_html($3) || "";
3401                                         $trail = chop_str($trail, 30, 10);
3402                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3403                                         print chop_str($text, 80, 5) . "<br/>\n";
3404                                 }
3405                         }
3406                         print "</td>\n" .
3407                               "<td class=\"link\">" .
3408                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3409                               " | " .
3410                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3411                         print "</td>\n" .
3412                               "</tr>\n";
3413                 }
3414                 close $fd;
3415         }
3417         if ($pickaxe_search) {
3418                 $/ = "\n";
3419                 my $git_command = git_cmd_str();
3420                 open my $fd, "-|", "$git_command rev-list $hash | " .
3421                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3422                 undef %co;
3423                 my @files;
3424                 while (my $line = <$fd>) {
3425                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3426                                 my %set;
3427                                 $set{'file'} = $6;
3428                                 $set{'from_id'} = $3;
3429                                 $set{'to_id'} = $4;
3430                                 $set{'id'} = $set{'to_id'};
3431                                 if ($set{'id'} =~ m/0{40}/) {
3432                                         $set{'id'} = $set{'from_id'};
3433                                 }
3434                                 if ($set{'id'} =~ m/0{40}/) {
3435                                         next;
3436                                 }
3437                                 push @files, \%set;
3438                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3439                                 if (%co) {
3440                                         if ($alternate) {
3441                                                 print "<tr class=\"dark\">\n";
3442                                         } else {
3443                                                 print "<tr class=\"light\">\n";
3444                                         }
3445                                         $alternate ^= 1;
3446                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3447                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3448                                               "<td>" .
3449                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3450                                                       -class => "list subject"},
3451                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3452                                         while (my $setref = shift @files) {
3453                                                 my %set = %$setref;
3454                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3455                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3456                                                               -class => "list"},
3457                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3458                                                       "<br/>\n";
3459                                         }
3460                                         print "</td>\n" .
3461                                               "<td class=\"link\">" .
3462                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3463                                               " | " .
3464                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3465                                         print "</td>\n" .
3466                                               "</tr>\n";
3467                                 }
3468                                 %co = parse_commit($1);
3469                         }
3470                 }
3471                 close $fd;
3472         }
3473         print "</table>\n";
3474         git_footer_html();
3477 sub git_shortlog {
3478         my $head = git_get_head_hash($project);
3479         if (!defined $hash) {
3480                 $hash = $head;
3481         }
3482         if (!defined $page) {
3483                 $page = 0;
3484         }
3485         my $refs = git_get_references();
3487         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3488         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3489                 or die_error(undef, "Open git-rev-list failed");
3490         my @revlist = map { chomp; $_ } <$fd>;
3491         close $fd;
3493         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3494         my $next_link = '';
3495         if ($#revlist >= (100 * ($page+1)-1)) {
3496                 $next_link =
3497                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3498                                  -title => "Alt-n"}, "next");
3499         }
3502         git_header_html();
3503         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3504         git_print_header_div('summary', $project);
3506         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3508         git_footer_html();
3511 ## ......................................................................
3512 ## feeds (RSS, OPML)
3514 sub git_rss {
3515         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3516         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3517                 or die_error(undef, "Open git-rev-list failed");
3518         my @revlist = map { chomp; $_ } <$fd>;
3519         close $fd or die_error(undef, "Reading git-rev-list failed");
3520         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3521         print <<XML;
3522 <?xml version="1.0" encoding="utf-8"?>
3523 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3524 <channel>
3525 <title>$project $my_uri $my_url</title>
3526 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3527 <description>$project log</description>
3528 <language>en</language>
3529 XML
3531         for (my $i = 0; $i <= $#revlist; $i++) {
3532                 my $commit = $revlist[$i];
3533                 my %co = parse_commit($commit);
3534                 # we read 150, we always show 30 and the ones more recent than 48 hours
3535                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3536                         last;
3537                 }
3538                 my %cd = parse_date($co{'committer_epoch'});
3539                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3540                         $co{'parent'}, $co{'id'}
3541                         or next;
3542                 my @difftree = map { chomp; $_ } <$fd>;
3543                 close $fd
3544                         or next;
3545                 print "<item>\n" .
3546                       "<title>" .
3547                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3548                       "</title>\n" .
3549                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3550                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3551                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3552                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3553                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3554                       "<content:encoded>" .
3555                       "<![CDATA[\n";
3556                 my $comment = $co{'comment'};
3557                 foreach my $line (@$comment) {
3558                         $line = decode("utf8", $line, Encode::FB_DEFAULT);
3559                         print "$line<br/>\n";
3560                 }
3561                 print "<br/>\n";
3562                 foreach my $line (@difftree) {
3563                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3564                                 next;
3565                         }
3566                         my $file = esc_html(unquote($7));
3567                         $file = decode("utf8", $file, Encode::FB_DEFAULT);
3568                         print "$file<br/>\n";
3569                 }
3570                 print "]]>\n" .
3571                       "</content:encoded>\n" .
3572                       "</item>\n";
3573         }
3574         print "</channel></rss>";
3577 sub git_opml {
3578         my @list = git_get_projects_list();
3580         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3581         print <<XML;
3582 <?xml version="1.0" encoding="utf-8"?>
3583 <opml version="1.0">
3584 <head>
3585   <title>$site_name Git OPML Export</title>
3586 </head>
3587 <body>
3588 <outline text="git RSS feeds">
3589 XML
3591         foreach my $pr (@list) {
3592                 my %proj = %$pr;
3593                 my $head = git_get_head_hash($proj{'path'});
3594                 if (!defined $head) {
3595                         next;
3596                 }
3597                 $git_dir = "$projectroot/$proj{'path'}";
3598                 my %co = parse_commit($head);
3599                 if (!%co) {
3600                         next;
3601                 }
3603                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3604                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3605                 my $html = "$my_url?p=$proj{'path'};a=summary";
3606                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3607         }
3608         print <<XML;
3609 </outline>
3610 </body>
3611 </opml>
3612 XML