Code

gitweb: fix warnings in PATH_INFO code and add export_ok/strict_export
[git.git] / gitweb / gitweb.perl
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
4 #
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
7 #
8 # This program is licensed under the GPLv2
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
21 our $cgi = new CGI;
22 our $version = "++GIT_VERSION++";
23 our $my_url = $cgi->url();
24 our $my_uri = $cgi->url(-absolute => 1);
26 # core git executable to use
27 # this can just be "git" if your webserver has a sensible PATH
28 our $GIT = "++GIT_BINDIR++/git";
30 # absolute fs-path which will be prepended to the project path
31 #our $projectroot = "/pub/scm";
32 our $projectroot = "++GITWEB_PROJECTROOT++";
34 # target of the home link on top of all pages
35 our $home_link = $my_uri || "/";
37 # string of the home link on top of all pages
38 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
40 # name of your site or organization to appear in page titles
41 # replace this with something more descriptive for clearer bookmarks
42 our $site_name = "++GITWEB_SITENAME++" || $ENV{'SERVER_NAME'} || "Untitled";
44 # html text to include at home page
45 our $home_text = "++GITWEB_HOMETEXT++";
47 # URI of default stylesheet
48 our $stylesheet = "++GITWEB_CSS++";
49 # URI of GIT logo
50 our $logo = "++GITWEB_LOGO++";
51 # URI of GIT favicon, assumed to be image/png type
52 our $favicon = "++GITWEB_FAVICON++";
54 # source of projects list
55 our $projects_list = "++GITWEB_LIST++";
57 # show repository only if this file exists
58 # (only effective if this variable evaluates to true)
59 our $export_ok = "++GITWEB_EXPORT_OK++";
61 # only allow viewing of repositories also shown on the overview page
62 our $strict_export = "++GITWEB_STRICT_EXPORT++";
64 # list of git base URLs used for URL to where fetch project from,
65 # i.e. full URL is "$git_base_url/$project"
66 our @git_base_url_list = ("++GITWEB_BASE_URL++");
68 # default blob_plain mimetype and default charset for text/plain blob
69 our $default_blob_plain_mimetype = 'text/plain';
70 our $default_text_plain_charset  = undef;
72 # file to use for guessing MIME types before trying /etc/mime.types
73 # (relative to the current git repository)
74 our $mimetypes_file = undef;
76 # You define site-wide feature defaults here; override them with
77 # $GITWEB_CONFIG as necessary.
78 our %feature = (
79         # feature => {
80         #       'sub' => feature-sub (subroutine),
81         #       'override' => allow-override (boolean),
82         #       'default' => [ default options...] (array reference)}
83         #
84         # if feature is overridable (it means that allow-override has true value,
85         # then feature-sub will be called with default options as parameters;
86         # return value of feature-sub indicates if to enable specified feature
87         #
88         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
90         'blame' => {
91                 'sub' => \&feature_blame,
92                 'override' => 0,
93                 'default' => [0]},
95         'snapshot' => {
96                 'sub' => \&feature_snapshot,
97                 'override' => 0,
98                 #         => [content-encoding, suffix, program]
99                 'default' => ['x-gzip', 'gz', 'gzip']},
101         'pickaxe' => {
102                 'sub' => \&feature_pickaxe,
103                 'override' => 0,
104                 'default' => [1]},
105 );
107 sub gitweb_check_feature {
108         my ($name) = @_;
109         return undef unless exists $feature{$name};
110         my ($sub, $override, @defaults) = (
111                 $feature{$name}{'sub'},
112                 $feature{$name}{'override'},
113                 @{$feature{$name}{'default'}});
114         if (!$override) { return @defaults; }
115         return $sub->(@defaults);
118 # To enable system wide have in $GITWEB_CONFIG
119 # $feature{'blame'}{'default'} = [1];
120 # To have project specific config enable override in $GITWEB_CONFIG
121 # $feature{'blame'}{'override'} = 1;
122 # and in project config gitweb.blame = 0|1;
124 sub feature_blame {
125         my ($val) = git_get_project_config('blame', '--bool');
127         if ($val eq 'true') {
128                 return 1;
129         } elsif ($val eq 'false') {
130                 return 0;
131         }
133         return $_[0];
136 # To disable system wide have in $GITWEB_CONFIG
137 # $feature{'snapshot'}{'default'} = [undef];
138 # To have project specific config enable override in $GITWEB_CONFIG
139 # $feature{'blame'}{'override'} = 1;
140 # and in project config  gitweb.snapshot = none|gzip|bzip2
142 sub feature_snapshot {
143         my ($ctype, $suffix, $command) = @_;
145         my ($val) = git_get_project_config('snapshot');
147         if ($val eq 'gzip') {
148                 return ('x-gzip', 'gz', 'gzip');
149         } elsif ($val eq 'bzip2') {
150                 return ('x-bzip2', 'bz2', 'bzip2');
151         } elsif ($val eq 'none') {
152                 return ();
153         }
155         return ($ctype, $suffix, $command);
158 # To enable system wide have in $GITWEB_CONFIG
159 # $feature{'pickaxe'}{'default'} = [1];
160 # To have project specific config enable override in $GITWEB_CONFIG
161 # $feature{'pickaxe'}{'override'} = 1;
162 # and in project config gitweb.pickaxe = 0|1;
164 sub feature_pickaxe {
165         my ($val) = git_get_project_config('pickaxe', '--bool');
167         if ($val eq 'true') {
168                 return (1);
169         } elsif ($val eq 'false') {
170                 return (0);
171         }
173         return ($_[0]);
176 # rename detection options for git-diff and git-diff-tree
177 # - default is '-M', with the cost proportional to
178 #   (number of removed files) * (number of new files).
179 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
180 #   (number of changed files + number of removed files) * (number of new files)
181 # - even more costly is '-C', '--find-copies-harder' with cost
182 #   (number of files in the original tree) * (number of new files)
183 # - one might want to include '-B' option, e.g. '-B', '-M'
184 our @diff_opts = ('-M'); # taken from git_commit
186 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
187 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
189 # version of the core git binary
190 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
192 $projects_list ||= $projectroot;
194 # ======================================================================
195 # input validation and dispatch
196 our $action = $cgi->param('a');
197 if (defined $action) {
198         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
199                 die_error(undef, "Invalid action parameter");
200         }
203 our $project = $cgi->param('p');
204 if (defined $project) {
205         if (!validate_input($project) ||
206             !(-d "$projectroot/$project") ||
207             !(-e "$projectroot/$project/HEAD") ||
208             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
209             ($strict_export && !project_in_list($project))) {
210                 undef $project;
211                 die_error(undef, "No such project");
212         }
215 our $file_name = $cgi->param('f');
216 if (defined $file_name) {
217         if (!validate_input($file_name)) {
218                 die_error(undef, "Invalid file parameter");
219         }
222 our $file_parent = $cgi->param('fp');
223 if (defined $file_parent) {
224         if (!validate_input($file_parent)) {
225                 die_error(undef, "Invalid file parent parameter");
226         }
229 our $hash = $cgi->param('h');
230 if (defined $hash) {
231         if (!validate_input($hash)) {
232                 die_error(undef, "Invalid hash parameter");
233         }
236 our $hash_parent = $cgi->param('hp');
237 if (defined $hash_parent) {
238         if (!validate_input($hash_parent)) {
239                 die_error(undef, "Invalid hash parent parameter");
240         }
243 our $hash_base = $cgi->param('hb');
244 if (defined $hash_base) {
245         if (!validate_input($hash_base)) {
246                 die_error(undef, "Invalid hash base parameter");
247         }
250 our $hash_parent_base = $cgi->param('hpb');
251 if (defined $hash_parent_base) {
252         if (!validate_input($hash_parent_base)) {
253                 die_error(undef, "Invalid hash parent base parameter");
254         }
257 our $page = $cgi->param('pg');
258 if (defined $page) {
259         if ($page =~ m/[^0-9]$/) {
260                 die_error(undef, "Invalid page parameter");
261         }
264 our $searchtext = $cgi->param('s');
265 if (defined $searchtext) {
266         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
267                 die_error(undef, "Invalid search parameter");
268         }
269         $searchtext = quotemeta $searchtext;
272 # now read PATH_INFO and use it as alternative to parameters
273 sub evaluate_path_info {
274         return if defined $project;
275         my $path_info = $ENV{"PATH_INFO"};
276         return if !$path_info;
277         $path_info =~ s,(^/|/$),,gs;
278         $path_info = validate_input($path_info);
279         return if !$path_info;
280         $project = $path_info;
281         while ($project && !-e "$projectroot/$project/HEAD") {
282                 $project =~ s,/*[^/]*$,,;
283         }
284         if (!$project ||
285             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
286             ($strict_export && !project_in_list($project))) {
287                 undef $project;
288                 return;
289         }
290         # do not change any parameters if an action is given using the query string
291         return if $action;
292         if ($path_info =~ m,^$project/([^/]+)/(.+)$,) {
293                 # we got "project.git/branch/filename"
294                 $action    ||= "blob_plain";
295                 $hash_base ||= validate_input($1);
296                 $file_name ||= validate_input($2);
297         } elsif ($path_info =~ m,^$project/([^/]+)$,) {
298                 # we got "project.git/branch"
299                 $action ||= "shortlog";
300                 $hash   ||= validate_input($1);
301         }
303 evaluate_path_info();
305 # path to the current git repository
306 our $git_dir;
307 $git_dir = "$projectroot/$project" if $project;
309 # dispatch
310 my %actions = (
311         "blame" => \&git_blame2,
312         "blobdiff" => \&git_blobdiff,
313         "blobdiff_plain" => \&git_blobdiff_plain,
314         "blob" => \&git_blob,
315         "blob_plain" => \&git_blob_plain,
316         "commitdiff" => \&git_commitdiff,
317         "commitdiff_plain" => \&git_commitdiff_plain,
318         "commit" => \&git_commit,
319         "heads" => \&git_heads,
320         "history" => \&git_history,
321         "log" => \&git_log,
322         "rss" => \&git_rss,
323         "search" => \&git_search,
324         "shortlog" => \&git_shortlog,
325         "summary" => \&git_summary,
326         "tag" => \&git_tag,
327         "tags" => \&git_tags,
328         "tree" => \&git_tree,
329         "snapshot" => \&git_snapshot,
330         # those below don't need $project
331         "opml" => \&git_opml,
332         "project_list" => \&git_project_list,
333         "project_index" => \&git_project_index,
334 );
336 if (defined $project) {
337         $action ||= 'summary';
338 } else {
339         $action ||= 'project_list';
341 if (!defined($actions{$action})) {
342         die_error(undef, "Unknown action");
344 $actions{$action}->();
345 exit;
347 ## ======================================================================
348 ## action links
350 sub href(%) {
351         my %params = @_;
353         my @mapping = (
354                 project => "p",
355                 action => "a",
356                 file_name => "f",
357                 file_parent => "fp",
358                 hash => "h",
359                 hash_parent => "hp",
360                 hash_base => "hb",
361                 hash_parent_base => "hpb",
362                 page => "pg",
363                 order => "o",
364                 searchtext => "s",
365         );
366         my %mapping = @mapping;
368         $params{'project'} = $project unless exists $params{'project'};
370         my @result = ();
371         for (my $i = 0; $i < @mapping; $i += 2) {
372                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
373                 if (defined $params{$name}) {
374                         push @result, $symbol . "=" . esc_param($params{$name});
375                 }
376         }
377         return "$my_uri?" . join(';', @result);
381 ## ======================================================================
382 ## validation, quoting/unquoting and escaping
384 sub validate_input {
385         my $input = shift;
387         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
388                 return $input;
389         }
390         if ($input =~ m/(^|\/)(|\.|\.\.)($|\/)/) {
391                 return undef;
392         }
393         if ($input =~ m/[^a-zA-Z0-9_\x80-\xff\ \t\.\/\-\+\#\~\%]/) {
394                 return undef;
395         }
396         return $input;
399 # quote unsafe chars, but keep the slash, even when it's not
400 # correct, but quoted slashes look too horrible in bookmarks
401 sub esc_param {
402         my $str = shift;
403         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
404         $str =~ s/\+/%2B/g;
405         $str =~ s/ /\+/g;
406         return $str;
409 # replace invalid utf8 character with SUBSTITUTION sequence
410 sub esc_html {
411         my $str = shift;
412         $str = decode("utf8", $str, Encode::FB_DEFAULT);
413         $str = escapeHTML($str);
414         $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
415         return $str;
418 # git may return quoted and escaped filenames
419 sub unquote {
420         my $str = shift;
421         if ($str =~ m/^"(.*)"$/) {
422                 $str = $1;
423                 $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
424         }
425         return $str;
428 # escape tabs (convert tabs to spaces)
429 sub untabify {
430         my $line = shift;
432         while ((my $pos = index($line, "\t")) != -1) {
433                 if (my $count = (8 - ($pos % 8))) {
434                         my $spaces = ' ' x $count;
435                         $line =~ s/\t/$spaces/;
436                 }
437         }
439         return $line;
442 sub project_in_list {
443         my $project = shift;
444         my @list = git_get_projects_list();
445         return @list && scalar(grep { $_->{'path'} eq $project } @list);
448 ## ----------------------------------------------------------------------
449 ## HTML aware string manipulation
451 sub chop_str {
452         my $str = shift;
453         my $len = shift;
454         my $add_len = shift || 10;
456         # allow only $len chars, but don't cut a word if it would fit in $add_len
457         # if it doesn't fit, cut it if it's still longer than the dots we would add
458         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
459         my $body = $1;
460         my $tail = $2;
461         if (length($tail) > 4) {
462                 $tail = " ...";
463                 $body =~ s/&[^;]*$//; # remove chopped character entities
464         }
465         return "$body$tail";
468 ## ----------------------------------------------------------------------
469 ## functions returning short strings
471 # CSS class for given age value (in seconds)
472 sub age_class {
473         my $age = shift;
475         if ($age < 60*60*2) {
476                 return "age0";
477         } elsif ($age < 60*60*24*2) {
478                 return "age1";
479         } else {
480                 return "age2";
481         }
484 # convert age in seconds to "nn units ago" string
485 sub age_string {
486         my $age = shift;
487         my $age_str;
489         if ($age > 60*60*24*365*2) {
490                 $age_str = (int $age/60/60/24/365);
491                 $age_str .= " years ago";
492         } elsif ($age > 60*60*24*(365/12)*2) {
493                 $age_str = int $age/60/60/24/(365/12);
494                 $age_str .= " months ago";
495         } elsif ($age > 60*60*24*7*2) {
496                 $age_str = int $age/60/60/24/7;
497                 $age_str .= " weeks ago";
498         } elsif ($age > 60*60*24*2) {
499                 $age_str = int $age/60/60/24;
500                 $age_str .= " days ago";
501         } elsif ($age > 60*60*2) {
502                 $age_str = int $age/60/60;
503                 $age_str .= " hours ago";
504         } elsif ($age > 60*2) {
505                 $age_str = int $age/60;
506                 $age_str .= " min ago";
507         } elsif ($age > 2) {
508                 $age_str = int $age;
509                 $age_str .= " sec ago";
510         } else {
511                 $age_str .= " right now";
512         }
513         return $age_str;
516 # convert file mode in octal to symbolic file mode string
517 sub mode_str {
518         my $mode = oct shift;
520         if (S_ISDIR($mode & S_IFMT)) {
521                 return 'drwxr-xr-x';
522         } elsif (S_ISLNK($mode)) {
523                 return 'lrwxrwxrwx';
524         } elsif (S_ISREG($mode)) {
525                 # git cares only about the executable bit
526                 if ($mode & S_IXUSR) {
527                         return '-rwxr-xr-x';
528                 } else {
529                         return '-rw-r--r--';
530                 };
531         } else {
532                 return '----------';
533         }
536 # convert file mode in octal to file type string
537 sub file_type {
538         my $mode = shift;
540         if ($mode !~ m/^[0-7]+$/) {
541                 return $mode;
542         } else {
543                 $mode = oct $mode;
544         }
546         if (S_ISDIR($mode & S_IFMT)) {
547                 return "directory";
548         } elsif (S_ISLNK($mode)) {
549                 return "symlink";
550         } elsif (S_ISREG($mode)) {
551                 return "file";
552         } else {
553                 return "unknown";
554         }
557 ## ----------------------------------------------------------------------
558 ## functions returning short HTML fragments, or transforming HTML fragments
559 ## which don't beling to other sections
561 # format line of commit message or tag comment
562 sub format_log_line_html {
563         my $line = shift;
565         $line = esc_html($line);
566         $line =~ s/ /&nbsp;/g;
567         if ($line =~ m/([0-9a-fA-F]{40})/) {
568                 my $hash_text = $1;
569                 if (git_get_type($hash_text) eq "commit") {
570                         my $link =
571                                 $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
572                                         -class => "text"}, $hash_text);
573                         $line =~ s/$hash_text/$link/;
574                 }
575         }
576         return $line;
579 # format marker of refs pointing to given object
580 sub format_ref_marker {
581         my ($refs, $id) = @_;
582         my $markers = '';
584         if (defined $refs->{$id}) {
585                 foreach my $ref (@{$refs->{$id}}) {
586                         my ($type, $name) = qw();
587                         # e.g. tags/v2.6.11 or heads/next
588                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
589                                 $type = $1;
590                                 $name = $2;
591                         } else {
592                                 $type = "ref";
593                                 $name = $ref;
594                         }
596                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
597                 }
598         }
600         if ($markers) {
601                 return ' <span class="refs">'. $markers . '</span>';
602         } else {
603                 return "";
604         }
607 # format, perhaps shortened and with markers, title line
608 sub format_subject_html {
609         my ($long, $short, $href, $extra) = @_;
610         $extra = '' unless defined($extra);
612         if (length($short) < length($long)) {
613                 return $cgi->a({-href => $href, -class => "list subject",
614                                 -title => $long},
615                        esc_html($short) . $extra);
616         } else {
617                 return $cgi->a({-href => $href, -class => "list subject"},
618                        esc_html($long)  . $extra);
619         }
622 sub format_diff_line {
623         my $line = shift;
624         my $char = substr($line, 0, 1);
625         my $diff_class = "";
627         chomp $line;
629         if ($char eq '+') {
630                 $diff_class = " add";
631         } elsif ($char eq "-") {
632                 $diff_class = " rem";
633         } elsif ($char eq "@") {
634                 $diff_class = " chunk_header";
635         } elsif ($char eq "\\") {
636                 $diff_class = " incomplete";
637         }
638         $line = untabify($line);
639         return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
642 ## ----------------------------------------------------------------------
643 ## git utility subroutines, invoking git commands
645 # returns path to the core git executable and the --git-dir parameter as list
646 sub git_cmd {
647         return $GIT, '--git-dir='.$git_dir;
650 # returns path to the core git executable and the --git-dir parameter as string
651 sub git_cmd_str {
652         return join(' ', git_cmd());
655 # get HEAD ref of given project as hash
656 sub git_get_head_hash {
657         my $project = shift;
658         my $o_git_dir = $git_dir;
659         my $retval = undef;
660         $git_dir = "$projectroot/$project";
661         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
662                 my $head = <$fd>;
663                 close $fd;
664                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
665                         $retval = $1;
666                 }
667         }
668         if (defined $o_git_dir) {
669                 $git_dir = $o_git_dir;
670         }
671         return $retval;
674 # get type of given object
675 sub git_get_type {
676         my $hash = shift;
678         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
679         my $type = <$fd>;
680         close $fd or return;
681         chomp $type;
682         return $type;
685 sub git_get_project_config {
686         my ($key, $type) = @_;
688         return unless ($key);
689         $key =~ s/^gitweb\.//;
690         return if ($key =~ m/\W/);
692         my @x = (git_cmd(), 'repo-config');
693         if (defined $type) { push @x, $type; }
694         push @x, "--get";
695         push @x, "gitweb.$key";
696         my $val = qx(@x);
697         chomp $val;
698         return ($val);
701 # get hash of given path at given ref
702 sub git_get_hash_by_path {
703         my $base = shift;
704         my $path = shift || return undef;
706         my $tree = $base;
708         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
709                 or die_error(undef, "Open git-ls-tree failed");
710         my $line = <$fd>;
711         close $fd or return undef;
713         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
714         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
715         return $3;
718 ## ......................................................................
719 ## git utility functions, directly accessing git repository
721 sub git_get_project_description {
722         my $path = shift;
724         open my $fd, "$projectroot/$path/description" or return undef;
725         my $descr = <$fd>;
726         close $fd;
727         chomp $descr;
728         return $descr;
731 sub git_get_project_url_list {
732         my $path = shift;
734         open my $fd, "$projectroot/$path/cloneurl" or return undef;
735         my @git_project_url_list = map { chomp; $_ } <$fd>;
736         close $fd;
738         return wantarray ? @git_project_url_list : \@git_project_url_list;
741 sub git_get_projects_list {
742         my @list;
744         if (-d $projects_list) {
745                 # search in directory
746                 my $dir = $projects_list;
747                 my $pfxlen = length("$dir");
749                 File::Find::find({
750                         follow_fast => 1, # follow symbolic links
751                         dangling_symlinks => 0, # ignore dangling symlinks, silently
752                         wanted => sub {
753                                 # skip project-list toplevel, if we get it.
754                                 return if (m!^[/.]$!);
755                                 # only directories can be git repositories
756                                 return unless (-d $_);
758                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
759                                 # we check related file in $projectroot
760                                 if (-e "$projectroot/$subdir/HEAD" && (!$export_ok ||
761                                     -e "$projectroot/$subdir/$export_ok")) {
762                                         push @list, { path => $subdir };
763                                         $File::Find::prune = 1;
764                                 }
765                         },
766                 }, "$dir");
768         } elsif (-f $projects_list) {
769                 # read from file(url-encoded):
770                 # 'git%2Fgit.git Linus+Torvalds'
771                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
772                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
773                 open my ($fd), $projects_list or return undef;
774                 while (my $line = <$fd>) {
775                         chomp $line;
776                         my ($path, $owner) = split ' ', $line;
777                         $path = unescape($path);
778                         $owner = unescape($owner);
779                         if (!defined $path) {
780                                 next;
781                         }
782                         if (-e "$projectroot/$path/HEAD" && (!$export_ok ||
783                             -e "$projectroot/$path/$export_ok")) {
784                                 my $pr = {
785                                         path => $path,
786                                         owner => decode("utf8", $owner, Encode::FB_DEFAULT),
787                                 };
788                                 push @list, $pr
789                         }
790                 }
791                 close $fd;
792         }
793         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
794         return @list;
797 sub git_get_project_owner {
798         my $project = shift;
799         my $owner;
801         return undef unless $project;
803         # read from file (url-encoded):
804         # 'git%2Fgit.git Linus+Torvalds'
805         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
806         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
807         if (-f $projects_list) {
808                 open (my $fd , $projects_list);
809                 while (my $line = <$fd>) {
810                         chomp $line;
811                         my ($pr, $ow) = split ' ', $line;
812                         $pr = unescape($pr);
813                         $ow = unescape($ow);
814                         if ($pr eq $project) {
815                                 $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
816                                 last;
817                         }
818                 }
819                 close $fd;
820         }
821         if (!defined $owner) {
822                 $owner = get_file_owner("$projectroot/$project");
823         }
825         return $owner;
828 sub git_get_references {
829         my $type = shift || "";
830         my %refs;
831         my $fd;
832         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
833         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
834         if (-f "$projectroot/$project/info/refs") {
835                 open $fd, "$projectroot/$project/info/refs"
836                         or return;
837         } else {
838                 open $fd, "-|", git_cmd(), "ls-remote", "."
839                         or return;
840         }
842         while (my $line = <$fd>) {
843                 chomp $line;
844                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
845                         if (defined $refs{$1}) {
846                                 push @{$refs{$1}}, $2;
847                         } else {
848                                 $refs{$1} = [ $2 ];
849                         }
850                 }
851         }
852         close $fd or return;
853         return \%refs;
856 sub git_get_rev_name_tags {
857         my $hash = shift || return undef;
859         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
860                 or return;
861         my $name_rev = <$fd>;
862         close $fd;
864         if ($name_rev =~ m|^$hash tags/(.*)$|) {
865                 return $1;
866         } else {
867                 # catches also '$hash undefined' output
868                 return undef;
869         }
872 ## ----------------------------------------------------------------------
873 ## parse to hash functions
875 sub parse_date {
876         my $epoch = shift;
877         my $tz = shift || "-0000";
879         my %date;
880         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
881         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
882         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
883         $date{'hour'} = $hour;
884         $date{'minute'} = $min;
885         $date{'mday'} = $mday;
886         $date{'day'} = $days[$wday];
887         $date{'month'} = $months[$mon];
888         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
889                            $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
890         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
891                              $mday, $months[$mon], $hour ,$min;
893         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
894         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
895         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
896         $date{'hour_local'} = $hour;
897         $date{'minute_local'} = $min;
898         $date{'tz_local'} = $tz;
899         return %date;
902 sub parse_tag {
903         my $tag_id = shift;
904         my %tag;
905         my @comment;
907         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
908         $tag{'id'} = $tag_id;
909         while (my $line = <$fd>) {
910                 chomp $line;
911                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
912                         $tag{'object'} = $1;
913                 } elsif ($line =~ m/^type (.+)$/) {
914                         $tag{'type'} = $1;
915                 } elsif ($line =~ m/^tag (.+)$/) {
916                         $tag{'name'} = $1;
917                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
918                         $tag{'author'} = $1;
919                         $tag{'epoch'} = $2;
920                         $tag{'tz'} = $3;
921                 } elsif ($line =~ m/--BEGIN/) {
922                         push @comment, $line;
923                         last;
924                 } elsif ($line eq "") {
925                         last;
926                 }
927         }
928         push @comment, <$fd>;
929         $tag{'comment'} = \@comment;
930         close $fd or return;
931         if (!defined $tag{'name'}) {
932                 return
933         };
934         return %tag
937 sub parse_commit {
938         my $commit_id = shift;
939         my $commit_text = shift;
941         my @commit_lines;
942         my %co;
944         if (defined $commit_text) {
945                 @commit_lines = @$commit_text;
946         } else {
947                 $/ = "\0";
948                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
949                         or return;
950                 @commit_lines = split '\n', <$fd>;
951                 close $fd or return;
952                 $/ = "\n";
953                 pop @commit_lines;
954         }
955         my $header = shift @commit_lines;
956         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
957                 return;
958         }
959         ($co{'id'}, my @parents) = split ' ', $header;
960         $co{'parents'} = \@parents;
961         $co{'parent'} = $parents[0];
962         while (my $line = shift @commit_lines) {
963                 last if $line eq "\n";
964                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
965                         $co{'tree'} = $1;
966                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
967                         $co{'author'} = $1;
968                         $co{'author_epoch'} = $2;
969                         $co{'author_tz'} = $3;
970                         if ($co{'author'} =~ m/^([^<]+) </) {
971                                 $co{'author_name'} = $1;
972                         } else {
973                                 $co{'author_name'} = $co{'author'};
974                         }
975                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
976                         $co{'committer'} = $1;
977                         $co{'committer_epoch'} = $2;
978                         $co{'committer_tz'} = $3;
979                         $co{'committer_name'} = $co{'committer'};
980                         $co{'committer_name'} =~ s/ <.*//;
981                 }
982         }
983         if (!defined $co{'tree'}) {
984                 return;
985         };
987         foreach my $title (@commit_lines) {
988                 $title =~ s/^    //;
989                 if ($title ne "") {
990                         $co{'title'} = chop_str($title, 80, 5);
991                         # remove leading stuff of merges to make the interesting part visible
992                         if (length($title) > 50) {
993                                 $title =~ s/^Automatic //;
994                                 $title =~ s/^merge (of|with) /Merge ... /i;
995                                 if (length($title) > 50) {
996                                         $title =~ s/(http|rsync):\/\///;
997                                 }
998                                 if (length($title) > 50) {
999                                         $title =~ s/(master|www|rsync)\.//;
1000                                 }
1001                                 if (length($title) > 50) {
1002                                         $title =~ s/kernel.org:?//;
1003                                 }
1004                                 if (length($title) > 50) {
1005                                         $title =~ s/\/pub\/scm//;
1006                                 }
1007                         }
1008                         $co{'title_short'} = chop_str($title, 50, 5);
1009                         last;
1010                 }
1011         }
1012         # remove added spaces
1013         foreach my $line (@commit_lines) {
1014                 $line =~ s/^    //;
1015         }
1016         $co{'comment'} = \@commit_lines;
1018         my $age = time - $co{'committer_epoch'};
1019         $co{'age'} = $age;
1020         $co{'age_string'} = age_string($age);
1021         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1022         if ($age > 60*60*24*7*2) {
1023                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1024                 $co{'age_string_age'} = $co{'age_string'};
1025         } else {
1026                 $co{'age_string_date'} = $co{'age_string'};
1027                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1028         }
1029         return %co;
1032 # parse ref from ref_file, given by ref_id, with given type
1033 sub parse_ref {
1034         my $ref_file = shift;
1035         my $ref_id = shift;
1036         my $type = shift || git_get_type($ref_id);
1037         my %ref_item;
1039         $ref_item{'type'} = $type;
1040         $ref_item{'id'} = $ref_id;
1041         $ref_item{'epoch'} = 0;
1042         $ref_item{'age'} = "unknown";
1043         if ($type eq "tag") {
1044                 my %tag = parse_tag($ref_id);
1045                 $ref_item{'comment'} = $tag{'comment'};
1046                 if ($tag{'type'} eq "commit") {
1047                         my %co = parse_commit($tag{'object'});
1048                         $ref_item{'epoch'} = $co{'committer_epoch'};
1049                         $ref_item{'age'} = $co{'age_string'};
1050                 } elsif (defined($tag{'epoch'})) {
1051                         my $age = time - $tag{'epoch'};
1052                         $ref_item{'epoch'} = $tag{'epoch'};
1053                         $ref_item{'age'} = age_string($age);
1054                 }
1055                 $ref_item{'reftype'} = $tag{'type'};
1056                 $ref_item{'name'} = $tag{'name'};
1057                 $ref_item{'refid'} = $tag{'object'};
1058         } elsif ($type eq "commit"){
1059                 my %co = parse_commit($ref_id);
1060                 $ref_item{'reftype'} = "commit";
1061                 $ref_item{'name'} = $ref_file;
1062                 $ref_item{'title'} = $co{'title'};
1063                 $ref_item{'refid'} = $ref_id;
1064                 $ref_item{'epoch'} = $co{'committer_epoch'};
1065                 $ref_item{'age'} = $co{'age_string'};
1066         } else {
1067                 $ref_item{'reftype'} = $type;
1068                 $ref_item{'name'} = $ref_file;
1069                 $ref_item{'refid'} = $ref_id;
1070         }
1072         return %ref_item;
1075 # parse line of git-diff-tree "raw" output
1076 sub parse_difftree_raw_line {
1077         my $line = shift;
1078         my %res;
1080         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1081         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1082         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1083                 $res{'from_mode'} = $1;
1084                 $res{'to_mode'} = $2;
1085                 $res{'from_id'} = $3;
1086                 $res{'to_id'} = $4;
1087                 $res{'status'} = $5;
1088                 $res{'similarity'} = $6;
1089                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1090                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1091                 } else {
1092                         $res{'file'} = unquote($7);
1093                 }
1094         }
1095         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1096         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1097                 $res{'commit'} = $1;
1098         }
1100         return wantarray ? %res : \%res;
1103 # parse line of git-ls-tree output
1104 sub parse_ls_tree_line ($;%) {
1105         my $line = shift;
1106         my %opts = @_;
1107         my %res;
1109         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1110         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1112         $res{'mode'} = $1;
1113         $res{'type'} = $2;
1114         $res{'hash'} = $3;
1115         if ($opts{'-z'}) {
1116                 $res{'name'} = $4;
1117         } else {
1118                 $res{'name'} = unquote($4);
1119         }
1121         return wantarray ? %res : \%res;
1124 ## ......................................................................
1125 ## parse to array of hashes functions
1127 sub git_get_refs_list {
1128         my $ref_dir = shift;
1129         my @reflist;
1131         my @refs;
1132         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1133                 or return;
1134         while (my $line = <$fd>) {
1135                 chomp $line;
1136                 if ($line =~ m/^([0-9a-fA-F]{40})\t$ref_dir\/?([^\^]+)$/) {
1137                         push @refs, { hash => $1, name => $2 };
1138                 } elsif ($line =~ m/^[0-9a-fA-F]{40}\t$ref_dir\/?(.*)\^\{\}$/ &&
1139                          $1 eq $refs[-1]{'name'}) {
1140                         # most likely a tag is followed by its peeled
1141                         # (deref) one, and when that happens we know the
1142                         # previous one was of type 'tag'.
1143                         $refs[-1]{'type'} = "tag";
1144                 }
1145         }
1146         close $fd;
1148         foreach my $ref (@refs) {
1149                 my $ref_file = $ref->{'name'};
1150                 my $ref_id   = $ref->{'hash'};
1152                 my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1153                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
1155                 push @reflist, \%ref_item;
1156         }
1157         # sort refs by age
1158         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1159         return \@reflist;
1162 ## ----------------------------------------------------------------------
1163 ## filesystem-related functions
1165 sub get_file_owner {
1166         my $path = shift;
1168         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1169         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1170         if (!defined $gcos) {
1171                 return undef;
1172         }
1173         my $owner = $gcos;
1174         $owner =~ s/[,;].*$//;
1175         return decode("utf8", $owner, Encode::FB_DEFAULT);
1178 ## ......................................................................
1179 ## mimetype related functions
1181 sub mimetype_guess_file {
1182         my $filename = shift;
1183         my $mimemap = shift;
1184         -r $mimemap or return undef;
1186         my %mimemap;
1187         open(MIME, $mimemap) or return undef;
1188         while (<MIME>) {
1189                 next if m/^#/; # skip comments
1190                 my ($mime, $exts) = split(/\t+/);
1191                 if (defined $exts) {
1192                         my @exts = split(/\s+/, $exts);
1193                         foreach my $ext (@exts) {
1194                                 $mimemap{$ext} = $mime;
1195                         }
1196                 }
1197         }
1198         close(MIME);
1200         $filename =~ /\.(.*?)$/;
1201         return $mimemap{$1};
1204 sub mimetype_guess {
1205         my $filename = shift;
1206         my $mime;
1207         $filename =~ /\./ or return undef;
1209         if ($mimetypes_file) {
1210                 my $file = $mimetypes_file;
1211                 if ($file !~ m!^/!) { # if it is relative path
1212                         # it is relative to project
1213                         $file = "$projectroot/$project/$file";
1214                 }
1215                 $mime = mimetype_guess_file($filename, $file);
1216         }
1217         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1218         return $mime;
1221 sub blob_mimetype {
1222         my $fd = shift;
1223         my $filename = shift;
1225         if ($filename) {
1226                 my $mime = mimetype_guess($filename);
1227                 $mime and return $mime;
1228         }
1230         # just in case
1231         return $default_blob_plain_mimetype unless $fd;
1233         if (-T $fd) {
1234                 return 'text/plain' .
1235                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1236         } elsif (! $filename) {
1237                 return 'application/octet-stream';
1238         } elsif ($filename =~ m/\.png$/i) {
1239                 return 'image/png';
1240         } elsif ($filename =~ m/\.gif$/i) {
1241                 return 'image/gif';
1242         } elsif ($filename =~ m/\.jpe?g$/i) {
1243                 return 'image/jpeg';
1244         } else {
1245                 return 'application/octet-stream';
1246         }
1249 ## ======================================================================
1250 ## functions printing HTML: header, footer, error page
1252 sub git_header_html {
1253         my $status = shift || "200 OK";
1254         my $expires = shift;
1256         my $title = "$site_name git";
1257         if (defined $project) {
1258                 $title .= " - $project";
1259                 if (defined $action) {
1260                         $title .= "/$action";
1261                         if (defined $file_name) {
1262                                 $title .= " - $file_name";
1263                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1264                                         $title .= "/";
1265                                 }
1266                         }
1267                 }
1268         }
1269         my $content_type;
1270         # require explicit support from the UA if we are to send the page as
1271         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1272         # we have to do this because MSIE sometimes globs '*/*', pretending to
1273         # support xhtml+xml but choking when it gets what it asked for.
1274         if (defined $cgi->http('HTTP_ACCEPT') &&
1275             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1276             $cgi->Accept('application/xhtml+xml') != 0) {
1277                 $content_type = 'application/xhtml+xml';
1278         } else {
1279                 $content_type = 'text/html';
1280         }
1281         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1282                            -status=> $status, -expires => $expires);
1283         print <<EOF;
1284 <?xml version="1.0" encoding="utf-8"?>
1285 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1286 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1287 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1288 <!-- git core binaries version $git_version -->
1289 <head>
1290 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1291 <meta name="generator" content="gitweb/$version git/$git_version"/>
1292 <meta name="robots" content="index, nofollow"/>
1293 <title>$title</title>
1294 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1295 EOF
1296         if (defined $project) {
1297                 printf('<link rel="alternate" title="%s log" '.
1298                        'href="%s" type="application/rss+xml"/>'."\n",
1299                        esc_param($project), href(action=>"rss"));
1300         } else {
1301                 printf('<link rel="alternate" title="%s projects list" '.
1302                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1303                        $site_name, href(project=>undef, action=>"project_index"));
1304                 printf('<link rel="alternate" title="%s projects logs" '.
1305                        'href="%s" type="text/x-opml"/>'."\n",
1306                        $site_name, href(project=>undef, action=>"opml"));
1307         }
1308         if (defined $favicon) {
1309                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1310         }
1312         print "</head>\n" .
1313               "<body>\n" .
1314               "<div class=\"page_header\">\n" .
1315               "<a href=\"http://www.kernel.org/pub/software/scm/git/docs/\" title=\"git documentation\">" .
1316               "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1317               "</a>\n";
1318         print $cgi->a({-href => esc_param($home_link)}, $home_link_str) . " / ";
1319         if (defined $project) {
1320                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1321                 if (defined $action) {
1322                         print " / $action";
1323                 }
1324                 print "\n";
1325                 if (!defined $searchtext) {
1326                         $searchtext = "";
1327                 }
1328                 my $search_hash;
1329                 if (defined $hash_base) {
1330                         $search_hash = $hash_base;
1331                 } elsif (defined $hash) {
1332                         $search_hash = $hash;
1333                 } else {
1334                         $search_hash = "HEAD";
1335                 }
1336                 $cgi->param("a", "search");
1337                 $cgi->param("h", $search_hash);
1338                 print $cgi->startform(-method => "get", -action => $my_uri) .
1339                       "<div class=\"search\">\n" .
1340                       $cgi->hidden(-name => "p") . "\n" .
1341                       $cgi->hidden(-name => "a") . "\n" .
1342                       $cgi->hidden(-name => "h") . "\n" .
1343                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1344                       "</div>" .
1345                       $cgi->end_form() . "\n";
1346         }
1347         print "</div>\n";
1350 sub git_footer_html {
1351         print "<div class=\"page_footer\">\n";
1352         if (defined $project) {
1353                 my $descr = git_get_project_description($project);
1354                 if (defined $descr) {
1355                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1356                 }
1357                 print $cgi->a({-href => href(action=>"rss"),
1358                               -class => "rss_logo"}, "RSS") . "\n";
1359         } else {
1360                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1361                               -class => "rss_logo"}, "OPML") . " ";
1362                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1363                               -class => "rss_logo"}, "TXT") . "\n";
1364         }
1365         print "</div>\n" .
1366               "</body>\n" .
1367               "</html>";
1370 sub die_error {
1371         my $status = shift || "403 Forbidden";
1372         my $error = shift || "Malformed query, file missing or permission denied";
1374         git_header_html($status);
1375         print <<EOF;
1376 <div class="page_body">
1377 <br /><br />
1378 $status - $error
1379 <br />
1380 </div>
1381 EOF
1382         git_footer_html();
1383         exit;
1386 ## ----------------------------------------------------------------------
1387 ## functions printing or outputting HTML: navigation
1389 sub git_print_page_nav {
1390         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1391         $extra = '' if !defined $extra; # pager or formats
1393         my @navs = qw(summary shortlog log commit commitdiff tree);
1394         if ($suppress) {
1395                 @navs = grep { $_ ne $suppress } @navs;
1396         }
1398         my %arg = map { $_ => {action=>$_} } @navs;
1399         if (defined $head) {
1400                 for (qw(commit commitdiff)) {
1401                         $arg{$_}{hash} = $head;
1402                 }
1403                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1404                         for (qw(shortlog log)) {
1405                                 $arg{$_}{hash} = $head;
1406                         }
1407                 }
1408         }
1409         $arg{tree}{hash} = $treehead if defined $treehead;
1410         $arg{tree}{hash_base} = $treebase if defined $treebase;
1412         print "<div class=\"page_nav\">\n" .
1413                 (join " | ",
1414                  map { $_ eq $current ?
1415                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1416                  } @navs);
1417         print "<br/>\n$extra<br/>\n" .
1418               "</div>\n";
1421 sub format_paging_nav {
1422         my ($action, $hash, $head, $page, $nrevs) = @_;
1423         my $paging_nav;
1426         if ($hash ne $head || $page) {
1427                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1428         } else {
1429                 $paging_nav .= "HEAD";
1430         }
1432         if ($page > 0) {
1433                 $paging_nav .= " &sdot; " .
1434                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1435                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1436         } else {
1437                 $paging_nav .= " &sdot; prev";
1438         }
1440         if ($nrevs >= (100 * ($page+1)-1)) {
1441                 $paging_nav .= " &sdot; " .
1442                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1443                                  -accesskey => "n", -title => "Alt-n"}, "next");
1444         } else {
1445                 $paging_nav .= " &sdot; next";
1446         }
1448         return $paging_nav;
1451 ## ......................................................................
1452 ## functions printing or outputting HTML: div
1454 sub git_print_header_div {
1455         my ($action, $title, $hash, $hash_base) = @_;
1456         my %args = ();
1458         $args{action} = $action;
1459         $args{hash} = $hash if $hash;
1460         $args{hash_base} = $hash_base if $hash_base;
1462         print "<div class=\"header\">\n" .
1463               $cgi->a({-href => href(%args), -class => "title"},
1464               $title ? $title : $action) .
1465               "\n</div>\n";
1468 #sub git_print_authorship (\%) {
1469 sub git_print_authorship {
1470         my $co = shift;
1472         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1473         print "<div class=\"author_date\">" .
1474               esc_html($co->{'author_name'}) .
1475               " [$ad{'rfc2822'}";
1476         if ($ad{'hour_local'} < 6) {
1477                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1478                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1479         } else {
1480                 printf(" (%02d:%02d %s)",
1481                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1482         }
1483         print "]</div>\n";
1486 sub git_print_page_path {
1487         my $name = shift;
1488         my $type = shift;
1489         my $hb = shift;
1491         if (!defined $name) {
1492                 print "<div class=\"page_path\">/</div>\n";
1493         } else {
1494                 my @dirname = split '/', $name;
1495                 my $basename = pop @dirname;
1496                 my $fullname = '';
1498                 print "<div class=\"page_path\">";
1499                 foreach my $dir (@dirname) {
1500                         $fullname .= $dir . '/';
1501                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1502                                                      hash_base=>$hb),
1503                                       -title => $fullname}, esc_html($dir));
1504                         print "/";
1505                 }
1506                 if (defined $type && $type eq 'blob') {
1507                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1508                                                      hash_base=>$hb),
1509                                       -title => $name}, esc_html($basename));
1510                 } elsif (defined $type && $type eq 'tree') {
1511                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1512                                                      hash_base=>$hb),
1513                                       -title => $name}, esc_html($basename));
1514                         print "/";
1515                 } else {
1516                         print esc_html($basename);
1517                 }
1518                 print "<br/></div>\n";
1519         }
1522 # sub git_print_log (\@;%) {
1523 sub git_print_log ($;%) {
1524         my $log = shift;
1525         my %opts = @_;
1527         if ($opts{'-remove_title'}) {
1528                 # remove title, i.e. first line of log
1529                 shift @$log;
1530         }
1531         # remove leading empty lines
1532         while (defined $log->[0] && $log->[0] eq "") {
1533                 shift @$log;
1534         }
1536         # print log
1537         my $signoff = 0;
1538         my $empty = 0;
1539         foreach my $line (@$log) {
1540                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1541                         $signoff = 1;
1542                         $empty = 0;
1543                         if (! $opts{'-remove_signoff'}) {
1544                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1545                                 next;
1546                         } else {
1547                                 # remove signoff lines
1548                                 next;
1549                         }
1550                 } else {
1551                         $signoff = 0;
1552                 }
1554                 # print only one empty line
1555                 # do not print empty line after signoff
1556                 if ($line eq "") {
1557                         next if ($empty || $signoff);
1558                         $empty = 1;
1559                 } else {
1560                         $empty = 0;
1561                 }
1563                 print format_log_line_html($line) . "<br/>\n";
1564         }
1566         if ($opts{'-final_empty_line'}) {
1567                 # end with single empty line
1568                 print "<br/>\n" unless $empty;
1569         }
1572 sub git_print_simplified_log {
1573         my $log = shift;
1574         my $remove_title = shift;
1576         git_print_log($log,
1577                 -final_empty_line=> 1,
1578                 -remove_title => $remove_title);
1581 # print tree entry (row of git_tree), but without encompassing <tr> element
1582 sub git_print_tree_entry {
1583         my ($t, $basedir, $hash_base, $have_blame) = @_;
1585         my %base_key = ();
1586         $base_key{hash_base} = $hash_base if defined $hash_base;
1588         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1589         if ($t->{'type'} eq "blob") {
1590                 print "<td class=\"list\">" .
1591                       $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1592                                              file_name=>"$basedir$t->{'name'}", %base_key),
1593                               -class => "list"}, esc_html($t->{'name'})) .
1594                       "</td>\n" .
1595                       "<td class=\"link\">" .
1596                       $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1597                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1598                               "blob");
1599                 if ($have_blame) {
1600                         print " | " .
1601                                 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1602                                                        file_name=>"$basedir$t->{'name'}", %base_key)},
1603                                         "blame");
1604                 }
1605                 if (defined $hash_base) {
1606                         print " | " .
1607                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1608                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1609                                       "history");
1610                 }
1611                 print " | " .
1612                       $cgi->a({-href => href(action=>"blob_plain",
1613                                              hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1614                               "raw") .
1615                       "</td>\n";
1617         } elsif ($t->{'type'} eq "tree") {
1618                 print "<td class=\"list\">" .
1619                       $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1620                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1621                               esc_html($t->{'name'})) .
1622                       "</td>\n" .
1623                       "<td class=\"link\">" .
1624                       $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1625                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1626                               "tree");
1627                 if (defined $hash_base) {
1628                         print " | " .
1629                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1630                                                      file_name=>"$basedir$t->{'name'}")},
1631                                       "history");
1632                 }
1633                 print "</td>\n";
1634         }
1637 ## ......................................................................
1638 ## functions printing large fragments of HTML
1640 sub git_difftree_body {
1641         my ($difftree, $hash, $parent) = @_;
1643         print "<div class=\"list_head\">\n";
1644         if ($#{$difftree} > 10) {
1645                 print(($#{$difftree} + 1) . " files changed:\n");
1646         }
1647         print "</div>\n";
1649         print "<table class=\"diff_tree\">\n";
1650         my $alternate = 0;
1651         my $patchno = 0;
1652         foreach my $line (@{$difftree}) {
1653                 my %diff = parse_difftree_raw_line($line);
1655                 if ($alternate) {
1656                         print "<tr class=\"dark\">\n";
1657                 } else {
1658                         print "<tr class=\"light\">\n";
1659                 }
1660                 $alternate ^= 1;
1662                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1663                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1664                 if ($diff{'to_mode'} ne ('0' x 6)) {
1665                         $to_mode_oct = oct $diff{'to_mode'};
1666                         if (S_ISREG($to_mode_oct)) { # only for regular file
1667                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1668                         }
1669                         $to_file_type = file_type($diff{'to_mode'});
1670                 }
1671                 if ($diff{'from_mode'} ne ('0' x 6)) {
1672                         $from_mode_oct = oct $diff{'from_mode'};
1673                         if (S_ISREG($to_mode_oct)) { # only for regular file
1674                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1675                         }
1676                         $from_file_type = file_type($diff{'from_mode'});
1677                 }
1679                 if ($diff{'status'} eq "A") { # created
1680                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1681                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1682                         $mode_chng   .= "]</span>";
1683                         print "<td>" .
1684                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1685                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1686                                       -class => "list"}, esc_html($diff{'file'})) .
1687                               "</td>\n" .
1688                               "<td>$mode_chng</td>\n" .
1689                               "<td class=\"link\">" .
1690                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1691                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1692                                       "blob");
1693                         if ($action eq 'commitdiff') {
1694                                 # link to patch
1695                                 $patchno++;
1696                                 print " | " .
1697                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1698                         }
1699                         print "</td>\n";
1701                 } elsif ($diff{'status'} eq "D") { # deleted
1702                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1703                         print "<td>" .
1704                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1705                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1706                                        -class => "list"}, esc_html($diff{'file'})) .
1707                               "</td>\n" .
1708                               "<td>$mode_chng</td>\n" .
1709                               "<td class=\"link\">" .
1710                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1711                                                      hash_base=>$parent, file_name=>$diff{'file'})},
1712                                       "blob") .
1713                               " | ";
1714                         if ($action eq 'commitdiff') {
1715                                 # link to patch
1716                                 $patchno++;
1717                                 print " | " .
1718                                       $cgi->a({-href => "#patch$patchno"}, "patch");
1719                         }
1720                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1721                                                      file_name=>$diff{'file'})},
1722                                       "history") .
1723                               "</td>\n";
1725                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1726                         my $mode_chnge = "";
1727                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1728                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1729                                 if ($from_file_type != $to_file_type) {
1730                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1731                                 }
1732                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1733                                         if ($from_mode_str && $to_mode_str) {
1734                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1735                                         } elsif ($to_mode_str) {
1736                                                 $mode_chnge .= " mode: $to_mode_str";
1737                                         }
1738                                 }
1739                                 $mode_chnge .= "]</span>\n";
1740                         }
1741                         print "<td>";
1742                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1743                                 print $cgi->a({-href => href(action=>"blobdiff",
1744                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1745                                                              hash_base=>$hash, hash_parent_base=>$parent,
1746                                                              file_name=>$diff{'file'}),
1747                                               -class => "list"}, esc_html($diff{'file'}));
1748                         } else { # only mode changed
1749                                 print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1750                                                              hash_base=>$hash, file_name=>$diff{'file'}),
1751                                               -class => "list"}, esc_html($diff{'file'}));
1752                         }
1753                         print "</td>\n" .
1754                               "<td>$mode_chnge</td>\n" .
1755                               "<td class=\"link\">" .
1756                               $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1757                                                      hash_base=>$hash, file_name=>$diff{'file'})},
1758                                       "blob");
1759                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1760                                 if ($action eq 'commitdiff') {
1761                                         # link to patch
1762                                         $patchno++;
1763                                         print " | " .
1764                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1765                                 } else {
1766                                         print " | " .
1767                                                 $cgi->a({-href => href(action=>"blobdiff",
1768                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1769                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1770                                                                        file_name=>$diff{'file'})},
1771                                                         "diff");
1772                                 }
1773                         }
1774                         print " | " .
1775                                 $cgi->a({-href => href(action=>"history",
1776                                                        hash_base=>$hash, file_name=>$diff{'file'})},
1777                                         "history");
1778                         print "</td>\n";
1780                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1781                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1782                         my $nstatus = $status_name{$diff{'status'}};
1783                         my $mode_chng = "";
1784                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1785                                 # mode also for directories, so we cannot use $to_mode_str
1786                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1787                         }
1788                         print "<td>" .
1789                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1790                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1791                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1792                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1793                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1794                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1795                                       -class => "list"}, esc_html($diff{'from_file'})) .
1796                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1797                               "<td class=\"link\">" .
1798                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1799                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'})},
1800                                       "blob");
1801                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1802                                 if ($action eq 'commitdiff') {
1803                                         # link to patch
1804                                         $patchno++;
1805                                         print " | " .
1806                                                 $cgi->a({-href => "#patch$patchno"}, "patch");
1807                                 } else {
1808                                         print " | " .
1809                                                 $cgi->a({-href => href(action=>"blobdiff",
1810                                                                        hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1811                                                                        hash_base=>$hash, hash_parent_base=>$parent,
1812                                                                        file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1813                                                         "diff");
1814                                 }
1815                         }
1816                         print "</td>\n";
1818                 } # we should not encounter Unmerged (U) or Unknown (X) status
1819                 print "</tr>\n";
1820         }
1821         print "</table>\n";
1824 sub git_patchset_body {
1825         my ($fd, $difftree, $hash, $hash_parent) = @_;
1827         my $patch_idx = 0;
1828         my $in_header = 0;
1829         my $patch_found = 0;
1830         my $diffinfo;
1832         print "<div class=\"patchset\">\n";
1834         LINE:
1835         while (my $patch_line = <$fd>) {
1836                 chomp $patch_line;
1838                 if ($patch_line =~ m/^diff /) { # "git diff" header
1839                         # beginning of patch (in patchset)
1840                         if ($patch_found) {
1841                                 # close previous patch
1842                                 print "</div>\n"; # class="patch"
1843                         } else {
1844                                 # first patch in patchset
1845                                 $patch_found = 1;
1846                         }
1847                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1849                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1850                                 $diffinfo = $difftree->[$patch_idx];
1851                         } else {
1852                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1853                         }
1854                         $patch_idx++;
1856                         # for now, no extended header, hence we skip empty patches
1857                         # companion to  next LINE if $in_header;
1858                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1859                                 $in_header = 1;
1860                                 next LINE;
1861                         }
1863                         if ($diffinfo->{'status'} eq "A") { # added
1864                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1865                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1866                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1867                                               $diffinfo->{'to_id'}) . "(new)" .
1868                                       "</div>\n"; # class="diff_info"
1870                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1871                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1872                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1873                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1874                                               $diffinfo->{'from_id'}) . "(deleted)" .
1875                                       "</div>\n"; # class="diff_info"
1877                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1878                                  $diffinfo->{'status'} eq "C" || # copied
1879                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1880                                 print "<div class=\"diff_info\">" .
1881                                       file_type($diffinfo->{'from_mode'}) . ":" .
1882                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1883                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1884                                               $diffinfo->{'from_id'}) .
1885                                       " -> " .
1886                                       file_type($diffinfo->{'to_mode'}) . ":" .
1887                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1888                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1889                                               $diffinfo->{'to_id'});
1890                                 print "</div>\n"; # class="diff_info"
1892                         } else { # modified, mode changed, ...
1893                                 print "<div class=\"diff_info\">" .
1894                                       file_type($diffinfo->{'from_mode'}) . ":" .
1895                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1896                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1897                                               $diffinfo->{'from_id'}) .
1898                                       " -> " .
1899                                       file_type($diffinfo->{'to_mode'}) . ":" .
1900                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1901                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1902                                               $diffinfo->{'to_id'});
1903                                 print "</div>\n"; # class="diff_info"
1904                         }
1906                         #print "<div class=\"diff extended_header\">\n";
1907                         $in_header = 1;
1908                         next LINE;
1909                 } # start of patch in patchset
1912                 if ($in_header && $patch_line =~ m/^---/) {
1913                         #print "</div>\n"; # class="diff extended_header"
1914                         $in_header = 0;
1916                         my $file = $diffinfo->{'from_file'};
1917                         $file  ||= $diffinfo->{'file'};
1918                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1919                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
1920                                         -class => "list"}, esc_html($file));
1921                         $patch_line =~ s|a/.*$|a/$file|g;
1922                         print "<div class=\"diff from_file\">$patch_line</div>\n";
1924                         $patch_line = <$fd>;
1925                         chomp $patch_line;
1927                         #$patch_line =~ m/^+++/;
1928                         $file    = $diffinfo->{'to_file'};
1929                         $file  ||= $diffinfo->{'file'};
1930                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1931                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
1932                                         -class => "list"}, esc_html($file));
1933                         $patch_line =~ s|b/.*|b/$file|g;
1934                         print "<div class=\"diff to_file\">$patch_line</div>\n";
1936                         next LINE;
1937                 }
1938                 next LINE if $in_header;
1940                 print format_diff_line($patch_line);
1941         }
1942         print "</div>\n" if $patch_found; # class="patch"
1944         print "</div>\n"; # class="patchset"
1947 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1949 sub git_shortlog_body {
1950         # uses global variable $project
1951         my ($revlist, $from, $to, $refs, $extra) = @_;
1953         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
1954         my $have_snapshot = (defined $ctype && defined $suffix);
1956         $from = 0 unless defined $from;
1957         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
1959         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
1960         my $alternate = 0;
1961         for (my $i = $from; $i <= $to; $i++) {
1962                 my $commit = $revlist->[$i];
1963                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
1964                 my $ref = format_ref_marker($refs, $commit);
1965                 my %co = parse_commit($commit);
1966                 if ($alternate) {
1967                         print "<tr class=\"dark\">\n";
1968                 } else {
1969                         print "<tr class=\"light\">\n";
1970                 }
1971                 $alternate ^= 1;
1972                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
1973                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
1974                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
1975                       "<td>";
1976                 print format_subject_html($co{'title'}, $co{'title_short'},
1977                                           href(action=>"commit", hash=>$commit), $ref);
1978                 print "</td>\n" .
1979                       "<td class=\"link\">" .
1980                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
1981                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
1982                 if ($have_snapshot) {
1983                         print " | " .  $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
1984                 }
1985                 print "</td>\n" .
1986                       "</tr>\n";
1987         }
1988         if (defined $extra) {
1989                 print "<tr>\n" .
1990                       "<td colspan=\"4\">$extra</td>\n" .
1991                       "</tr>\n";
1992         }
1993         print "</table>\n";
1996 sub git_history_body {
1997         # Warning: assumes constant type (blob or tree) during history
1998         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2000         $from = 0 unless defined $from;
2001         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2003         print "<table class=\"history\" cellspacing=\"0\">\n";
2004         my $alternate = 0;
2005         for (my $i = $from; $i <= $to; $i++) {
2006                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2007                         next;
2008                 }
2010                 my $commit = $1;
2011                 my %co = parse_commit($commit);
2012                 if (!%co) {
2013                         next;
2014                 }
2016                 my $ref = format_ref_marker($refs, $commit);
2018                 if ($alternate) {
2019                         print "<tr class=\"dark\">\n";
2020                 } else {
2021                         print "<tr class=\"light\">\n";
2022                 }
2023                 $alternate ^= 1;
2024                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2025                       # shortlog uses      chop_str($co{'author_name'}, 10)
2026                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2027                       "<td>";
2028                 # originally git_history used chop_str($co{'title'}, 50)
2029                 print format_subject_html($co{'title'}, $co{'title_short'},
2030                                           href(action=>"commit", hash=>$commit), $ref);
2031                 print "</td>\n" .
2032                       "<td class=\"link\">" .
2033                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2034                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2035                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype);
2037                 if ($ftype eq 'blob') {
2038                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2039                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2040                         if (defined $blob_current && defined $blob_parent &&
2041                                         $blob_current ne $blob_parent) {
2042                                 print " | " .
2043                                         $cgi->a({-href => href(action=>"blobdiff",
2044                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2045                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2046                                                                file_name=>$file_name)},
2047                                                 "diff to current");
2048                         }
2049                 }
2050                 print "</td>\n" .
2051                       "</tr>\n";
2052         }
2053         if (defined $extra) {
2054                 print "<tr>\n" .
2055                       "<td colspan=\"4\">$extra</td>\n" .
2056                       "</tr>\n";
2057         }
2058         print "</table>\n";
2061 sub git_tags_body {
2062         # uses global variable $project
2063         my ($taglist, $from, $to, $extra) = @_;
2064         $from = 0 unless defined $from;
2065         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2067         print "<table class=\"tags\" cellspacing=\"0\">\n";
2068         my $alternate = 0;
2069         for (my $i = $from; $i <= $to; $i++) {
2070                 my $entry = $taglist->[$i];
2071                 my %tag = %$entry;
2072                 my $comment_lines = $tag{'comment'};
2073                 my $comment = shift @$comment_lines;
2074                 my $comment_short;
2075                 if (defined $comment) {
2076                         $comment_short = chop_str($comment, 30, 5);
2077                 }
2078                 if ($alternate) {
2079                         print "<tr class=\"dark\">\n";
2080                 } else {
2081                         print "<tr class=\"light\">\n";
2082                 }
2083                 $alternate ^= 1;
2084                 print "<td><i>$tag{'age'}</i></td>\n" .
2085                       "<td>" .
2086                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2087                                -class => "list name"}, esc_html($tag{'name'})) .
2088                       "</td>\n" .
2089                       "<td>";
2090                 if (defined $comment) {
2091                         print format_subject_html($comment, $comment_short,
2092                                                   href(action=>"tag", hash=>$tag{'id'}));
2093                 }
2094                 print "</td>\n" .
2095                       "<td class=\"selflink\">";
2096                 if ($tag{'type'} eq "tag") {
2097                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2098                 } else {
2099                         print "&nbsp;";
2100                 }
2101                 print "</td>\n" .
2102                       "<td class=\"link\">" . " | " .
2103                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2104                 if ($tag{'reftype'} eq "commit") {
2105                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2106                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2107                 } elsif ($tag{'reftype'} eq "blob") {
2108                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2109                 }
2110                 print "</td>\n" .
2111                       "</tr>";
2112         }
2113         if (defined $extra) {
2114                 print "<tr>\n" .
2115                       "<td colspan=\"5\">$extra</td>\n" .
2116                       "</tr>\n";
2117         }
2118         print "</table>\n";
2121 sub git_heads_body {
2122         # uses global variable $project
2123         my ($taglist, $head, $from, $to, $extra) = @_;
2124         $from = 0 unless defined $from;
2125         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2127         print "<table class=\"heads\" cellspacing=\"0\">\n";
2128         my $alternate = 0;
2129         for (my $i = $from; $i <= $to; $i++) {
2130                 my $entry = $taglist->[$i];
2131                 my %tag = %$entry;
2132                 my $curr = $tag{'id'} eq $head;
2133                 if ($alternate) {
2134                         print "<tr class=\"dark\">\n";
2135                 } else {
2136                         print "<tr class=\"light\">\n";
2137                 }
2138                 $alternate ^= 1;
2139                 print "<td><i>$tag{'age'}</i></td>\n" .
2140                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2141                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2142                                -class => "list name"},esc_html($tag{'name'})) .
2143                       "</td>\n" .
2144                       "<td class=\"link\">" .
2145                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2146                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") .
2147                       "</td>\n" .
2148                       "</tr>";
2149         }
2150         if (defined $extra) {
2151                 print "<tr>\n" .
2152                       "<td colspan=\"3\">$extra</td>\n" .
2153                       "</tr>\n";
2154         }
2155         print "</table>\n";
2158 ## ======================================================================
2159 ## ======================================================================
2160 ## actions
2162 sub git_project_list {
2163         my $order = $cgi->param('o');
2164         if (defined $order && $order !~ m/project|descr|owner|age/) {
2165                 die_error(undef, "Unknown order parameter");
2166         }
2168         my @list = git_get_projects_list();
2169         my @projects;
2170         if (!@list) {
2171                 die_error(undef, "No projects found");
2172         }
2173         foreach my $pr (@list) {
2174                 my $head = git_get_head_hash($pr->{'path'});
2175                 if (!defined $head) {
2176                         next;
2177                 }
2178                 $git_dir = "$projectroot/$pr->{'path'}";
2179                 my %co = parse_commit($head);
2180                 if (!%co) {
2181                         next;
2182                 }
2183                 $pr->{'commit'} = \%co;
2184                 if (!defined $pr->{'descr'}) {
2185                         my $descr = git_get_project_description($pr->{'path'}) || "";
2186                         $pr->{'descr'} = chop_str($descr, 25, 5);
2187                 }
2188                 if (!defined $pr->{'owner'}) {
2189                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2190                 }
2191                 push @projects, $pr;
2192         }
2194         git_header_html();
2195         if (-f $home_text) {
2196                 print "<div class=\"index_include\">\n";
2197                 open (my $fd, $home_text);
2198                 print <$fd>;
2199                 close $fd;
2200                 print "</div>\n";
2201         }
2202         print "<table class=\"project_list\">\n" .
2203               "<tr>\n";
2204         $order ||= "project";
2205         if ($order eq "project") {
2206                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2207                 print "<th>Project</th>\n";
2208         } else {
2209                 print "<th>" .
2210                       $cgi->a({-href => href(project=>undef, order=>'project'),
2211                                -class => "header"}, "Project") .
2212                       "</th>\n";
2213         }
2214         if ($order eq "descr") {
2215                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2216                 print "<th>Description</th>\n";
2217         } else {
2218                 print "<th>" .
2219                       $cgi->a({-href => href(project=>undef, order=>'descr'),
2220                                -class => "header"}, "Description") .
2221                       "</th>\n";
2222         }
2223         if ($order eq "owner") {
2224                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2225                 print "<th>Owner</th>\n";
2226         } else {
2227                 print "<th>" .
2228                       $cgi->a({-href => href(project=>undef, order=>'owner'),
2229                                -class => "header"}, "Owner") .
2230                       "</th>\n";
2231         }
2232         if ($order eq "age") {
2233                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2234                 print "<th>Last Change</th>\n";
2235         } else {
2236                 print "<th>" .
2237                       $cgi->a({-href => href(project=>undef, order=>'age'),
2238                                -class => "header"}, "Last Change") .
2239                       "</th>\n";
2240         }
2241         print "<th></th>\n" .
2242               "</tr>\n";
2243         my $alternate = 0;
2244         foreach my $pr (@projects) {
2245                 if ($alternate) {
2246                         print "<tr class=\"dark\">\n";
2247                 } else {
2248                         print "<tr class=\"light\">\n";
2249                 }
2250                 $alternate ^= 1;
2251                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2252                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2253                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2254                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2255                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2256                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2257                       "<td class=\"link\">" .
2258                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2259                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2260                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") .
2261                       "</td>\n" .
2262                       "</tr>\n";
2263         }
2264         print "</table>\n";
2265         git_footer_html();
2268 sub git_project_index {
2269         my @projects = git_get_projects_list();
2271         print $cgi->header(
2272                 -type => 'text/plain',
2273                 -charset => 'utf-8',
2274                 -content_disposition => qq(inline; filename="index.aux"));
2276         foreach my $pr (@projects) {
2277                 if (!exists $pr->{'owner'}) {
2278                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2279                 }
2281                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2282                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2283                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2284                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2285                 $path  =~ s/ /\+/g;
2286                 $owner =~ s/ /\+/g;
2288                 print "$path $owner\n";
2289         }
2292 sub git_summary {
2293         my $descr = git_get_project_description($project) || "none";
2294         my $head = git_get_head_hash($project);
2295         my %co = parse_commit($head);
2296         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2298         my $owner = git_get_project_owner($project);
2300         my $refs = git_get_references();
2301         git_header_html();
2302         git_print_page_nav('summary','', $head);
2304         print "<div class=\"title\">&nbsp;</div>\n";
2305         print "<table cellspacing=\"0\">\n" .
2306               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2307               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2308               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2309         # use per project git URL list in $projectroot/$project/cloneurl
2310         # or make project git URL from git base URL and project name
2311         my $url_tag = "URL";
2312         my @url_list = git_get_project_url_list($project);
2313         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2314         foreach my $git_url (@url_list) {
2315                 next unless $git_url;
2316                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2317                 $url_tag = "";
2318         }
2319         print "</table>\n";
2321         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2322                 git_get_head_hash($project)
2323                 or die_error(undef, "Open git-rev-list failed");
2324         my @revlist = map { chomp; $_ } <$fd>;
2325         close $fd;
2326         git_print_header_div('shortlog');
2327         git_shortlog_body(\@revlist, 0, 15, $refs,
2328                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2330         my $taglist = git_get_refs_list("refs/tags");
2331         if (defined @$taglist) {
2332                 git_print_header_div('tags');
2333                 git_tags_body($taglist, 0, 15,
2334                               $cgi->a({-href => href(action=>"tags")}, "..."));
2335         }
2337         my $headlist = git_get_refs_list("refs/heads");
2338         if (defined @$headlist) {
2339                 git_print_header_div('heads');
2340                 git_heads_body($headlist, $head, 0, 15,
2341                                $cgi->a({-href => href(action=>"heads")}, "..."));
2342         }
2344         git_footer_html();
2347 sub git_tag {
2348         my $head = git_get_head_hash($project);
2349         git_header_html();
2350         git_print_page_nav('','', $head,undef,$head);
2351         my %tag = parse_tag($hash);
2352         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2353         print "<div class=\"title_text\">\n" .
2354               "<table cellspacing=\"0\">\n" .
2355               "<tr>\n" .
2356               "<td>object</td>\n" .
2357               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2358                                $tag{'object'}) . "</td>\n" .
2359               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2360                                               $tag{'type'}) . "</td>\n" .
2361               "</tr>\n";
2362         if (defined($tag{'author'})) {
2363                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2364                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2365                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2366                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2367                         "</td></tr>\n";
2368         }
2369         print "</table>\n\n" .
2370               "</div>\n";
2371         print "<div class=\"page_body\">";
2372         my $comment = $tag{'comment'};
2373         foreach my $line (@$comment) {
2374                 print esc_html($line) . "<br/>\n";
2375         }
2376         print "</div>\n";
2377         git_footer_html();
2380 sub git_blame2 {
2381         my $fd;
2382         my $ftype;
2384         my ($have_blame) = gitweb_check_feature('blame');
2385         if (!$have_blame) {
2386                 die_error('403 Permission denied', "Permission denied");
2387         }
2388         die_error('404 Not Found', "File name not defined") if (!$file_name);
2389         $hash_base ||= git_get_head_hash($project);
2390         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2391         my %co = parse_commit($hash_base)
2392                 or die_error(undef, "Reading commit failed");
2393         if (!defined $hash) {
2394                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2395                         or die_error(undef, "Error looking up file");
2396         }
2397         $ftype = git_get_type($hash);
2398         if ($ftype !~ "blob") {
2399                 die_error("400 Bad Request", "Object is not a blob");
2400         }
2401         open ($fd, "-|", git_cmd(), "blame", '-l', $file_name, $hash_base)
2402                 or die_error(undef, "Open git-blame failed");
2403         git_header_html();
2404         my $formats_nav =
2405                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2406                         "blob") .
2407                 " | " .
2408                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2409                         "head");
2410         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2411         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2412         git_print_page_path($file_name, $ftype, $hash_base);
2413         my @rev_color = (qw(light2 dark2));
2414         my $num_colors = scalar(@rev_color);
2415         my $current_color = 0;
2416         my $last_rev;
2417         print <<HTML;
2418 <div class="page_body">
2419 <table class="blame">
2420 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2421 HTML
2422         while (<$fd>) {
2423                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2424                 my $full_rev = $1;
2425                 my $rev = substr($full_rev, 0, 8);
2426                 my $lineno = $2;
2427                 my $data = $3;
2429                 if (!defined $last_rev) {
2430                         $last_rev = $full_rev;
2431                 } elsif ($last_rev ne $full_rev) {
2432                         $last_rev = $full_rev;
2433                         $current_color = ++$current_color % $num_colors;
2434                 }
2435                 print "<tr class=\"$rev_color[$current_color]\">\n";
2436                 print "<td class=\"sha1\">" .
2437                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2438                                 esc_html($rev)) . "</td>\n";
2439                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2440                       esc_html($lineno) . "</a></td>\n";
2441                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2442                 print "</tr>\n";
2443         }
2444         print "</table>\n";
2445         print "</div>";
2446         close $fd
2447                 or print "Reading blob failed\n";
2448         git_footer_html();
2451 sub git_blame {
2452         my $fd;
2454         my ($have_blame) = gitweb_check_feature('blame');
2455         if (!$have_blame) {
2456                 die_error('403 Permission denied', "Permission denied");
2457         }
2458         die_error('404 Not Found', "File name not defined") if (!$file_name);
2459         $hash_base ||= git_get_head_hash($project);
2460         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2461         my %co = parse_commit($hash_base)
2462                 or die_error(undef, "Reading commit failed");
2463         if (!defined $hash) {
2464                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2465                         or die_error(undef, "Error lookup file");
2466         }
2467         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2468                 or die_error(undef, "Open git-annotate failed");
2469         git_header_html();
2470         my $formats_nav =
2471                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2472                         "blob") .
2473                 " | " .
2474                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2475                         "head");
2476         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2477         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2478         git_print_page_path($file_name, 'blob', $hash_base);
2479         print "<div class=\"page_body\">\n";
2480         print <<HTML;
2481 <table class="blame">
2482   <tr>
2483     <th>Commit</th>
2484     <th>Age</th>
2485     <th>Author</th>
2486     <th>Line</th>
2487     <th>Data</th>
2488   </tr>
2489 HTML
2490         my @line_class = (qw(light dark));
2491         my $line_class_len = scalar (@line_class);
2492         my $line_class_num = $#line_class;
2493         while (my $line = <$fd>) {
2494                 my $long_rev;
2495                 my $short_rev;
2496                 my $author;
2497                 my $time;
2498                 my $lineno;
2499                 my $data;
2500                 my $age;
2501                 my $age_str;
2502                 my $age_class;
2504                 chomp $line;
2505                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2507                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2508                         $long_rev = $1;
2509                         $author   = $2;
2510                         $time     = $3;
2511                         $lineno   = $4;
2512                         $data     = $5;
2513                 } else {
2514                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2515                         next;
2516                 }
2517                 $short_rev  = substr ($long_rev, 0, 8);
2518                 $age        = time () - $time;
2519                 $age_str    = age_string ($age);
2520                 $age_str    =~ s/ /&nbsp;/g;
2521                 $age_class  = age_class($age);
2522                 $author     = esc_html ($author);
2523                 $author     =~ s/ /&nbsp;/g;
2525                 $data = untabify($data);
2526                 $data = esc_html ($data);
2528                 print <<HTML;
2529   <tr class="$line_class[$line_class_num]">
2530     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2531     <td class="$age_class">$age_str</td>
2532     <td>$author</td>
2533     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2534     <td class="pre">$data</td>
2535   </tr>
2536 HTML
2537         } # while (my $line = <$fd>)
2538         print "</table>\n\n";
2539         close $fd
2540                 or print "Reading blob failed.\n";
2541         print "</div>";
2542         git_footer_html();
2545 sub git_tags {
2546         my $head = git_get_head_hash($project);
2547         git_header_html();
2548         git_print_page_nav('','', $head,undef,$head);
2549         git_print_header_div('summary', $project);
2551         my $taglist = git_get_refs_list("refs/tags");
2552         if (defined @$taglist) {
2553                 git_tags_body($taglist);
2554         }
2555         git_footer_html();
2558 sub git_heads {
2559         my $head = git_get_head_hash($project);
2560         git_header_html();
2561         git_print_page_nav('','', $head,undef,$head);
2562         git_print_header_div('summary', $project);
2564         my $taglist = git_get_refs_list("refs/heads");
2565         if (defined @$taglist) {
2566                 git_heads_body($taglist, $head);
2567         }
2568         git_footer_html();
2571 sub git_blob_plain {
2572         my $expires;
2574         if (!defined $hash) {
2575                 if (defined $file_name) {
2576                         my $base = $hash_base || git_get_head_hash($project);
2577                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2578                                 or die_error(undef, "Error lookup file");
2579                 } else {
2580                         die_error(undef, "No file name defined");
2581                 }
2582         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2583                 # blobs defined by non-textual hash id's can be cached
2584                 $expires = "+1d";
2585         }
2587         my $type = shift;
2588         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2589                 or die_error(undef, "Couldn't cat $file_name, $hash");
2591         $type ||= blob_mimetype($fd, $file_name);
2593         # save as filename, even when no $file_name is given
2594         my $save_as = "$hash";
2595         if (defined $file_name) {
2596                 $save_as = $file_name;
2597         } elsif ($type =~ m/^text\//) {
2598                 $save_as .= '.txt';
2599         }
2601         print $cgi->header(
2602                 -type => "$type",
2603                 -expires=>$expires,
2604                 -content_disposition => "inline; filename=\"$save_as\"");
2605         undef $/;
2606         binmode STDOUT, ':raw';
2607         print <$fd>;
2608         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2609         $/ = "\n";
2610         close $fd;
2613 sub git_blob {
2614         my $expires;
2616         if (!defined $hash) {
2617                 if (defined $file_name) {
2618                         my $base = $hash_base || git_get_head_hash($project);
2619                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2620                                 or die_error(undef, "Error lookup file");
2621                 } else {
2622                         die_error(undef, "No file name defined");
2623                 }
2624         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2625                 # blobs defined by non-textual hash id's can be cached
2626                 $expires = "+1d";
2627         }
2629         my ($have_blame) = gitweb_check_feature('blame');
2630         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2631                 or die_error(undef, "Couldn't cat $file_name, $hash");
2632         my $mimetype = blob_mimetype($fd, $file_name);
2633         if ($mimetype !~ m/^text\//) {
2634                 close $fd;
2635                 return git_blob_plain($mimetype);
2636         }
2637         git_header_html(undef, $expires);
2638         my $formats_nav = '';
2639         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2640                 if (defined $file_name) {
2641                         if ($have_blame) {
2642                                 $formats_nav .=
2643                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2644                                                                hash=>$hash, file_name=>$file_name)},
2645                                                 "blame") .
2646                                         " | ";
2647                         }
2648                         $formats_nav .=
2649                                 $cgi->a({-href => href(action=>"blob_plain",
2650                                                        hash=>$hash, file_name=>$file_name)},
2651                                         "plain") .
2652                                 " | " .
2653                                 $cgi->a({-href => href(action=>"blob",
2654                                                        hash_base=>"HEAD", file_name=>$file_name)},
2655                                         "head");
2656                 } else {
2657                         $formats_nav .=
2658                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "plain");
2659                 }
2660                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2661                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2662         } else {
2663                 print "<div class=\"page_nav\">\n" .
2664                       "<br/><br/></div>\n" .
2665                       "<div class=\"title\">$hash</div>\n";
2666         }
2667         git_print_page_path($file_name, "blob", $hash_base);
2668         print "<div class=\"page_body\">\n";
2669         my $nr;
2670         while (my $line = <$fd>) {
2671                 chomp $line;
2672                 $nr++;
2673                 $line = untabify($line);
2674                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2675                        $nr, $nr, $nr, esc_html($line);
2676         }
2677         close $fd
2678                 or print "Reading blob failed.\n";
2679         print "</div>";
2680         git_footer_html();
2683 sub git_tree {
2684         if (!defined $hash) {
2685                 $hash = git_get_head_hash($project);
2686                 if (defined $file_name) {
2687                         my $base = $hash_base || $hash;
2688                         $hash = git_get_hash_by_path($base, $file_name, "tree");
2689                 }
2690                 if (!defined $hash_base) {
2691                         $hash_base = $hash;
2692                 }
2693         }
2694         $/ = "\0";
2695         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2696                 or die_error(undef, "Open git-ls-tree failed");
2697         my @entries = map { chomp; $_ } <$fd>;
2698         close $fd or die_error(undef, "Reading tree failed");
2699         $/ = "\n";
2701         my $refs = git_get_references();
2702         my $ref = format_ref_marker($refs, $hash_base);
2703         git_header_html();
2704         my $base = "";
2705         my ($have_blame) = gitweb_check_feature('blame');
2706         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2707                 git_print_page_nav('tree','', $hash_base);
2708                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2709         } else {
2710                 undef $hash_base;
2711                 print "<div class=\"page_nav\">\n";
2712                 print "<br/><br/></div>\n";
2713                 print "<div class=\"title\">$hash</div>\n";
2714         }
2715         if (defined $file_name) {
2716                 $base = esc_html("$file_name/");
2717         }
2718         git_print_page_path($file_name, 'tree', $hash_base);
2719         print "<div class=\"page_body\">\n";
2720         print "<table cellspacing=\"0\">\n";
2721         my $alternate = 0;
2722         foreach my $line (@entries) {
2723                 my %t = parse_ls_tree_line($line, -z => 1);
2725                 if ($alternate) {
2726                         print "<tr class=\"dark\">\n";
2727                 } else {
2728                         print "<tr class=\"light\">\n";
2729                 }
2730                 $alternate ^= 1;
2732                 git_print_tree_entry(\%t, $base, $hash_base, $have_blame);
2734                 print "</tr>\n";
2735         }
2736         print "</table>\n" .
2737               "</div>";
2738         git_footer_html();
2741 sub git_snapshot {
2743         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2744         my $have_snapshot = (defined $ctype && defined $suffix);
2745         if (!$have_snapshot) {
2746                 die_error('403 Permission denied', "Permission denied");
2747         }
2749         if (!defined $hash) {
2750                 $hash = git_get_head_hash($project);
2751         }
2753         my $filename = basename($project) . "-$hash.tar.$suffix";
2755         print $cgi->header(-type => 'application/x-tar',
2756                            -content_encoding => $ctype,
2757                            -content_disposition => "inline; filename=\"$filename\"",
2758                            -status => '200 OK');
2760         my $git_command = git_cmd_str();
2761         open my $fd, "-|", "$git_command tar-tree $hash \'$project\' | $command" or
2762                 die_error(undef, "Execute git-tar-tree failed.");
2763         binmode STDOUT, ':raw';
2764         print <$fd>;
2765         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2766         close $fd;
2770 sub git_log {
2771         my $head = git_get_head_hash($project);
2772         if (!defined $hash) {
2773                 $hash = $head;
2774         }
2775         if (!defined $page) {
2776                 $page = 0;
2777         }
2778         my $refs = git_get_references();
2780         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2781         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2782                 or die_error(undef, "Open git-rev-list failed");
2783         my @revlist = map { chomp; $_ } <$fd>;
2784         close $fd;
2786         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2788         git_header_html();
2789         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2791         if (!@revlist) {
2792                 my %co = parse_commit($hash);
2794                 git_print_header_div('summary', $project);
2795                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2796         }
2797         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2798                 my $commit = $revlist[$i];
2799                 my $ref = format_ref_marker($refs, $commit);
2800                 my %co = parse_commit($commit);
2801                 next if !%co;
2802                 my %ad = parse_date($co{'author_epoch'});
2803                 git_print_header_div('commit',
2804                                "<span class=\"age\">$co{'age_string'}</span>" .
2805                                esc_html($co{'title'}) . $ref,
2806                                $commit);
2807                 print "<div class=\"title_text\">\n" .
2808                       "<div class=\"log_link\">\n" .
2809                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2810                       " | " .
2811                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2812                       "<br/>\n" .
2813                       "</div>\n" .
2814                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2815                       "</div>\n";
2817                 print "<div class=\"log_body\">\n";
2818                 git_print_simplified_log($co{'comment'});
2819                 print "</div>\n";
2820         }
2821         git_footer_html();
2824 sub git_commit {
2825         my %co = parse_commit($hash);
2826         if (!%co) {
2827                 die_error(undef, "Unknown commit object");
2828         }
2829         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2830         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2832         my $parent = $co{'parent'};
2833         if (!defined $parent) {
2834                 $parent = "--root";
2835         }
2836         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2837                 or die_error(undef, "Open git-diff-tree failed");
2838         my @difftree = map { chomp; $_ } <$fd>;
2839         close $fd or die_error(undef, "Reading git-diff-tree failed");
2841         # non-textual hash id's can be cached
2842         my $expires;
2843         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2844                 $expires = "+1d";
2845         }
2846         my $refs = git_get_references();
2847         my $ref = format_ref_marker($refs, $co{'id'});
2849         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2850         my $have_snapshot = (defined $ctype && defined $suffix);
2852         my $formats_nav = '';
2853         if (defined $file_name && defined $co{'parent'}) {
2854                 my $parent = $co{'parent'};
2855                 $formats_nav .=
2856                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2857                                 "blame");
2858         }
2859         git_header_html(undef, $expires);
2860         git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2861                            $hash, $co{'tree'}, $hash,
2862                            $formats_nav);
2864         if (defined $co{'parent'}) {
2865                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2866         } else {
2867                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2868         }
2869         print "<div class=\"title_text\">\n" .
2870               "<table cellspacing=\"0\">\n";
2871         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2872               "<tr>" .
2873               "<td></td><td> $ad{'rfc2822'}";
2874         if ($ad{'hour_local'} < 6) {
2875                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2876                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2877         } else {
2878                 printf(" (%02d:%02d %s)",
2879                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2880         }
2881         print "</td>" .
2882               "</tr>\n";
2883         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2884         print "<tr><td></td><td> $cd{'rfc2822'}" .
2885               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2886               "</td></tr>\n";
2887         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2888         print "<tr>" .
2889               "<td>tree</td>" .
2890               "<td class=\"sha1\">" .
2891               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2892                        class => "list"}, $co{'tree'}) .
2893               "</td>" .
2894               "<td class=\"link\">" .
2895               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2896                       "tree");
2897         if ($have_snapshot) {
2898                 print " | " .
2899                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2900         }
2901         print "</td>" .
2902               "</tr>\n";
2903         my $parents = $co{'parents'};
2904         foreach my $par (@$parents) {
2905                 print "<tr>" .
2906                       "<td>parent</td>" .
2907                       "<td class=\"sha1\">" .
2908                       $cgi->a({-href => href(action=>"commit", hash=>$par),
2909                                class => "list"}, $par) .
2910                       "</td>" .
2911                       "<td class=\"link\">" .
2912                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
2913                       " | " .
2914                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
2915                       "</td>" .
2916                       "</tr>\n";
2917         }
2918         print "</table>".
2919               "</div>\n";
2921         print "<div class=\"page_body\">\n";
2922         git_print_log($co{'comment'});
2923         print "</div>\n";
2925         git_difftree_body(\@difftree, $hash, $parent);
2927         git_footer_html();
2930 sub git_blobdiff {
2931         my $format = shift || 'html';
2933         my $fd;
2934         my @difftree;
2935         my %diffinfo;
2936         my $expires;
2938         # preparing $fd and %diffinfo for git_patchset_body
2939         # new style URI
2940         if (defined $hash_base && defined $hash_parent_base) {
2941                 if (defined $file_name) {
2942                         # read raw output
2943                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
2944                                 "--", $file_name
2945                                 or die_error(undef, "Open git-diff-tree failed");
2946                         @difftree = map { chomp; $_ } <$fd>;
2947                         close $fd
2948                                 or die_error(undef, "Reading git-diff-tree failed");
2949                         @difftree
2950                                 or die_error('404 Not Found', "Blob diff not found");
2952                 } elsif (defined $hash &&
2953                          $hash =~ /[0-9a-fA-F]{40}/) {
2954                         # try to find filename from $hash
2956                         # read filtered raw output
2957                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
2958                                 or die_error(undef, "Open git-diff-tree failed");
2959                         @difftree =
2960                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
2961                                 # $hash == to_id
2962                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
2963                                 map { chomp; $_ } <$fd>;
2964                         close $fd
2965                                 or die_error(undef, "Reading git-diff-tree failed");
2966                         @difftree
2967                                 or die_error('404 Not Found', "Blob diff not found");
2969                 } else {
2970                         die_error('404 Not Found', "Missing one of the blob diff parameters");
2971                 }
2973                 if (@difftree > 1) {
2974                         die_error('404 Not Found', "Ambiguous blob diff specification");
2975                 }
2977                 %diffinfo = parse_difftree_raw_line($difftree[0]);
2978                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
2979                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
2981                 $hash_parent ||= $diffinfo{'from_id'};
2982                 $hash        ||= $diffinfo{'to_id'};
2984                 # non-textual hash id's can be cached
2985                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
2986                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
2987                         $expires = '+1d';
2988                 }
2990                 # open patch output
2991                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
2992                         '-p', $hash_parent_base, $hash_base,
2993                         "--", $file_name
2994                         or die_error(undef, "Open git-diff-tree failed");
2995         }
2997         # old/legacy style URI
2998         if (!%diffinfo && # if new style URI failed
2999             defined $hash && defined $hash_parent) {
3000                 # fake git-diff-tree raw output
3001                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3002                 $diffinfo{'from_id'} = $hash_parent;
3003                 $diffinfo{'to_id'}   = $hash;
3004                 if (defined $file_name) {
3005                         if (defined $file_parent) {
3006                                 $diffinfo{'status'} = '2';
3007                                 $diffinfo{'from_file'} = $file_parent;
3008                                 $diffinfo{'to_file'}   = $file_name;
3009                         } else { # assume not renamed
3010                                 $diffinfo{'status'} = '1';
3011                                 $diffinfo{'from_file'} = $file_name;
3012                                 $diffinfo{'to_file'}   = $file_name;
3013                         }
3014                 } else { # no filename given
3015                         $diffinfo{'status'} = '2';
3016                         $diffinfo{'from_file'} = $hash_parent;
3017                         $diffinfo{'to_file'}   = $hash;
3018                 }
3020                 # non-textual hash id's can be cached
3021                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3022                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3023                         $expires = '+1d';
3024                 }
3026                 # open patch output
3027                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3028                         or die_error(undef, "Open git-diff failed");
3029         } else  {
3030                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3031                         unless %diffinfo;
3032         }
3034         # header
3035         if ($format eq 'html') {
3036                 my $formats_nav =
3037                         $cgi->a({-href => href(action=>"blobdiff_plain",
3038                                                hash=>$hash, hash_parent=>$hash_parent,
3039                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3040                                                file_name=>$file_name, file_parent=>$file_parent)},
3041                                 "plain");
3042                 git_header_html(undef, $expires);
3043                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3044                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3045                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3046                 } else {
3047                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3048                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3049                 }
3050                 if (defined $file_name) {
3051                         git_print_page_path($file_name, "blob", $hash_base);
3052                 } else {
3053                         print "<div class=\"page_path\"></div>\n";
3054                 }
3056         } elsif ($format eq 'plain') {
3057                 print $cgi->header(
3058                         -type => 'text/plain',
3059                         -charset => 'utf-8',
3060                         -expires => $expires,
3061                         -content_disposition => qq(inline; filename="${file_name}.patch"));
3063                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3065         } else {
3066                 die_error(undef, "Unknown blobdiff format");
3067         }
3069         # patch
3070         if ($format eq 'html') {
3071                 print "<div class=\"page_body\">\n";
3073                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3074                 close $fd;
3076                 print "</div>\n"; # class="page_body"
3077                 git_footer_html();
3079         } else {
3080                 while (my $line = <$fd>) {
3081                         $line =~ s!a/($hash|$hash_parent)!a/$diffinfo{'from_file'}!g;
3082                         $line =~ s!b/($hash|$hash_parent)!b/$diffinfo{'to_file'}!g;
3084                         print $line;
3086                         last if $line =~ m!^\+\+\+!;
3087                 }
3088                 local $/ = undef;
3089                 print <$fd>;
3090                 close $fd;
3091         }
3094 sub git_blobdiff_plain {
3095         git_blobdiff('plain');
3098 sub git_commitdiff {
3099         my $format = shift || 'html';
3100         my %co = parse_commit($hash);
3101         if (!%co) {
3102                 die_error(undef, "Unknown commit object");
3103         }
3104         if (!defined $hash_parent) {
3105                 $hash_parent = $co{'parent'} || '--root';
3106         }
3108         # read commitdiff
3109         my $fd;
3110         my @difftree;
3111         if ($format eq 'html') {
3112                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3113                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3114                         or die_error(undef, "Open git-diff-tree failed");
3116                 while (chomp(my $line = <$fd>)) {
3117                         # empty line ends raw part of diff-tree output
3118                         last unless $line;
3119                         push @difftree, $line;
3120                 }
3122         } elsif ($format eq 'plain') {
3123                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3124                         '-p', $hash_parent, $hash
3125                         or die_error(undef, "Open git-diff-tree failed");
3127         } else {
3128                 die_error(undef, "Unknown commitdiff format");
3129         }
3131         # non-textual hash id's can be cached
3132         my $expires;
3133         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3134                 $expires = "+1d";
3135         }
3137         # write commit message
3138         if ($format eq 'html') {
3139                 my $refs = git_get_references();
3140                 my $ref = format_ref_marker($refs, $co{'id'});
3141                 my $formats_nav =
3142                         $cgi->a({-href => href(action=>"commitdiff_plain",
3143                                                hash=>$hash, hash_parent=>$hash_parent)},
3144                                 "plain");
3146                 git_header_html(undef, $expires);
3147                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3148                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3149                 git_print_authorship(\%co);
3150                 print "<div class=\"page_body\">\n";
3151                 print "<div class=\"log\">\n";
3152                 git_print_simplified_log($co{'comment'}, 1); # skip title
3153                 print "</div>\n"; # class="log"
3155         } elsif ($format eq 'plain') {
3156                 my $refs = git_get_references("tags");
3157                 my $tagname = git_get_rev_name_tags($hash);
3158                 my $filename = basename($project) . "-$hash.patch";
3160                 print $cgi->header(
3161                         -type => 'text/plain',
3162                         -charset => 'utf-8',
3163                         -expires => $expires,
3164                         -content_disposition => qq(inline; filename="$filename"));
3165                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3166                 print <<TEXT;
3167 From: $co{'author'}
3168 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3169 Subject: $co{'title'}
3170 TEXT
3171                 print "X-Git-Tag: $tagname\n" if $tagname;
3172                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3174                 foreach my $line (@{$co{'comment'}}) {
3175                         print "$line\n";
3176                 }
3177                 print "---\n\n";
3178         }
3180         # write patch
3181         if ($format eq 'html') {
3182                 git_difftree_body(\@difftree, $hash, $hash_parent);
3183                 print "<br/>\n";
3185                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3186                 close $fd;
3187                 print "</div>\n"; # class="page_body"
3188                 git_footer_html();
3190         } elsif ($format eq 'plain') {
3191                 local $/ = undef;
3192                 print <$fd>;
3193                 close $fd
3194                         or print "Reading git-diff-tree failed\n";
3195         }
3198 sub git_commitdiff_plain {
3199         git_commitdiff('plain');
3202 sub git_history {
3203         if (!defined $hash_base) {
3204                 $hash_base = git_get_head_hash($project);
3205         }
3206         if (!defined $page) {
3207                 $page = 0;
3208         }
3209         my $ftype;
3210         my %co = parse_commit($hash_base);
3211         if (!%co) {
3212                 die_error(undef, "Unknown commit object");
3213         }
3215         my $refs = git_get_references();
3216         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3218         if (!defined $hash && defined $file_name) {
3219                 $hash = git_get_hash_by_path($hash_base, $file_name);
3220         }
3221         if (defined $hash) {
3222                 $ftype = git_get_type($hash);
3223         }
3225         open my $fd, "-|",
3226                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3227                         or die_error(undef, "Open git-rev-list-failed");
3228         my @revlist = map { chomp; $_ } <$fd>;
3229         close $fd
3230                 or die_error(undef, "Reading git-rev-list failed");
3232         my $paging_nav = '';
3233         if ($page > 0) {
3234                 $paging_nav .=
3235                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3236                                                file_name=>$file_name)},
3237                                 "first");
3238                 $paging_nav .= " &sdot; " .
3239                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3240                                                file_name=>$file_name, page=>$page-1),
3241                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3242         } else {
3243                 $paging_nav .= "first";
3244                 $paging_nav .= " &sdot; prev";
3245         }
3246         if ($#revlist >= (100 * ($page+1)-1)) {
3247                 $paging_nav .= " &sdot; " .
3248                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3249                                                file_name=>$file_name, page=>$page+1),
3250                                  -accesskey => "n", -title => "Alt-n"}, "next");
3251         } else {
3252                 $paging_nav .= " &sdot; next";
3253         }
3254         my $next_link = '';
3255         if ($#revlist >= (100 * ($page+1)-1)) {
3256                 $next_link =
3257                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3258                                                file_name=>$file_name, page=>$page+1),
3259                                  -title => "Alt-n"}, "next");
3260         }
3262         git_header_html();
3263         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3264         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3265         git_print_page_path($file_name, $ftype, $hash_base);
3267         git_history_body(\@revlist, ($page * 100), $#revlist,
3268                          $refs, $hash_base, $ftype, $next_link);
3270         git_footer_html();
3273 sub git_search {
3274         if (!defined $searchtext) {
3275                 die_error(undef, "Text field empty");
3276         }
3277         if (!defined $hash) {
3278                 $hash = git_get_head_hash($project);
3279         }
3280         my %co = parse_commit($hash);
3281         if (!%co) {
3282                 die_error(undef, "Unknown commit object");
3283         }
3285         my $commit_search = 1;
3286         my $author_search = 0;
3287         my $committer_search = 0;
3288         my $pickaxe_search = 0;
3289         if ($searchtext =~ s/^author\\://i) {
3290                 $author_search = 1;
3291         } elsif ($searchtext =~ s/^committer\\://i) {
3292                 $committer_search = 1;
3293         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3294                 $commit_search = 0;
3295                 $pickaxe_search = 1;
3297                 # pickaxe may take all resources of your box and run for several minutes
3298                 # with every query - so decide by yourself how public you make this feature
3299                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3300                 if (!$have_pickaxe) {
3301                         die_error('403 Permission denied', "Permission denied");
3302                 }
3303         }
3304         git_header_html();
3305         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3306         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3308         print "<table cellspacing=\"0\">\n";
3309         my $alternate = 0;
3310         if ($commit_search) {
3311                 $/ = "\0";
3312                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3313                 while (my $commit_text = <$fd>) {
3314                         if (!grep m/$searchtext/i, $commit_text) {
3315                                 next;
3316                         }
3317                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3318                                 next;
3319                         }
3320                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3321                                 next;
3322                         }
3323                         my @commit_lines = split "\n", $commit_text;
3324                         my %co = parse_commit(undef, \@commit_lines);
3325                         if (!%co) {
3326                                 next;
3327                         }
3328                         if ($alternate) {
3329                                 print "<tr class=\"dark\">\n";
3330                         } else {
3331                                 print "<tr class=\"light\">\n";
3332                         }
3333                         $alternate ^= 1;
3334                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3335                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3336                               "<td>" .
3337                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3338                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3339                         my $comment = $co{'comment'};
3340                         foreach my $line (@$comment) {
3341                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3342                                         my $lead = esc_html($1) || "";
3343                                         $lead = chop_str($lead, 30, 10);
3344                                         my $match = esc_html($2) || "";
3345                                         my $trail = esc_html($3) || "";
3346                                         $trail = chop_str($trail, 30, 10);
3347                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3348                                         print chop_str($text, 80, 5) . "<br/>\n";
3349                                 }
3350                         }
3351                         print "</td>\n" .
3352                               "<td class=\"link\">" .
3353                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3354                               " | " .
3355                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3356                         print "</td>\n" .
3357                               "</tr>\n";
3358                 }
3359                 close $fd;
3360         }
3362         if ($pickaxe_search) {
3363                 $/ = "\n";
3364                 my $git_command = git_cmd_str();
3365                 open my $fd, "-|", "$git_command rev-list $hash | " .
3366                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3367                 undef %co;
3368                 my @files;
3369                 while (my $line = <$fd>) {
3370                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3371                                 my %set;
3372                                 $set{'file'} = $6;
3373                                 $set{'from_id'} = $3;
3374                                 $set{'to_id'} = $4;
3375                                 $set{'id'} = $set{'to_id'};
3376                                 if ($set{'id'} =~ m/0{40}/) {
3377                                         $set{'id'} = $set{'from_id'};
3378                                 }
3379                                 if ($set{'id'} =~ m/0{40}/) {
3380                                         next;
3381                                 }
3382                                 push @files, \%set;
3383                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3384                                 if (%co) {
3385                                         if ($alternate) {
3386                                                 print "<tr class=\"dark\">\n";
3387                                         } else {
3388                                                 print "<tr class=\"light\">\n";
3389                                         }
3390                                         $alternate ^= 1;
3391                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3392                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3393                                               "<td>" .
3394                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3395                                                       -class => "list subject"},
3396                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3397                                         while (my $setref = shift @files) {
3398                                                 my %set = %$setref;
3399                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3400                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3401                                                               -class => "list"},
3402                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3403                                                       "<br/>\n";
3404                                         }
3405                                         print "</td>\n" .
3406                                               "<td class=\"link\">" .
3407                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3408                                               " | " .
3409                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3410                                         print "</td>\n" .
3411                                               "</tr>\n";
3412                                 }
3413                                 %co = parse_commit($1);
3414                         }
3415                 }
3416                 close $fd;
3417         }
3418         print "</table>\n";
3419         git_footer_html();
3422 sub git_shortlog {
3423         my $head = git_get_head_hash($project);
3424         if (!defined $hash) {
3425                 $hash = $head;
3426         }
3427         if (!defined $page) {
3428                 $page = 0;
3429         }
3430         my $refs = git_get_references();
3432         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3433         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3434                 or die_error(undef, "Open git-rev-list failed");
3435         my @revlist = map { chomp; $_ } <$fd>;
3436         close $fd;
3438         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3439         my $next_link = '';
3440         if ($#revlist >= (100 * ($page+1)-1)) {
3441                 $next_link =
3442                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3443                                  -title => "Alt-n"}, "next");
3444         }
3447         git_header_html();
3448         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3449         git_print_header_div('summary', $project);
3451         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3453         git_footer_html();
3456 ## ......................................................................
3457 ## feeds (RSS, OPML)
3459 sub git_rss {
3460         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3461         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3462                 or die_error(undef, "Open git-rev-list failed");
3463         my @revlist = map { chomp; $_ } <$fd>;
3464         close $fd or die_error(undef, "Reading git-rev-list failed");
3465         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3466         print <<XML;
3467 <?xml version="1.0" encoding="utf-8"?>
3468 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3469 <channel>
3470 <title>$project $my_uri $my_url</title>
3471 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3472 <description>$project log</description>
3473 <language>en</language>
3474 XML
3476         for (my $i = 0; $i <= $#revlist; $i++) {
3477                 my $commit = $revlist[$i];
3478                 my %co = parse_commit($commit);
3479                 # we read 150, we always show 30 and the ones more recent than 48 hours
3480                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3481                         last;
3482                 }
3483                 my %cd = parse_date($co{'committer_epoch'});
3484                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3485                         $co{'parent'}, $co{'id'}
3486                         or next;
3487                 my @difftree = map { chomp; $_ } <$fd>;
3488                 close $fd
3489                         or next;
3490                 print "<item>\n" .
3491                       "<title>" .
3492                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3493                       "</title>\n" .
3494                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3495                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3496                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3497                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3498                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3499                       "<content:encoded>" .
3500                       "<![CDATA[\n";
3501                 my $comment = $co{'comment'};
3502                 foreach my $line (@$comment) {
3503                         $line = decode("utf8", $line, Encode::FB_DEFAULT);
3504                         print "$line<br/>\n";
3505                 }
3506                 print "<br/>\n";
3507                 foreach my $line (@difftree) {
3508                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3509                                 next;
3510                         }
3511                         my $file = validate_input(unquote($7));
3512                         $file = decode("utf8", $file, Encode::FB_DEFAULT);
3513                         print "$file<br/>\n";
3514                 }
3515                 print "]]>\n" .
3516                       "</content:encoded>\n" .
3517                       "</item>\n";
3518         }
3519         print "</channel></rss>";
3522 sub git_opml {
3523         my @list = git_get_projects_list();
3525         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3526         print <<XML;
3527 <?xml version="1.0" encoding="utf-8"?>
3528 <opml version="1.0">
3529 <head>
3530   <title>$site_name Git OPML Export</title>
3531 </head>
3532 <body>
3533 <outline text="git RSS feeds">
3534 XML
3536         foreach my $pr (@list) {
3537                 my %proj = %$pr;
3538                 my $head = git_get_head_hash($proj{'path'});
3539                 if (!defined $head) {
3540                         next;
3541                 }
3542                 $git_dir = "$projectroot/$proj{'path'}";
3543                 my %co = parse_commit($head);
3544                 if (!%co) {
3545                         next;
3546                 }
3548                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3549                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3550                 my $html = "$my_url?p=$proj{'path'};a=summary";
3551                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3552         }
3553         print <<XML;
3554 </outline>
3555 </body>
3556 </opml>
3557 XML