Code

gitweb: Empty patch for merge means trivial merge, not no differences
[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 BEGIN {
22         CGI->compile() if $ENV{'MOD_PERL'};
23 }
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
30 # core git executable to use
31 # this can just be "git" if your webserver has a sensible PATH
32 our $GIT = "++GIT_BINDIR++/git";
34 # absolute fs-path which will be prepended to the project path
35 #our $projectroot = "/pub/scm";
36 our $projectroot = "++GITWEB_PROJECTROOT++";
38 # target of the home link on top of all pages
39 our $home_link = $my_uri || "/";
41 # string of the home link on top of all pages
42 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
44 # name of your site or organization to appear in page titles
45 # replace this with something more descriptive for clearer bookmarks
46 our $site_name = "++GITWEB_SITENAME++"
47                  || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
49 # filename of html text to include at top of each page
50 our $site_header = "++GITWEB_SITE_HEADER++";
51 # html text to include at home page
52 our $home_text = "++GITWEB_HOMETEXT++";
53 # filename of html text to include at bottom of each page
54 our $site_footer = "++GITWEB_SITE_FOOTER++";
56 # URI of stylesheets
57 our @stylesheets = ("++GITWEB_CSS++");
58 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
59 our $stylesheet = undef;
60 # URI of GIT logo (72x27 size)
61 our $logo = "++GITWEB_LOGO++";
62 # URI of GIT favicon, assumed to be image/png type
63 our $favicon = "++GITWEB_FAVICON++";
65 # URI and label (title) of GIT logo link
66 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
67 #our $logo_label = "git documentation";
68 our $logo_url = "http://git.or.cz/";
69 our $logo_label = "git homepage";
71 # source of projects list
72 our $projects_list = "++GITWEB_LIST++";
74 # default order of projects list
75 # valid values are none, project, descr, owner, and age
76 our $default_projects_order = "project";
78 # show repository only if this file exists
79 # (only effective if this variable evaluates to true)
80 our $export_ok = "++GITWEB_EXPORT_OK++";
82 # only allow viewing of repositories also shown on the overview page
83 our $strict_export = "++GITWEB_STRICT_EXPORT++";
85 # list of git base URLs used for URL to where fetch project from,
86 # i.e. full URL is "$git_base_url/$project"
87 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
89 # default blob_plain mimetype and default charset for text/plain blob
90 our $default_blob_plain_mimetype = 'text/plain';
91 our $default_text_plain_charset  = undef;
93 # file to use for guessing MIME types before trying /etc/mime.types
94 # (relative to the current git repository)
95 our $mimetypes_file = undef;
97 # You define site-wide feature defaults here; override them with
98 # $GITWEB_CONFIG as necessary.
99 our %feature = (
100         # feature => {
101         #       'sub' => feature-sub (subroutine),
102         #       'override' => allow-override (boolean),
103         #       'default' => [ default options...] (array reference)}
104         #
105         # if feature is overridable (it means that allow-override has true value),
106         # then feature-sub will be called with default options as parameters;
107         # return value of feature-sub indicates if to enable specified feature
108         #
109         # if there is no 'sub' key (no feature-sub), then feature cannot be
110         # overriden
111         #
112         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
114         # Enable the 'blame' blob view, showing the last commit that modified
115         # each line in the file. This can be very CPU-intensive.
117         # To enable system wide have in $GITWEB_CONFIG
118         # $feature{'blame'}{'default'} = [1];
119         # To have project specific config enable override in $GITWEB_CONFIG
120         # $feature{'blame'}{'override'} = 1;
121         # and in project config gitweb.blame = 0|1;
122         'blame' => {
123                 'sub' => \&feature_blame,
124                 'override' => 0,
125                 'default' => [0]},
127         # Enable the 'snapshot' link, providing a compressed tarball of any
128         # tree. This can potentially generate high traffic if you have large
129         # project.
131         # To disable system wide have in $GITWEB_CONFIG
132         # $feature{'snapshot'}{'default'} = [undef];
133         # To have project specific config enable override in $GITWEB_CONFIG
134         # $feature{'snapshot'}{'override'} = 1;
135         # and in project config gitweb.snapshot = none|gzip|bzip2;
136         'snapshot' => {
137                 'sub' => \&feature_snapshot,
138                 'override' => 0,
139                 #         => [content-encoding, suffix, program]
140                 'default' => ['x-gzip', 'gz', 'gzip']},
142         # Enable text search, which will list the commits which match author,
143         # committer or commit text to a given string.  Enabled by default.
144         # Project specific override is not supported.
145         'search' => {
146                 'override' => 0,
147                 'default' => [1]},
149         # Enable the pickaxe search, which will list the commits that modified
150         # a given string in a file. This can be practical and quite faster
151         # alternative to 'blame', but still potentially CPU-intensive.
153         # To enable system wide have in $GITWEB_CONFIG
154         # $feature{'pickaxe'}{'default'} = [1];
155         # To have project specific config enable override in $GITWEB_CONFIG
156         # $feature{'pickaxe'}{'override'} = 1;
157         # and in project config gitweb.pickaxe = 0|1;
158         'pickaxe' => {
159                 'sub' => \&feature_pickaxe,
160                 'override' => 0,
161                 'default' => [1]},
163         # Make gitweb use an alternative format of the URLs which can be
164         # more readable and natural-looking: project name is embedded
165         # directly in the path and the query string contains other
166         # auxiliary information. All gitweb installations recognize
167         # URL in either format; this configures in which formats gitweb
168         # generates links.
170         # To enable system wide have in $GITWEB_CONFIG
171         # $feature{'pathinfo'}{'default'} = [1];
172         # Project specific override is not supported.
174         # Note that you will need to change the default location of CSS,
175         # favicon, logo and possibly other files to an absolute URL. Also,
176         # if gitweb.cgi serves as your indexfile, you will need to force
177         # $my_uri to contain the script name in your $GITWEB_CONFIG.
178         'pathinfo' => {
179                 'override' => 0,
180                 'default' => [0]},
182         # Make gitweb consider projects in project root subdirectories
183         # to be forks of existing projects. Given project $projname.git,
184         # projects matching $projname/*.git will not be shown in the main
185         # projects list, instead a '+' mark will be added to $projname
186         # there and a 'forks' view will be enabled for the project, listing
187         # all the forks. If project list is taken from a file, forks have
188         # to be listed after the main project.
190         # To enable system wide have in $GITWEB_CONFIG
191         # $feature{'forks'}{'default'} = [1];
192         # Project specific override is not supported.
193         'forks' => {
194                 'override' => 0,
195                 'default' => [0]},
196 );
198 sub gitweb_check_feature {
199         my ($name) = @_;
200         return unless exists $feature{$name};
201         my ($sub, $override, @defaults) = (
202                 $feature{$name}{'sub'},
203                 $feature{$name}{'override'},
204                 @{$feature{$name}{'default'}});
205         if (!$override) { return @defaults; }
206         if (!defined $sub) {
207                 warn "feature $name is not overrideable";
208                 return @defaults;
209         }
210         return $sub->(@defaults);
213 sub feature_blame {
214         my ($val) = git_get_project_config('blame', '--bool');
216         if ($val eq 'true') {
217                 return 1;
218         } elsif ($val eq 'false') {
219                 return 0;
220         }
222         return $_[0];
225 sub feature_snapshot {
226         my ($ctype, $suffix, $command) = @_;
228         my ($val) = git_get_project_config('snapshot');
230         if ($val eq 'gzip') {
231                 return ('x-gzip', 'gz', 'gzip');
232         } elsif ($val eq 'bzip2') {
233                 return ('x-bzip2', 'bz2', 'bzip2');
234         } elsif ($val eq 'none') {
235                 return ();
236         }
238         return ($ctype, $suffix, $command);
241 sub gitweb_have_snapshot {
242         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
243         my $have_snapshot = (defined $ctype && defined $suffix);
245         return $have_snapshot;
248 sub feature_pickaxe {
249         my ($val) = git_get_project_config('pickaxe', '--bool');
251         if ($val eq 'true') {
252                 return (1);
253         } elsif ($val eq 'false') {
254                 return (0);
255         }
257         return ($_[0]);
260 # checking HEAD file with -e is fragile if the repository was
261 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
262 # and then pruned.
263 sub check_head_link {
264         my ($dir) = @_;
265         my $headfile = "$dir/HEAD";
266         return ((-e $headfile) ||
267                 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
270 sub check_export_ok {
271         my ($dir) = @_;
272         return (check_head_link($dir) &&
273                 (!$export_ok || -e "$dir/$export_ok"));
276 # rename detection options for git-diff and git-diff-tree
277 # - default is '-M', with the cost proportional to
278 #   (number of removed files) * (number of new files).
279 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
280 #   (number of changed files + number of removed files) * (number of new files)
281 # - even more costly is '-C', '--find-copies-harder' with cost
282 #   (number of files in the original tree) * (number of new files)
283 # - one might want to include '-B' option, e.g. '-B', '-M'
284 our @diff_opts = ('-M'); # taken from git_commit
286 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
287 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
289 # version of the core git binary
290 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
292 $projects_list ||= $projectroot;
294 # ======================================================================
295 # input validation and dispatch
296 our $action = $cgi->param('a');
297 if (defined $action) {
298         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
299                 die_error(undef, "Invalid action parameter");
300         }
303 # parameters which are pathnames
304 our $project = $cgi->param('p');
305 if (defined $project) {
306         if (!validate_pathname($project) ||
307             !(-d "$projectroot/$project") ||
308             !check_head_link("$projectroot/$project") ||
309             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
310             ($strict_export && !project_in_list($project))) {
311                 undef $project;
312                 die_error(undef, "No such project");
313         }
316 our $file_name = $cgi->param('f');
317 if (defined $file_name) {
318         if (!validate_pathname($file_name)) {
319                 die_error(undef, "Invalid file parameter");
320         }
323 our $file_parent = $cgi->param('fp');
324 if (defined $file_parent) {
325         if (!validate_pathname($file_parent)) {
326                 die_error(undef, "Invalid file parent parameter");
327         }
330 # parameters which are refnames
331 our $hash = $cgi->param('h');
332 if (defined $hash) {
333         if (!validate_refname($hash)) {
334                 die_error(undef, "Invalid hash parameter");
335         }
338 our $hash_parent = $cgi->param('hp');
339 if (defined $hash_parent) {
340         if (!validate_refname($hash_parent)) {
341                 die_error(undef, "Invalid hash parent parameter");
342         }
345 our $hash_base = $cgi->param('hb');
346 if (defined $hash_base) {
347         if (!validate_refname($hash_base)) {
348                 die_error(undef, "Invalid hash base parameter");
349         }
352 our $hash_parent_base = $cgi->param('hpb');
353 if (defined $hash_parent_base) {
354         if (!validate_refname($hash_parent_base)) {
355                 die_error(undef, "Invalid hash parent base parameter");
356         }
359 # other parameters
360 our $page = $cgi->param('pg');
361 if (defined $page) {
362         if ($page =~ m/[^0-9]/) {
363                 die_error(undef, "Invalid page parameter");
364         }
367 our $searchtext = $cgi->param('s');
368 our $search_regexp;
369 if (defined $searchtext) {
370         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
371                 die_error(undef, "Invalid search parameter");
372         }
373         if (length($searchtext) < 2) {
374                 die_error(undef, "At least two characters are required for search parameter");
375         }
376         $search_regexp = quotemeta $searchtext;
379 our $searchtype = $cgi->param('st');
380 if (defined $searchtype) {
381         if ($searchtype =~ m/[^a-z]/) {
382                 die_error(undef, "Invalid searchtype parameter");
383         }
386 # now read PATH_INFO and use it as alternative to parameters
387 sub evaluate_path_info {
388         return if defined $project;
389         my $path_info = $ENV{"PATH_INFO"};
390         return if !$path_info;
391         $path_info =~ s,^/+,,;
392         return if !$path_info;
393         # find which part of PATH_INFO is project
394         $project = $path_info;
395         $project =~ s,/+$,,;
396         while ($project && !check_head_link("$projectroot/$project")) {
397                 $project =~ s,/*[^/]*$,,;
398         }
399         # validate project
400         $project = validate_pathname($project);
401         if (!$project ||
402             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
403             ($strict_export && !project_in_list($project))) {
404                 undef $project;
405                 return;
406         }
407         # do not change any parameters if an action is given using the query string
408         return if $action;
409         $path_info =~ s,^$project/*,,;
410         my ($refname, $pathname) = split(/:/, $path_info, 2);
411         if (defined $pathname) {
412                 # we got "project.git/branch:filename" or "project.git/branch:dir/"
413                 # we could use git_get_type(branch:pathname), but it needs $git_dir
414                 $pathname =~ s,^/+,,;
415                 if (!$pathname || substr($pathname, -1) eq "/") {
416                         $action  ||= "tree";
417                         $pathname =~ s,/$,,;
418                 } else {
419                         $action  ||= "blob_plain";
420                 }
421                 $hash_base ||= validate_refname($refname);
422                 $file_name ||= validate_pathname($pathname);
423         } elsif (defined $refname) {
424                 # we got "project.git/branch"
425                 $action ||= "shortlog";
426                 $hash   ||= validate_refname($refname);
427         }
429 evaluate_path_info();
431 # path to the current git repository
432 our $git_dir;
433 $git_dir = "$projectroot/$project" if $project;
435 # dispatch
436 my %actions = (
437         "blame" => \&git_blame2,
438         "blobdiff" => \&git_blobdiff,
439         "blobdiff_plain" => \&git_blobdiff_plain,
440         "blob" => \&git_blob,
441         "blob_plain" => \&git_blob_plain,
442         "commitdiff" => \&git_commitdiff,
443         "commitdiff_plain" => \&git_commitdiff_plain,
444         "commit" => \&git_commit,
445         "forks" => \&git_forks,
446         "heads" => \&git_heads,
447         "history" => \&git_history,
448         "log" => \&git_log,
449         "rss" => \&git_rss,
450         "atom" => \&git_atom,
451         "search" => \&git_search,
452         "search_help" => \&git_search_help,
453         "shortlog" => \&git_shortlog,
454         "summary" => \&git_summary,
455         "tag" => \&git_tag,
456         "tags" => \&git_tags,
457         "tree" => \&git_tree,
458         "snapshot" => \&git_snapshot,
459         "object" => \&git_object,
460         # those below don't need $project
461         "opml" => \&git_opml,
462         "project_list" => \&git_project_list,
463         "project_index" => \&git_project_index,
464 );
466 if (!defined $action) {
467         if (defined $hash) {
468                 $action = git_get_type($hash);
469         } elsif (defined $hash_base && defined $file_name) {
470                 $action = git_get_type("$hash_base:$file_name");
471         } elsif (defined $project) {
472                 $action = 'summary';
473         } else {
474                 $action = 'project_list';
475         }
477 if (!defined($actions{$action})) {
478         die_error(undef, "Unknown action");
480 if ($action !~ m/^(opml|project_list|project_index)$/ &&
481     !$project) {
482         die_error(undef, "Project needed");
484 $actions{$action}->();
485 exit;
487 ## ======================================================================
488 ## action links
490 sub href(%) {
491         my %params = @_;
492         # default is to use -absolute url() i.e. $my_uri
493         my $href = $params{-full} ? $my_url : $my_uri;
495         # XXX: Warning: If you touch this, check the search form for updating,
496         # too.
498         my @mapping = (
499                 project => "p",
500                 action => "a",
501                 file_name => "f",
502                 file_parent => "fp",
503                 hash => "h",
504                 hash_parent => "hp",
505                 hash_base => "hb",
506                 hash_parent_base => "hpb",
507                 page => "pg",
508                 order => "o",
509                 searchtext => "s",
510                 searchtype => "st",
511         );
512         my %mapping = @mapping;
514         $params{'project'} = $project unless exists $params{'project'};
516         my ($use_pathinfo) = gitweb_check_feature('pathinfo');
517         if ($use_pathinfo) {
518                 # use PATH_INFO for project name
519                 $href .= "/$params{'project'}" if defined $params{'project'};
520                 delete $params{'project'};
522                 # Summary just uses the project path URL
523                 if (defined $params{'action'} && $params{'action'} eq 'summary') {
524                         delete $params{'action'};
525                 }
526         }
528         # now encode the parameters explicitly
529         my @result = ();
530         for (my $i = 0; $i < @mapping; $i += 2) {
531                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
532                 if (defined $params{$name}) {
533                         push @result, $symbol . "=" . esc_param($params{$name});
534                 }
535         }
536         $href .= "?" . join(';', @result) if scalar @result;
538         return $href;
542 ## ======================================================================
543 ## validation, quoting/unquoting and escaping
545 sub validate_pathname {
546         my $input = shift || return undef;
548         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
549         # at the beginning, at the end, and between slashes.
550         # also this catches doubled slashes
551         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
552                 return undef;
553         }
554         # no null characters
555         if ($input =~ m!\0!) {
556                 return undef;
557         }
558         return $input;
561 sub validate_refname {
562         my $input = shift || return undef;
564         # textual hashes are O.K.
565         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
566                 return $input;
567         }
568         # it must be correct pathname
569         $input = validate_pathname($input)
570                 or return undef;
571         # restrictions on ref name according to git-check-ref-format
572         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
573                 return undef;
574         }
575         return $input;
578 # quote unsafe chars, but keep the slash, even when it's not
579 # correct, but quoted slashes look too horrible in bookmarks
580 sub esc_param {
581         my $str = shift;
582         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
583         $str =~ s/\+/%2B/g;
584         $str =~ s/ /\+/g;
585         return $str;
588 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
589 sub esc_url {
590         my $str = shift;
591         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
592         $str =~ s/\+/%2B/g;
593         $str =~ s/ /\+/g;
594         return $str;
597 # replace invalid utf8 character with SUBSTITUTION sequence
598 sub esc_html ($;%) {
599         my $str = shift;
600         my %opts = @_;
602         $str = decode_utf8($str);
603         $str = $cgi->escapeHTML($str);
604         if ($opts{'-nbsp'}) {
605                 $str =~ s/ /&nbsp;/g;
606         }
607         $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
608         return $str;
611 # quote control characters and escape filename to HTML
612 sub esc_path {
613         my $str = shift;
614         my %opts = @_;
616         $str = decode_utf8($str);
617         $str = $cgi->escapeHTML($str);
618         if ($opts{'-nbsp'}) {
619                 $str =~ s/ /&nbsp;/g;
620         }
621         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
622         return $str;
625 # Make control characters "printable", using character escape codes (CEC)
626 sub quot_cec {
627         my $cntrl = shift;
628         my %es = ( # character escape codes, aka escape sequences
629                    "\t" => '\t',   # tab            (HT)
630                    "\n" => '\n',   # line feed      (LF)
631                    "\r" => '\r',   # carrige return (CR)
632                    "\f" => '\f',   # form feed      (FF)
633                    "\b" => '\b',   # backspace      (BS)
634                    "\a" => '\a',   # alarm (bell)   (BEL)
635                    "\e" => '\e',   # escape         (ESC)
636                    "\013" => '\v', # vertical tab   (VT)
637                    "\000" => '\0', # nul character  (NUL)
638                    );
639         my $chr = ( (exists $es{$cntrl})
640                     ? $es{$cntrl}
641                     : sprintf('\%03o', ord($cntrl)) );
642         return "<span class=\"cntrl\">$chr</span>";
645 # Alternatively use unicode control pictures codepoints,
646 # Unicode "printable representation" (PR)
647 sub quot_upr {
648         my $cntrl = shift;
649         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
650         return "<span class=\"cntrl\">$chr</span>";
653 # git may return quoted and escaped filenames
654 sub unquote {
655         my $str = shift;
657         sub unq {
658                 my $seq = shift;
659                 my %es = ( # character escape codes, aka escape sequences
660                         't' => "\t",   # tab            (HT, TAB)
661                         'n' => "\n",   # newline        (NL)
662                         'r' => "\r",   # return         (CR)
663                         'f' => "\f",   # form feed      (FF)
664                         'b' => "\b",   # backspace      (BS)
665                         'a' => "\a",   # alarm (bell)   (BEL)
666                         'e' => "\e",   # escape         (ESC)
667                         'v' => "\013", # vertical tab   (VT)
668                 );
670                 if ($seq =~ m/^[0-7]{1,3}$/) {
671                         # octal char sequence
672                         return chr(oct($seq));
673                 } elsif (exists $es{$seq}) {
674                         # C escape sequence, aka character escape code
675                         return $es{$seq}
676                 }
677                 # quoted ordinary character
678                 return $seq;
679         }
681         if ($str =~ m/^"(.*)"$/) {
682                 # needs unquoting
683                 $str = $1;
684                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
685         }
686         return $str;
689 # escape tabs (convert tabs to spaces)
690 sub untabify {
691         my $line = shift;
693         while ((my $pos = index($line, "\t")) != -1) {
694                 if (my $count = (8 - ($pos % 8))) {
695                         my $spaces = ' ' x $count;
696                         $line =~ s/\t/$spaces/;
697                 }
698         }
700         return $line;
703 sub project_in_list {
704         my $project = shift;
705         my @list = git_get_projects_list();
706         return @list && scalar(grep { $_->{'path'} eq $project } @list);
709 ## ----------------------------------------------------------------------
710 ## HTML aware string manipulation
712 sub chop_str {
713         my $str = shift;
714         my $len = shift;
715         my $add_len = shift || 10;
717         # allow only $len chars, but don't cut a word if it would fit in $add_len
718         # if it doesn't fit, cut it if it's still longer than the dots we would add
719         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
720         my $body = $1;
721         my $tail = $2;
722         if (length($tail) > 4) {
723                 $tail = " ...";
724                 $body =~ s/&[^;]*$//; # remove chopped character entities
725         }
726         return "$body$tail";
729 ## ----------------------------------------------------------------------
730 ## functions returning short strings
732 # CSS class for given age value (in seconds)
733 sub age_class {
734         my $age = shift;
736         if (!defined $age) {
737                 return "noage";
738         } elsif ($age < 60*60*2) {
739                 return "age0";
740         } elsif ($age < 60*60*24*2) {
741                 return "age1";
742         } else {
743                 return "age2";
744         }
747 # convert age in seconds to "nn units ago" string
748 sub age_string {
749         my $age = shift;
750         my $age_str;
752         if ($age > 60*60*24*365*2) {
753                 $age_str = (int $age/60/60/24/365);
754                 $age_str .= " years ago";
755         } elsif ($age > 60*60*24*(365/12)*2) {
756                 $age_str = int $age/60/60/24/(365/12);
757                 $age_str .= " months ago";
758         } elsif ($age > 60*60*24*7*2) {
759                 $age_str = int $age/60/60/24/7;
760                 $age_str .= " weeks ago";
761         } elsif ($age > 60*60*24*2) {
762                 $age_str = int $age/60/60/24;
763                 $age_str .= " days ago";
764         } elsif ($age > 60*60*2) {
765                 $age_str = int $age/60/60;
766                 $age_str .= " hours ago";
767         } elsif ($age > 60*2) {
768                 $age_str = int $age/60;
769                 $age_str .= " min ago";
770         } elsif ($age > 2) {
771                 $age_str = int $age;
772                 $age_str .= " sec ago";
773         } else {
774                 $age_str .= " right now";
775         }
776         return $age_str;
779 # convert file mode in octal to symbolic file mode string
780 sub mode_str {
781         my $mode = oct shift;
783         if (S_ISDIR($mode & S_IFMT)) {
784                 return 'drwxr-xr-x';
785         } elsif (S_ISLNK($mode)) {
786                 return 'lrwxrwxrwx';
787         } elsif (S_ISREG($mode)) {
788                 # git cares only about the executable bit
789                 if ($mode & S_IXUSR) {
790                         return '-rwxr-xr-x';
791                 } else {
792                         return '-rw-r--r--';
793                 };
794         } else {
795                 return '----------';
796         }
799 # convert file mode in octal to file type string
800 sub file_type {
801         my $mode = shift;
803         if ($mode !~ m/^[0-7]+$/) {
804                 return $mode;
805         } else {
806                 $mode = oct $mode;
807         }
809         if (S_ISDIR($mode & S_IFMT)) {
810                 return "directory";
811         } elsif (S_ISLNK($mode)) {
812                 return "symlink";
813         } elsif (S_ISREG($mode)) {
814                 return "file";
815         } else {
816                 return "unknown";
817         }
820 # convert file mode in octal to file type description string
821 sub file_type_long {
822         my $mode = shift;
824         if ($mode !~ m/^[0-7]+$/) {
825                 return $mode;
826         } else {
827                 $mode = oct $mode;
828         }
830         if (S_ISDIR($mode & S_IFMT)) {
831                 return "directory";
832         } elsif (S_ISLNK($mode)) {
833                 return "symlink";
834         } elsif (S_ISREG($mode)) {
835                 if ($mode & S_IXUSR) {
836                         return "executable";
837                 } else {
838                         return "file";
839                 };
840         } else {
841                 return "unknown";
842         }
846 ## ----------------------------------------------------------------------
847 ## functions returning short HTML fragments, or transforming HTML fragments
848 ## which don't belong to other sections
850 # format line of commit message.
851 sub format_log_line_html {
852         my $line = shift;
854         $line = esc_html($line, -nbsp=>1);
855         if ($line =~ m/([0-9a-fA-F]{8,40})/) {
856                 my $hash_text = $1;
857                 my $link =
858                         $cgi->a({-href => href(action=>"object", hash=>$hash_text),
859                                 -class => "text"}, $hash_text);
860                 $line =~ s/$hash_text/$link/;
861         }
862         return $line;
865 # format marker of refs pointing to given object
866 sub format_ref_marker {
867         my ($refs, $id) = @_;
868         my $markers = '';
870         if (defined $refs->{$id}) {
871                 foreach my $ref (@{$refs->{$id}}) {
872                         my ($type, $name) = qw();
873                         # e.g. tags/v2.6.11 or heads/next
874                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
875                                 $type = $1;
876                                 $name = $2;
877                         } else {
878                                 $type = "ref";
879                                 $name = $ref;
880                         }
882                         $markers .= " <span class=\"$type\" title=\"$ref\">" .
883                                     esc_html($name) . "</span>";
884                 }
885         }
887         if ($markers) {
888                 return ' <span class="refs">'. $markers . '</span>';
889         } else {
890                 return "";
891         }
894 # format, perhaps shortened and with markers, title line
895 sub format_subject_html {
896         my ($long, $short, $href, $extra) = @_;
897         $extra = '' unless defined($extra);
899         if (length($short) < length($long)) {
900                 return $cgi->a({-href => $href, -class => "list subject",
901                                 -title => decode_utf8($long)},
902                        esc_html($short) . $extra);
903         } else {
904                 return $cgi->a({-href => $href, -class => "list subject"},
905                        esc_html($long)  . $extra);
906         }
909 # format patch (diff) line (rather not to be used for diff headers)
910 sub format_diff_line {
911         my $line = shift;
912         my ($from, $to) = @_;
913         my $diff_class = "";
915         chomp $line;
917         if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
918                 # combined diff
919                 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
920                 if ($line =~ m/^\@{3}/) {
921                         $diff_class = " chunk_header";
922                 } elsif ($line =~ m/^\\/) {
923                         $diff_class = " incomplete";
924                 } elsif ($prefix =~ tr/+/+/) {
925                         $diff_class = " add";
926                 } elsif ($prefix =~ tr/-/-/) {
927                         $diff_class = " rem";
928                 }
929         } else {
930                 # assume ordinary diff
931                 my $char = substr($line, 0, 1);
932                 if ($char eq '+') {
933                         $diff_class = " add";
934                 } elsif ($char eq '-') {
935                         $diff_class = " rem";
936                 } elsif ($char eq '@') {
937                         $diff_class = " chunk_header";
938                 } elsif ($char eq "\\") {
939                         $diff_class = " incomplete";
940                 }
941         }
942         $line = untabify($line);
943         if ($from && $to && $line =~ m/^\@{2} /) {
944                 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
945                         $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
947                 $from_lines = 0 unless defined $from_lines;
948                 $to_lines   = 0 unless defined $to_lines;
950                 if ($from->{'href'}) {
951                         $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
952                                              -class=>"list"}, $from_text);
953                 }
954                 if ($to->{'href'}) {
955                         $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
956                                              -class=>"list"}, $to_text);
957                 }
958                 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
959                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
960                 return "<div class=\"diff$diff_class\">$line</div>\n";
961         } elsif ($from && $to && $line =~ m/^\@{3}/) {
962                 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
963                 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
965                 @from_text = split(' ', $ranges);
966                 for (my $i = 0; $i < @from_text; ++$i) {
967                         ($from_start[$i], $from_nlines[$i]) =
968                                 (split(',', substr($from_text[$i], 1)), 0);
969                 }
971                 $to_text   = pop @from_text;
972                 $to_start  = pop @from_start;
973                 $to_nlines = pop @from_nlines;
975                 $line = "<span class=\"chunk_info\">$prefix ";
976                 for (my $i = 0; $i < @from_text; ++$i) {
977                         if ($from->{'href'}[$i]) {
978                                 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
979                                                   -class=>"list"}, $from_text[$i]);
980                         } else {
981                                 $line .= $from_text[$i];
982                         }
983                         $line .= " ";
984                 }
985                 if ($to->{'href'}) {
986                         $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
987                                           -class=>"list"}, $to_text);
988                 } else {
989                         $line .= $to_text;
990                 }
991                 $line .= " $prefix</span>" .
992                          "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
993                 return "<div class=\"diff$diff_class\">$line</div>\n";
994         }
995         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
998 ## ----------------------------------------------------------------------
999 ## git utility subroutines, invoking git commands
1001 # returns path to the core git executable and the --git-dir parameter as list
1002 sub git_cmd {
1003         return $GIT, '--git-dir='.$git_dir;
1006 # returns path to the core git executable and the --git-dir parameter as string
1007 sub git_cmd_str {
1008         return join(' ', git_cmd());
1011 # get HEAD ref of given project as hash
1012 sub git_get_head_hash {
1013         my $project = shift;
1014         my $o_git_dir = $git_dir;
1015         my $retval = undef;
1016         $git_dir = "$projectroot/$project";
1017         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1018                 my $head = <$fd>;
1019                 close $fd;
1020                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1021                         $retval = $1;
1022                 }
1023         }
1024         if (defined $o_git_dir) {
1025                 $git_dir = $o_git_dir;
1026         }
1027         return $retval;
1030 # get type of given object
1031 sub git_get_type {
1032         my $hash = shift;
1034         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1035         my $type = <$fd>;
1036         close $fd or return;
1037         chomp $type;
1038         return $type;
1041 sub git_get_project_config {
1042         my ($key, $type) = @_;
1044         return unless ($key);
1045         $key =~ s/^gitweb\.//;
1046         return if ($key =~ m/\W/);
1048         my @x = (git_cmd(), 'config');
1049         if (defined $type) { push @x, $type; }
1050         push @x, "--get";
1051         push @x, "gitweb.$key";
1052         my $val = qx(@x);
1053         chomp $val;
1054         return ($val);
1057 # get hash of given path at given ref
1058 sub git_get_hash_by_path {
1059         my $base = shift;
1060         my $path = shift || return undef;
1061         my $type = shift;
1063         $path =~ s,/+$,,;
1065         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1066                 or die_error(undef, "Open git-ls-tree failed");
1067         my $line = <$fd>;
1068         close $fd or return undef;
1070         if (!defined $line) {
1071                 # there is no tree or hash given by $path at $base
1072                 return undef;
1073         }
1075         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1076         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1077         if (defined $type && $type ne $2) {
1078                 # type doesn't match
1079                 return undef;
1080         }
1081         return $3;
1084 # get path of entry with given hash at given tree-ish (ref)
1085 # used to get 'from' filename for combined diff (merge commit) for renames
1086 sub git_get_path_by_hash {
1087         my $base = shift || return;
1088         my $hash = shift || return;
1090         local $/ = "\0";
1092         open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1093                 or return undef;
1094         while (my $line = <$fd>) {
1095                 chomp $line;
1097                 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
1098                 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
1099                 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1100                         close $fd;
1101                         return $1;
1102                 }
1103         }
1104         close $fd;
1105         return undef;
1108 ## ......................................................................
1109 ## git utility functions, directly accessing git repository
1111 sub git_get_project_description {
1112         my $path = shift;
1114         open my $fd, "$projectroot/$path/description" or return undef;
1115         my $descr = <$fd>;
1116         close $fd;
1117         chomp $descr;
1118         return $descr;
1121 sub git_get_project_url_list {
1122         my $path = shift;
1124         open my $fd, "$projectroot/$path/cloneurl" or return;
1125         my @git_project_url_list = map { chomp; $_ } <$fd>;
1126         close $fd;
1128         return wantarray ? @git_project_url_list : \@git_project_url_list;
1131 sub git_get_projects_list {
1132         my ($filter) = @_;
1133         my @list;
1135         $filter ||= '';
1136         $filter =~ s/\.git$//;
1138         my ($check_forks) = gitweb_check_feature('forks');
1140         if (-d $projects_list) {
1141                 # search in directory
1142                 my $dir = $projects_list . ($filter ? "/$filter" : '');
1143                 # remove the trailing "/"
1144                 $dir =~ s!/+$!!;
1145                 my $pfxlen = length("$dir");
1147                 File::Find::find({
1148                         follow_fast => 1, # follow symbolic links
1149                         dangling_symlinks => 0, # ignore dangling symlinks, silently
1150                         wanted => sub {
1151                                 # skip project-list toplevel, if we get it.
1152                                 return if (m!^[/.]$!);
1153                                 # only directories can be git repositories
1154                                 return unless (-d $_);
1156                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
1157                                 # we check related file in $projectroot
1158                                 if ($check_forks and $subdir =~ m#/.#) {
1159                                         $File::Find::prune = 1;
1160                                 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1161                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1162                                         $File::Find::prune = 1;
1163                                 }
1164                         },
1165                 }, "$dir");
1167         } elsif (-f $projects_list) {
1168                 # read from file(url-encoded):
1169                 # 'git%2Fgit.git Linus+Torvalds'
1170                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1171                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1172                 my %paths;
1173                 open my ($fd), $projects_list or return;
1174         PROJECT:
1175                 while (my $line = <$fd>) {
1176                         chomp $line;
1177                         my ($path, $owner) = split ' ', $line;
1178                         $path = unescape($path);
1179                         $owner = unescape($owner);
1180                         if (!defined $path) {
1181                                 next;
1182                         }
1183                         if ($filter ne '') {
1184                                 # looking for forks;
1185                                 my $pfx = substr($path, 0, length($filter));
1186                                 if ($pfx ne $filter) {
1187                                         next PROJECT;
1188                                 }
1189                                 my $sfx = substr($path, length($filter));
1190                                 if ($sfx !~ /^\/.*\.git$/) {
1191                                         next PROJECT;
1192                                 }
1193                         } elsif ($check_forks) {
1194                         PATH:
1195                                 foreach my $filter (keys %paths) {
1196                                         # looking for forks;
1197                                         my $pfx = substr($path, 0, length($filter));
1198                                         if ($pfx ne $filter) {
1199                                                 next PATH;
1200                                         }
1201                                         my $sfx = substr($path, length($filter));
1202                                         if ($sfx !~ /^\/.*\.git$/) {
1203                                                 next PATH;
1204                                         }
1205                                         # is a fork, don't include it in
1206                                         # the list
1207                                         next PROJECT;
1208                                 }
1209                         }
1210                         if (check_export_ok("$projectroot/$path")) {
1211                                 my $pr = {
1212                                         path => $path,
1213                                         owner => decode_utf8($owner),
1214                                 };
1215                                 push @list, $pr;
1216                                 (my $forks_path = $path) =~ s/\.git$//;
1217                                 $paths{$forks_path}++;
1218                         }
1219                 }
1220                 close $fd;
1221         }
1222         return @list;
1225 sub git_get_project_owner {
1226         my $project = shift;
1227         my $owner;
1229         return undef unless $project;
1231         # read from file (url-encoded):
1232         # 'git%2Fgit.git Linus+Torvalds'
1233         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1234         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1235         if (-f $projects_list) {
1236                 open (my $fd , $projects_list);
1237                 while (my $line = <$fd>) {
1238                         chomp $line;
1239                         my ($pr, $ow) = split ' ', $line;
1240                         $pr = unescape($pr);
1241                         $ow = unescape($ow);
1242                         if ($pr eq $project) {
1243                                 $owner = decode_utf8($ow);
1244                                 last;
1245                         }
1246                 }
1247                 close $fd;
1248         }
1249         if (!defined $owner) {
1250                 $owner = get_file_owner("$projectroot/$project");
1251         }
1253         return $owner;
1256 sub git_get_last_activity {
1257         my ($path) = @_;
1258         my $fd;
1260         $git_dir = "$projectroot/$path";
1261         open($fd, "-|", git_cmd(), 'for-each-ref',
1262              '--format=%(committer)',
1263              '--sort=-committerdate',
1264              '--count=1',
1265              'refs/heads') or return;
1266         my $most_recent = <$fd>;
1267         close $fd or return;
1268         if (defined $most_recent &&
1269             $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1270                 my $timestamp = $1;
1271                 my $age = time - $timestamp;
1272                 return ($age, age_string($age));
1273         }
1276 sub git_get_references {
1277         my $type = shift || "";
1278         my %refs;
1279         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1280         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1281         open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1282                 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1283                 or return;
1285         while (my $line = <$fd>) {
1286                 chomp $line;
1287                 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1288                         if (defined $refs{$1}) {
1289                                 push @{$refs{$1}}, $2;
1290                         } else {
1291                                 $refs{$1} = [ $2 ];
1292                         }
1293                 }
1294         }
1295         close $fd or return;
1296         return \%refs;
1299 sub git_get_rev_name_tags {
1300         my $hash = shift || return undef;
1302         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1303                 or return;
1304         my $name_rev = <$fd>;
1305         close $fd;
1307         if ($name_rev =~ m|^$hash tags/(.*)$|) {
1308                 return $1;
1309         } else {
1310                 # catches also '$hash undefined' output
1311                 return undef;
1312         }
1315 ## ----------------------------------------------------------------------
1316 ## parse to hash functions
1318 sub parse_date {
1319         my $epoch = shift;
1320         my $tz = shift || "-0000";
1322         my %date;
1323         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1324         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1325         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1326         $date{'hour'} = $hour;
1327         $date{'minute'} = $min;
1328         $date{'mday'} = $mday;
1329         $date{'day'} = $days[$wday];
1330         $date{'month'} = $months[$mon];
1331         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1332                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1333         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1334                              $mday, $months[$mon], $hour ,$min;
1335         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1336                              1900+$year, $mon, $mday, $hour ,$min, $sec;
1338         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1339         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1340         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1341         $date{'hour_local'} = $hour;
1342         $date{'minute_local'} = $min;
1343         $date{'tz_local'} = $tz;
1344         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1345                                   1900+$year, $mon+1, $mday,
1346                                   $hour, $min, $sec, $tz);
1347         return %date;
1350 sub parse_tag {
1351         my $tag_id = shift;
1352         my %tag;
1353         my @comment;
1355         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1356         $tag{'id'} = $tag_id;
1357         while (my $line = <$fd>) {
1358                 chomp $line;
1359                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1360                         $tag{'object'} = $1;
1361                 } elsif ($line =~ m/^type (.+)$/) {
1362                         $tag{'type'} = $1;
1363                 } elsif ($line =~ m/^tag (.+)$/) {
1364                         $tag{'name'} = $1;
1365                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1366                         $tag{'author'} = $1;
1367                         $tag{'epoch'} = $2;
1368                         $tag{'tz'} = $3;
1369                 } elsif ($line =~ m/--BEGIN/) {
1370                         push @comment, $line;
1371                         last;
1372                 } elsif ($line eq "") {
1373                         last;
1374                 }
1375         }
1376         push @comment, <$fd>;
1377         $tag{'comment'} = \@comment;
1378         close $fd or return;
1379         if (!defined $tag{'name'}) {
1380                 return
1381         };
1382         return %tag
1385 sub parse_commit_text {
1386         my ($commit_text, $withparents) = @_;
1387         my @commit_lines = split '\n', $commit_text;
1388         my %co;
1390         pop @commit_lines; # Remove '\0'
1392         if (! @commit_lines) {
1393                 return;
1394         }
1396         my $header = shift @commit_lines;
1397         if ($header !~ m/^[0-9a-fA-F]{40}/) {
1398                 return;
1399         }
1400         ($co{'id'}, my @parents) = split ' ', $header;
1401         while (my $line = shift @commit_lines) {
1402                 last if $line eq "\n";
1403                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1404                         $co{'tree'} = $1;
1405                 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1406                         push @parents, $1;
1407                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1408                         $co{'author'} = $1;
1409                         $co{'author_epoch'} = $2;
1410                         $co{'author_tz'} = $3;
1411                         if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1412                                 $co{'author_name'}  = $1;
1413                                 $co{'author_email'} = $2;
1414                         } else {
1415                                 $co{'author_name'} = $co{'author'};
1416                         }
1417                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1418                         $co{'committer'} = $1;
1419                         $co{'committer_epoch'} = $2;
1420                         $co{'committer_tz'} = $3;
1421                         $co{'committer_name'} = $co{'committer'};
1422                         if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1423                                 $co{'committer_name'}  = $1;
1424                                 $co{'committer_email'} = $2;
1425                         } else {
1426                                 $co{'committer_name'} = $co{'committer'};
1427                         }
1428                 }
1429         }
1430         if (!defined $co{'tree'}) {
1431                 return;
1432         };
1433         $co{'parents'} = \@parents;
1434         $co{'parent'} = $parents[0];
1436         foreach my $title (@commit_lines) {
1437                 $title =~ s/^    //;
1438                 if ($title ne "") {
1439                         $co{'title'} = chop_str($title, 80, 5);
1440                         # remove leading stuff of merges to make the interesting part visible
1441                         if (length($title) > 50) {
1442                                 $title =~ s/^Automatic //;
1443                                 $title =~ s/^merge (of|with) /Merge ... /i;
1444                                 if (length($title) > 50) {
1445                                         $title =~ s/(http|rsync):\/\///;
1446                                 }
1447                                 if (length($title) > 50) {
1448                                         $title =~ s/(master|www|rsync)\.//;
1449                                 }
1450                                 if (length($title) > 50) {
1451                                         $title =~ s/kernel.org:?//;
1452                                 }
1453                                 if (length($title) > 50) {
1454                                         $title =~ s/\/pub\/scm//;
1455                                 }
1456                         }
1457                         $co{'title_short'} = chop_str($title, 50, 5);
1458                         last;
1459                 }
1460         }
1461         if ($co{'title'} eq "") {
1462                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1463         }
1464         # remove added spaces
1465         foreach my $line (@commit_lines) {
1466                 $line =~ s/^    //;
1467         }
1468         $co{'comment'} = \@commit_lines;
1470         my $age = time - $co{'committer_epoch'};
1471         $co{'age'} = $age;
1472         $co{'age_string'} = age_string($age);
1473         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1474         if ($age > 60*60*24*7*2) {
1475                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1476                 $co{'age_string_age'} = $co{'age_string'};
1477         } else {
1478                 $co{'age_string_date'} = $co{'age_string'};
1479                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1480         }
1481         return %co;
1484 sub parse_commit {
1485         my ($commit_id) = @_;
1486         my %co;
1488         local $/ = "\0";
1490         open my $fd, "-|", git_cmd(), "rev-list",
1491                 "--parents",
1492                 "--header",
1493                 "--max-count=1",
1494                 $commit_id,
1495                 "--",
1496                 or die_error(undef, "Open git-rev-list failed");
1497         %co = parse_commit_text(<$fd>, 1);
1498         close $fd;
1500         return %co;
1503 sub parse_commits {
1504         my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1505         my @cos;
1507         $maxcount ||= 1;
1508         $skip ||= 0;
1510         local $/ = "\0";
1512         open my $fd, "-|", git_cmd(), "rev-list",
1513                 "--header",
1514                 ($arg ? ($arg) : ()),
1515                 ("--max-count=" . $maxcount),
1516                 ("--skip=" . $skip),
1517                 $commit_id,
1518                 "--",
1519                 ($filename ? ($filename) : ())
1520                 or die_error(undef, "Open git-rev-list failed");
1521         while (my $line = <$fd>) {
1522                 my %co = parse_commit_text($line);
1523                 push @cos, \%co;
1524         }
1525         close $fd;
1527         return wantarray ? @cos : \@cos;
1530 # parse ref from ref_file, given by ref_id, with given type
1531 sub parse_ref {
1532         my $ref_file = shift;
1533         my $ref_id = shift;
1534         my $type = shift || git_get_type($ref_id);
1535         my %ref_item;
1537         $ref_item{'type'} = $type;
1538         $ref_item{'id'} = $ref_id;
1539         $ref_item{'epoch'} = 0;
1540         $ref_item{'age'} = "unknown";
1541         if ($type eq "tag") {
1542                 my %tag = parse_tag($ref_id);
1543                 $ref_item{'comment'} = $tag{'comment'};
1544                 if ($tag{'type'} eq "commit") {
1545                         my %co = parse_commit($tag{'object'});
1546                         $ref_item{'epoch'} = $co{'committer_epoch'};
1547                         $ref_item{'age'} = $co{'age_string'};
1548                 } elsif (defined($tag{'epoch'})) {
1549                         my $age = time - $tag{'epoch'};
1550                         $ref_item{'epoch'} = $tag{'epoch'};
1551                         $ref_item{'age'} = age_string($age);
1552                 }
1553                 $ref_item{'reftype'} = $tag{'type'};
1554                 $ref_item{'name'} = $tag{'name'};
1555                 $ref_item{'refid'} = $tag{'object'};
1556         } elsif ($type eq "commit"){
1557                 my %co = parse_commit($ref_id);
1558                 $ref_item{'reftype'} = "commit";
1559                 $ref_item{'name'} = $ref_file;
1560                 $ref_item{'title'} = $co{'title'};
1561                 $ref_item{'refid'} = $ref_id;
1562                 $ref_item{'epoch'} = $co{'committer_epoch'};
1563                 $ref_item{'age'} = $co{'age_string'};
1564         } else {
1565                 $ref_item{'reftype'} = $type;
1566                 $ref_item{'name'} = $ref_file;
1567                 $ref_item{'refid'} = $ref_id;
1568         }
1570         return %ref_item;
1573 # parse line of git-diff-tree "raw" output
1574 sub parse_difftree_raw_line {
1575         my $line = shift;
1576         my %res;
1578         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1579         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1580         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1581                 $res{'from_mode'} = $1;
1582                 $res{'to_mode'} = $2;
1583                 $res{'from_id'} = $3;
1584                 $res{'to_id'} = $4;
1585                 $res{'status'} = $5;
1586                 $res{'similarity'} = $6;
1587                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1588                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1589                 } else {
1590                         $res{'file'} = unquote($7);
1591                 }
1592         }
1593         # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
1594         # combined diff (for merge commit)
1595         elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
1596                 $res{'nparents'}  = length($1);
1597                 $res{'from_mode'} = [ split(' ', $2) ];
1598                 $res{'to_mode'} = pop @{$res{'from_mode'}};
1599                 $res{'from_id'} = [ split(' ', $3) ];
1600                 $res{'to_id'} = pop @{$res{'from_id'}};
1601                 $res{'status'} = [ split('', $4) ];
1602                 $res{'to_file'} = unquote($5);
1603         }
1604         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1605         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1606                 $res{'commit'} = $1;
1607         }
1609         return wantarray ? %res : \%res;
1612 # parse line of git-ls-tree output
1613 sub parse_ls_tree_line ($;%) {
1614         my $line = shift;
1615         my %opts = @_;
1616         my %res;
1618         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1619         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1621         $res{'mode'} = $1;
1622         $res{'type'} = $2;
1623         $res{'hash'} = $3;
1624         if ($opts{'-z'}) {
1625                 $res{'name'} = $4;
1626         } else {
1627                 $res{'name'} = unquote($4);
1628         }
1630         return wantarray ? %res : \%res;
1633 ## ......................................................................
1634 ## parse to array of hashes functions
1636 sub git_get_heads_list {
1637         my $limit = shift;
1638         my @headslist;
1640         open my $fd, '-|', git_cmd(), 'for-each-ref',
1641                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1642                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1643                 'refs/heads'
1644                 or return;
1645         while (my $line = <$fd>) {
1646                 my %ref_item;
1648                 chomp $line;
1649                 my ($refinfo, $committerinfo) = split(/\0/, $line);
1650                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
1651                 my ($committer, $epoch, $tz) =
1652                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1653                 $name =~ s!^refs/heads/!!;
1655                 $ref_item{'name'}  = $name;
1656                 $ref_item{'id'}    = $hash;
1657                 $ref_item{'title'} = $title || '(no commit message)';
1658                 $ref_item{'epoch'} = $epoch;
1659                 if ($epoch) {
1660                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1661                 } else {
1662                         $ref_item{'age'} = "unknown";
1663                 }
1665                 push @headslist, \%ref_item;
1666         }
1667         close $fd;
1669         return wantarray ? @headslist : \@headslist;
1672 sub git_get_tags_list {
1673         my $limit = shift;
1674         my @tagslist;
1676         open my $fd, '-|', git_cmd(), 'for-each-ref',
1677                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1678                 '--format=%(objectname) %(objecttype) %(refname) '.
1679                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
1680                 'refs/tags'
1681                 or return;
1682         while (my $line = <$fd>) {
1683                 my %ref_item;
1685                 chomp $line;
1686                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
1687                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
1688                 my ($creator, $epoch, $tz) =
1689                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
1690                 $name =~ s!^refs/tags/!!;
1692                 $ref_item{'type'} = $type;
1693                 $ref_item{'id'} = $id;
1694                 $ref_item{'name'} = $name;
1695                 if ($type eq "tag") {
1696                         $ref_item{'subject'} = $title;
1697                         $ref_item{'reftype'} = $reftype;
1698                         $ref_item{'refid'}   = $refid;
1699                 } else {
1700                         $ref_item{'reftype'} = $type;
1701                         $ref_item{'refid'}   = $id;
1702                 }
1704                 if ($type eq "tag" || $type eq "commit") {
1705                         $ref_item{'epoch'} = $epoch;
1706                         if ($epoch) {
1707                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1708                         } else {
1709                                 $ref_item{'age'} = "unknown";
1710                         }
1711                 }
1713                 push @tagslist, \%ref_item;
1714         }
1715         close $fd;
1717         return wantarray ? @tagslist : \@tagslist;
1720 ## ----------------------------------------------------------------------
1721 ## filesystem-related functions
1723 sub get_file_owner {
1724         my $path = shift;
1726         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1727         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1728         if (!defined $gcos) {
1729                 return undef;
1730         }
1731         my $owner = $gcos;
1732         $owner =~ s/[,;].*$//;
1733         return decode_utf8($owner);
1736 ## ......................................................................
1737 ## mimetype related functions
1739 sub mimetype_guess_file {
1740         my $filename = shift;
1741         my $mimemap = shift;
1742         -r $mimemap or return undef;
1744         my %mimemap;
1745         open(MIME, $mimemap) or return undef;
1746         while (<MIME>) {
1747                 next if m/^#/; # skip comments
1748                 my ($mime, $exts) = split(/\t+/);
1749                 if (defined $exts) {
1750                         my @exts = split(/\s+/, $exts);
1751                         foreach my $ext (@exts) {
1752                                 $mimemap{$ext} = $mime;
1753                         }
1754                 }
1755         }
1756         close(MIME);
1758         $filename =~ /\.([^.]*)$/;
1759         return $mimemap{$1};
1762 sub mimetype_guess {
1763         my $filename = shift;
1764         my $mime;
1765         $filename =~ /\./ or return undef;
1767         if ($mimetypes_file) {
1768                 my $file = $mimetypes_file;
1769                 if ($file !~ m!^/!) { # if it is relative path
1770                         # it is relative to project
1771                         $file = "$projectroot/$project/$file";
1772                 }
1773                 $mime = mimetype_guess_file($filename, $file);
1774         }
1775         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1776         return $mime;
1779 sub blob_mimetype {
1780         my $fd = shift;
1781         my $filename = shift;
1783         if ($filename) {
1784                 my $mime = mimetype_guess($filename);
1785                 $mime and return $mime;
1786         }
1788         # just in case
1789         return $default_blob_plain_mimetype unless $fd;
1791         if (-T $fd) {
1792                 return 'text/plain' .
1793                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1794         } elsif (! $filename) {
1795                 return 'application/octet-stream';
1796         } elsif ($filename =~ m/\.png$/i) {
1797                 return 'image/png';
1798         } elsif ($filename =~ m/\.gif$/i) {
1799                 return 'image/gif';
1800         } elsif ($filename =~ m/\.jpe?g$/i) {
1801                 return 'image/jpeg';
1802         } else {
1803                 return 'application/octet-stream';
1804         }
1807 ## ======================================================================
1808 ## functions printing HTML: header, footer, error page
1810 sub git_header_html {
1811         my $status = shift || "200 OK";
1812         my $expires = shift;
1814         my $title = "$site_name";
1815         if (defined $project) {
1816                 $title .= " - " . decode_utf8($project);
1817                 if (defined $action) {
1818                         $title .= "/$action";
1819                         if (defined $file_name) {
1820                                 $title .= " - " . esc_path($file_name);
1821                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1822                                         $title .= "/";
1823                                 }
1824                         }
1825                 }
1826         }
1827         my $content_type;
1828         # require explicit support from the UA if we are to send the page as
1829         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1830         # we have to do this because MSIE sometimes globs '*/*', pretending to
1831         # support xhtml+xml but choking when it gets what it asked for.
1832         if (defined $cgi->http('HTTP_ACCEPT') &&
1833             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1834             $cgi->Accept('application/xhtml+xml') != 0) {
1835                 $content_type = 'application/xhtml+xml';
1836         } else {
1837                 $content_type = 'text/html';
1838         }
1839         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1840                            -status=> $status, -expires => $expires);
1841         my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
1842         print <<EOF;
1843 <?xml version="1.0" encoding="utf-8"?>
1844 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1845 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1846 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1847 <!-- git core binaries version $git_version -->
1848 <head>
1849 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1850 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
1851 <meta name="robots" content="index, nofollow"/>
1852 <title>$title</title>
1853 EOF
1854 # print out each stylesheet that exist
1855         if (defined $stylesheet) {
1856 #provides backwards capability for those people who define style sheet in a config file
1857                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1858         } else {
1859                 foreach my $stylesheet (@stylesheets) {
1860                         next unless $stylesheet;
1861                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1862                 }
1863         }
1864         if (defined $project) {
1865                 printf('<link rel="alternate" title="%s log RSS feed" '.
1866                        'href="%s" type="application/rss+xml" />'."\n",
1867                        esc_param($project), href(action=>"rss"));
1868                 printf('<link rel="alternate" title="%s log Atom feed" '.
1869                        'href="%s" type="application/atom+xml" />'."\n",
1870                        esc_param($project), href(action=>"atom"));
1871         } else {
1872                 printf('<link rel="alternate" title="%s projects list" '.
1873                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1874                        $site_name, href(project=>undef, action=>"project_index"));
1875                 printf('<link rel="alternate" title="%s projects feeds" '.
1876                        'href="%s" type="text/x-opml"/>'."\n",
1877                        $site_name, href(project=>undef, action=>"opml"));
1878         }
1879         if (defined $favicon) {
1880                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1881         }
1883         print "</head>\n" .
1884               "<body>\n";
1886         if (-f $site_header) {
1887                 open (my $fd, $site_header);
1888                 print <$fd>;
1889                 close $fd;
1890         }
1892         print "<div class=\"page_header\">\n" .
1893               $cgi->a({-href => esc_url($logo_url),
1894                        -title => $logo_label},
1895                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1896         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1897         if (defined $project) {
1898                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1899                 if (defined $action) {
1900                         print " / $action";
1901                 }
1902                 print "\n";
1903         }
1904         my ($have_search) = gitweb_check_feature('search');
1905         if ((defined $project) && ($have_search)) {
1906                 if (!defined $searchtext) {
1907                         $searchtext = "";
1908                 }
1909                 my $search_hash;
1910                 if (defined $hash_base) {
1911                         $search_hash = $hash_base;
1912                 } elsif (defined $hash) {
1913                         $search_hash = $hash;
1914                 } else {
1915                         $search_hash = "HEAD";
1916                 }
1917                 $cgi->param("a", "search");
1918                 $cgi->param("h", $search_hash);
1919                 $cgi->param("p", $project);
1920                 print $cgi->startform(-method => "get", -action => $my_uri) .
1921                       "<div class=\"search\">\n" .
1922                       $cgi->hidden(-name => "p") . "\n" .
1923                       $cgi->hidden(-name => "a") . "\n" .
1924                       $cgi->hidden(-name => "h") . "\n" .
1925                       $cgi->popup_menu(-name => 'st', -default => 'commit',
1926                                        -values => ['commit', 'author', 'committer', 'pickaxe']) .
1927                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
1928                       " search:\n",
1929                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1930                       "</div>" .
1931                       $cgi->end_form() . "\n";
1932         }
1933         print "</div>\n";
1936 sub git_footer_html {
1937         print "<div class=\"page_footer\">\n";
1938         if (defined $project) {
1939                 my $descr = git_get_project_description($project);
1940                 if (defined $descr) {
1941                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1942                 }
1943                 print $cgi->a({-href => href(action=>"rss"),
1944                               -class => "rss_logo"}, "RSS") . " ";
1945                 print $cgi->a({-href => href(action=>"atom"),
1946                               -class => "rss_logo"}, "Atom") . "\n";
1947         } else {
1948                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1949                               -class => "rss_logo"}, "OPML") . " ";
1950                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1951                               -class => "rss_logo"}, "TXT") . "\n";
1952         }
1953         print "</div>\n" ;
1955         if (-f $site_footer) {
1956                 open (my $fd, $site_footer);
1957                 print <$fd>;
1958                 close $fd;
1959         }
1961         print "</body>\n" .
1962               "</html>";
1965 sub die_error {
1966         my $status = shift || "403 Forbidden";
1967         my $error = shift || "Malformed query, file missing or permission denied";
1969         git_header_html($status);
1970         print <<EOF;
1971 <div class="page_body">
1972 <br /><br />
1973 $status - $error
1974 <br />
1975 </div>
1976 EOF
1977         git_footer_html();
1978         exit;
1981 ## ----------------------------------------------------------------------
1982 ## functions printing or outputting HTML: navigation
1984 sub git_print_page_nav {
1985         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1986         $extra = '' if !defined $extra; # pager or formats
1988         my @navs = qw(summary shortlog log commit commitdiff tree);
1989         if ($suppress) {
1990                 @navs = grep { $_ ne $suppress } @navs;
1991         }
1993         my %arg = map { $_ => {action=>$_} } @navs;
1994         if (defined $head) {
1995                 for (qw(commit commitdiff)) {
1996                         $arg{$_}{'hash'} = $head;
1997                 }
1998                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1999                         for (qw(shortlog log)) {
2000                                 $arg{$_}{'hash'} = $head;
2001                         }
2002                 }
2003         }
2004         $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2005         $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2007         print "<div class=\"page_nav\">\n" .
2008                 (join " | ",
2009                  map { $_ eq $current ?
2010                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2011                  } @navs);
2012         print "<br/>\n$extra<br/>\n" .
2013               "</div>\n";
2016 sub format_paging_nav {
2017         my ($action, $hash, $head, $page, $nrevs) = @_;
2018         my $paging_nav;
2021         if ($hash ne $head || $page) {
2022                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2023         } else {
2024                 $paging_nav .= "HEAD";
2025         }
2027         if ($page > 0) {
2028                 $paging_nav .= " &sdot; " .
2029                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
2030                                  -accesskey => "p", -title => "Alt-p"}, "prev");
2031         } else {
2032                 $paging_nav .= " &sdot; prev";
2033         }
2035         if ($nrevs >= (100 * ($page+1)-1)) {
2036                 $paging_nav .= " &sdot; " .
2037                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
2038                                  -accesskey => "n", -title => "Alt-n"}, "next");
2039         } else {
2040                 $paging_nav .= " &sdot; next";
2041         }
2043         return $paging_nav;
2046 ## ......................................................................
2047 ## functions printing or outputting HTML: div
2049 sub git_print_header_div {
2050         my ($action, $title, $hash, $hash_base) = @_;
2051         my %args = ();
2053         $args{'action'} = $action;
2054         $args{'hash'} = $hash if $hash;
2055         $args{'hash_base'} = $hash_base if $hash_base;
2057         print "<div class=\"header\">\n" .
2058               $cgi->a({-href => href(%args), -class => "title"},
2059               $title ? $title : $action) .
2060               "\n</div>\n";
2063 #sub git_print_authorship (\%) {
2064 sub git_print_authorship {
2065         my $co = shift;
2067         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2068         print "<div class=\"author_date\">" .
2069               esc_html($co->{'author_name'}) .
2070               " [$ad{'rfc2822'}";
2071         if ($ad{'hour_local'} < 6) {
2072                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2073                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2074         } else {
2075                 printf(" (%02d:%02d %s)",
2076                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2077         }
2078         print "]</div>\n";
2081 sub git_print_page_path {
2082         my $name = shift;
2083         my $type = shift;
2084         my $hb = shift;
2087         print "<div class=\"page_path\">";
2088         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2089                       -title => 'tree root'}, decode_utf8("[$project]"));
2090         print " / ";
2091         if (defined $name) {
2092                 my @dirname = split '/', $name;
2093                 my $basename = pop @dirname;
2094                 my $fullname = '';
2096                 foreach my $dir (@dirname) {
2097                         $fullname .= ($fullname ? '/' : '') . $dir;
2098                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2099                                                      hash_base=>$hb),
2100                                       -title => $fullname}, esc_path($dir));
2101                         print " / ";
2102                 }
2103                 if (defined $type && $type eq 'blob') {
2104                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2105                                                      hash_base=>$hb),
2106                                       -title => $name}, esc_path($basename));
2107                 } elsif (defined $type && $type eq 'tree') {
2108                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2109                                                      hash_base=>$hb),
2110                                       -title => $name}, esc_path($basename));
2111                         print " / ";
2112                 } else {
2113                         print esc_path($basename);
2114                 }
2115         }
2116         print "<br/></div>\n";
2119 # sub git_print_log (\@;%) {
2120 sub git_print_log ($;%) {
2121         my $log = shift;
2122         my %opts = @_;
2124         if ($opts{'-remove_title'}) {
2125                 # remove title, i.e. first line of log
2126                 shift @$log;
2127         }
2128         # remove leading empty lines
2129         while (defined $log->[0] && $log->[0] eq "") {
2130                 shift @$log;
2131         }
2133         # print log
2134         my $signoff = 0;
2135         my $empty = 0;
2136         foreach my $line (@$log) {
2137                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2138                         $signoff = 1;
2139                         $empty = 0;
2140                         if (! $opts{'-remove_signoff'}) {
2141                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2142                                 next;
2143                         } else {
2144                                 # remove signoff lines
2145                                 next;
2146                         }
2147                 } else {
2148                         $signoff = 0;
2149                 }
2151                 # print only one empty line
2152                 # do not print empty line after signoff
2153                 if ($line eq "") {
2154                         next if ($empty || $signoff);
2155                         $empty = 1;
2156                 } else {
2157                         $empty = 0;
2158                 }
2160                 print format_log_line_html($line) . "<br/>\n";
2161         }
2163         if ($opts{'-final_empty_line'}) {
2164                 # end with single empty line
2165                 print "<br/>\n" unless $empty;
2166         }
2169 # return link target (what link points to)
2170 sub git_get_link_target {
2171         my $hash = shift;
2172         my $link_target;
2174         # read link
2175         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2176                 or return;
2177         {
2178                 local $/;
2179                 $link_target = <$fd>;
2180         }
2181         close $fd
2182                 or return;
2184         return $link_target;
2187 # given link target, and the directory (basedir) the link is in,
2188 # return target of link relative to top directory (top tree);
2189 # return undef if it is not possible (including absolute links).
2190 sub normalize_link_target {
2191         my ($link_target, $basedir, $hash_base) = @_;
2193         # we can normalize symlink target only if $hash_base is provided
2194         return unless $hash_base;
2196         # absolute symlinks (beginning with '/') cannot be normalized
2197         return if (substr($link_target, 0, 1) eq '/');
2199         # normalize link target to path from top (root) tree (dir)
2200         my $path;
2201         if ($basedir) {
2202                 $path = $basedir . '/' . $link_target;
2203         } else {
2204                 # we are in top (root) tree (dir)
2205                 $path = $link_target;
2206         }
2208         # remove //, /./, and /../
2209         my @path_parts;
2210         foreach my $part (split('/', $path)) {
2211                 # discard '.' and ''
2212                 next if (!$part || $part eq '.');
2213                 # handle '..'
2214                 if ($part eq '..') {
2215                         if (@path_parts) {
2216                                 pop @path_parts;
2217                         } else {
2218                                 # link leads outside repository (outside top dir)
2219                                 return;
2220                         }
2221                 } else {
2222                         push @path_parts, $part;
2223                 }
2224         }
2225         $path = join('/', @path_parts);
2227         return $path;
2230 # print tree entry (row of git_tree), but without encompassing <tr> element
2231 sub git_print_tree_entry {
2232         my ($t, $basedir, $hash_base, $have_blame) = @_;
2234         my %base_key = ();
2235         $base_key{'hash_base'} = $hash_base if defined $hash_base;
2237         # The format of a table row is: mode list link.  Where mode is
2238         # the mode of the entry, list is the name of the entry, an href,
2239         # and link is the action links of the entry.
2241         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2242         if ($t->{'type'} eq "blob") {
2243                 print "<td class=\"list\">" .
2244                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2245                                                file_name=>"$basedir$t->{'name'}", %base_key),
2246                                 -class => "list"}, esc_path($t->{'name'}));
2247                 if (S_ISLNK(oct $t->{'mode'})) {
2248                         my $link_target = git_get_link_target($t->{'hash'});
2249                         if ($link_target) {
2250                                 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2251                                 if (defined $norm_target) {
2252                                         print " -> " .
2253                                               $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2254                                                                      file_name=>$norm_target),
2255                                                        -title => $norm_target}, esc_path($link_target));
2256                                 } else {
2257                                         print " -> " . esc_path($link_target);
2258                                 }
2259                         }
2260                 }
2261                 print "</td>\n";
2262                 print "<td class=\"link\">";
2263                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2264                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2265                               "blob");
2266                 if ($have_blame) {
2267                         print " | " .
2268                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2269                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
2270                                       "blame");
2271                 }
2272                 if (defined $hash_base) {
2273                         print " | " .
2274                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2275                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2276                                       "history");
2277                 }
2278                 print " | " .
2279                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2280                                                file_name=>"$basedir$t->{'name'}")},
2281                                 "raw");
2282                 print "</td>\n";
2284         } elsif ($t->{'type'} eq "tree") {
2285                 print "<td class=\"list\">";
2286                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2287                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2288                               esc_path($t->{'name'}));
2289                 print "</td>\n";
2290                 print "<td class=\"link\">";
2291                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2292                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2293                               "tree");
2294                 if (defined $hash_base) {
2295                         print " | " .
2296                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2297                                                      file_name=>"$basedir$t->{'name'}")},
2298                                       "history");
2299                 }
2300                 print "</td>\n";
2301         }
2304 ## ......................................................................
2305 ## functions printing large fragments of HTML
2307 sub fill_from_file_info {
2308         my ($diff, @parents) = @_;
2310         $diff->{'from_file'} = [ ];
2311         $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
2312         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2313                 if ($diff->{'status'}[$i] eq 'R' ||
2314                     $diff->{'status'}[$i] eq 'C') {
2315                         $diff->{'from_file'}[$i] =
2316                                 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
2317                 }
2318         }
2320         return $diff;
2323 # parameters can be strings, or references to arrays of strings
2324 sub from_ids_eq {
2325         my ($a, $b) = @_;
2327         if (ref($a) eq "ARRAY" && ref($b) eq "ARRAY" && @$a == @$b) {
2328                 for (my $i = 0; $i < @$a; ++$i) {
2329                         return 0 unless ($a->[$i] eq $b->[$i]);
2330                 }
2331                 return 1;
2332         } elsif (!ref($a) && !ref($b)) {
2333                 return $a eq $b;
2334         } else {
2335                 return 0;
2336         }
2340 sub git_difftree_body {
2341         my ($difftree, $hash, @parents) = @_;
2342         my ($parent) = $parents[0];
2343         my ($have_blame) = gitweb_check_feature('blame');
2344         print "<div class=\"list_head\">\n";
2345         if ($#{$difftree} > 10) {
2346                 print(($#{$difftree} + 1) . " files changed:\n");
2347         }
2348         print "</div>\n";
2350         print "<table class=\"" .
2351               (@parents > 1 ? "combined " : "") .
2352               "diff_tree\">\n";
2353         my $alternate = 1;
2354         my $patchno = 0;
2355         foreach my $line (@{$difftree}) {
2356                 my $diff;
2357                 if (ref($line) eq "HASH") {
2358                         # pre-parsed (or generated by hand)
2359                         $diff = $line;
2360                 } else {
2361                         $diff = parse_difftree_raw_line($line);
2362                 }
2364                 if ($alternate) {
2365                         print "<tr class=\"dark\">\n";
2366                 } else {
2367                         print "<tr class=\"light\">\n";
2368                 }
2369                 $alternate ^= 1;
2371                 if (exists $diff->{'nparents'}) { # combined diff
2373                         fill_from_file_info($diff, @parents)
2374                                 unless exists $diff->{'from_file'};
2376                         if ($diff->{'to_id'} ne ('0' x 40)) {
2377                                 # file exists in the result (child) commit
2378                                 print "<td>" .
2379                                       $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2380                                                              file_name=>$diff->{'to_file'},
2381                                                              hash_base=>$hash),
2382                                               -class => "list"}, esc_path($diff->{'to_file'})) .
2383                                       "</td>\n";
2384                         } else {
2385                                 print "<td>" .
2386                                       esc_path($diff->{'to_file'}) .
2387                                       "</td>\n";
2388                         }
2390                         if ($action eq 'commitdiff') {
2391                                 # link to patch
2392                                 $patchno++;
2393                                 print "<td class=\"link\">" .
2394                                       $cgi->a({-href => "#patch$patchno"}, "patch") .
2395                                       " | " .
2396                                       "</td>\n";
2397                         }
2399                         my $has_history = 0;
2400                         my $not_deleted = 0;
2401                         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2402                                 my $hash_parent = $parents[$i];
2403                                 my $from_hash = $diff->{'from_id'}[$i];
2404                                 my $from_path = $diff->{'from_file'}[$i];
2405                                 my $status = $diff->{'status'}[$i];
2407                                 $has_history ||= ($status ne 'A');
2408                                 $not_deleted ||= ($status ne 'D');
2410                                 if ($status eq 'A') {
2411                                         print "<td  class=\"link\" align=\"right\"> | </td>\n";
2412                                 } elsif ($status eq 'D') {
2413                                         print "<td class=\"link\">" .
2414                                               $cgi->a({-href => href(action=>"blob",
2415                                                                      hash_base=>$hash,
2416                                                                      hash=>$from_hash,
2417                                                                      file_name=>$from_path)},
2418                                                       "blob" . ($i+1)) .
2419                                               " | </td>\n";
2420                                 } else {
2421                                         if ($diff->{'to_id'} eq $from_hash) {
2422                                                 print "<td class=\"link nochange\">";
2423                                         } else {
2424                                                 print "<td class=\"link\">";
2425                                         }
2426                                         print $cgi->a({-href => href(action=>"blobdiff",
2427                                                                      hash=>$diff->{'to_id'},
2428                                                                      hash_parent=>$from_hash,
2429                                                                      hash_base=>$hash,
2430                                                                      hash_parent_base=>$hash_parent,
2431                                                                      file_name=>$diff->{'to_file'},
2432                                                                      file_parent=>$from_path)},
2433                                                       "diff" . ($i+1)) .
2434                                               " | </td>\n";
2435                                 }
2436                         }
2438                         print "<td class=\"link\">";
2439                         if ($not_deleted) {
2440                                 print $cgi->a({-href => href(action=>"blob",
2441                                                              hash=>$diff->{'to_id'},
2442                                                              file_name=>$diff->{'to_file'},
2443                                                              hash_base=>$hash)},
2444                                               "blob");
2445                                 print " | " if ($has_history);
2446                         }
2447                         if ($has_history) {
2448                                 print $cgi->a({-href => href(action=>"history",
2449                                                              file_name=>$diff->{'to_file'},
2450                                                              hash_base=>$hash)},
2451                                               "history");
2452                         }
2453                         print "</td>\n";
2455                         print "</tr>\n";
2456                         next; # instead of 'else' clause, to avoid extra indent
2457                 }
2458                 # else ordinary diff
2460                 my ($to_mode_oct, $to_mode_str, $to_file_type);
2461                 my ($from_mode_oct, $from_mode_str, $from_file_type);
2462                 if ($diff->{'to_mode'} ne ('0' x 6)) {
2463                         $to_mode_oct = oct $diff->{'to_mode'};
2464                         if (S_ISREG($to_mode_oct)) { # only for regular file
2465                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2466                         }
2467                         $to_file_type = file_type($diff->{'to_mode'});
2468                 }
2469                 if ($diff->{'from_mode'} ne ('0' x 6)) {
2470                         $from_mode_oct = oct $diff->{'from_mode'};
2471                         if (S_ISREG($to_mode_oct)) { # only for regular file
2472                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2473                         }
2474                         $from_file_type = file_type($diff->{'from_mode'});
2475                 }
2477                 if ($diff->{'status'} eq "A") { # created
2478                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2479                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2480                         $mode_chng   .= "]</span>";
2481                         print "<td>";
2482                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2483                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
2484                                       -class => "list"}, esc_path($diff->{'file'}));
2485                         print "</td>\n";
2486                         print "<td>$mode_chng</td>\n";
2487                         print "<td class=\"link\">";
2488                         if ($action eq 'commitdiff') {
2489                                 # link to patch
2490                                 $patchno++;
2491                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2492                                 print " | ";
2493                         }
2494                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2495                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
2496                                       "blob");
2497                         print "</td>\n";
2499                 } elsif ($diff->{'status'} eq "D") { # deleted
2500                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2501                         print "<td>";
2502                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2503                                                      hash_base=>$parent, file_name=>$diff->{'file'}),
2504                                        -class => "list"}, esc_path($diff->{'file'}));
2505                         print "</td>\n";
2506                         print "<td>$mode_chng</td>\n";
2507                         print "<td class=\"link\">";
2508                         if ($action eq 'commitdiff') {
2509                                 # link to patch
2510                                 $patchno++;
2511                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2512                                 print " | ";
2513                         }
2514                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2515                                                      hash_base=>$parent, file_name=>$diff->{'file'})},
2516                                       "blob") . " | ";
2517                         if ($have_blame) {
2518                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2519                                                              file_name=>$diff->{'file'})},
2520                                               "blame") . " | ";
2521                         }
2522                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2523                                                      file_name=>$diff->{'file'})},
2524                                       "history");
2525                         print "</td>\n";
2527                 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
2528                         my $mode_chnge = "";
2529                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2530                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2531                                 if ($from_file_type ne $to_file_type) {
2532                                         $mode_chnge .= " from $from_file_type to $to_file_type";
2533                                 }
2534                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2535                                         if ($from_mode_str && $to_mode_str) {
2536                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2537                                         } elsif ($to_mode_str) {
2538                                                 $mode_chnge .= " mode: $to_mode_str";
2539                                         }
2540                                 }
2541                                 $mode_chnge .= "]</span>\n";
2542                         }
2543                         print "<td>";
2544                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2545                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
2546                                       -class => "list"}, esc_path($diff->{'file'}));
2547                         print "</td>\n";
2548                         print "<td>$mode_chnge</td>\n";
2549                         print "<td class=\"link\">";
2550                         if ($action eq 'commitdiff') {
2551                                 # link to patch
2552                                 $patchno++;
2553                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2554                                       " | ";
2555                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2556                                 # "commit" view and modified file (not onlu mode changed)
2557                                 print $cgi->a({-href => href(action=>"blobdiff",
2558                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2559                                                              hash_base=>$hash, hash_parent_base=>$parent,
2560                                                              file_name=>$diff->{'file'})},
2561                                               "diff") .
2562                                       " | ";
2563                         }
2564                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2565                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
2566                                        "blob") . " | ";
2567                         if ($have_blame) {
2568                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2569                                                              file_name=>$diff->{'file'})},
2570                                               "blame") . " | ";
2571                         }
2572                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2573                                                      file_name=>$diff->{'file'})},
2574                                       "history");
2575                         print "</td>\n";
2577                 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
2578                         my %status_name = ('R' => 'moved', 'C' => 'copied');
2579                         my $nstatus = $status_name{$diff->{'status'}};
2580                         my $mode_chng = "";
2581                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2582                                 # mode also for directories, so we cannot use $to_mode_str
2583                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2584                         }
2585                         print "<td>" .
2586                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2587                                                      hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
2588                                       -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
2589                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2590                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2591                                                      hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
2592                                       -class => "list"}, esc_path($diff->{'from_file'})) .
2593                               " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2594                               "<td class=\"link\">";
2595                         if ($action eq 'commitdiff') {
2596                                 # link to patch
2597                                 $patchno++;
2598                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2599                                       " | ";
2600                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2601                                 # "commit" view and modified file (not only pure rename or copy)
2602                                 print $cgi->a({-href => href(action=>"blobdiff",
2603                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2604                                                              hash_base=>$hash, hash_parent_base=>$parent,
2605                                                              file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
2606                                               "diff") .
2607                                       " | ";
2608                         }
2609                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2610                                                      hash_base=>$parent, file_name=>$diff->{'to_file'})},
2611                                       "blob") . " | ";
2612                         if ($have_blame) {
2613                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2614                                                              file_name=>$diff->{'to_file'})},
2615                                               "blame") . " | ";
2616                         }
2617                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2618                                                     file_name=>$diff->{'to_file'})},
2619                                       "history");
2620                         print "</td>\n";
2622                 } # we should not encounter Unmerged (U) or Unknown (X) status
2623                 print "</tr>\n";
2624         }
2625         print "</table>\n";
2628 sub git_patchset_body {
2629         my ($fd, $difftree, $hash, @hash_parents) = @_;
2630         my ($hash_parent) = $hash_parents[0];
2632         my $patch_idx = 0;
2633         my $patch_number = 0;
2634         my $patch_line;
2635         my $diffinfo;
2636         my (%from, %to);
2638         print "<div class=\"patchset\">\n";
2640         # skip to first patch
2641         while ($patch_line = <$fd>) {
2642                 chomp $patch_line;
2644                 last if ($patch_line =~ m/^diff /);
2645         }
2647  PATCH:
2648         while ($patch_line) {
2649                 my @diff_header;
2650                 my ($from_id, $to_id);
2652                 # git diff header
2653                 #assert($patch_line =~ m/^diff /) if DEBUG;
2654                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
2655                 $patch_number++;
2656                 push @diff_header, $patch_line;
2658                 # extended diff header
2659         EXTENDED_HEADER:
2660                 while ($patch_line = <$fd>) {
2661                         chomp $patch_line;
2663                         last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
2665                         if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2666                                 $from_id = $1;
2667                                 $to_id   = $2;
2668                         } elsif ($patch_line =~ m/^index ((?:[0-9a-fA-F]{40},)+[0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2669                                 $from_id = [ split(',', $1) ];
2670                                 $to_id   = $2;
2671                         }
2673                         push @diff_header, $patch_line;
2674                 }
2675                 my $last_patch_line = $patch_line;
2677                 # check if current patch belong to current raw line
2678                 # and parse raw git-diff line if needed
2679                 if (defined $diffinfo &&
2680                     defined $from_id && defined $to_id &&
2681                     from_ids_eq($diffinfo->{'from_id'}, $from_id) &&
2682                     $diffinfo->{'to_id'} eq $to_id) {
2683                         # this is continuation of a split patch
2684                         print "<div class=\"patch cont\">\n";
2685                 } else {
2686                         # advance raw git-diff output if needed
2687                         $patch_idx++ if defined $diffinfo;
2689                         # read and prepare patch information
2690                         if (ref($difftree->[$patch_idx]) eq "HASH") {
2691                                 # pre-parsed (or generated by hand)
2692                                 $diffinfo = $difftree->[$patch_idx];
2693                         } else {
2694                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
2695                         }
2696                         if ($diffinfo->{'nparents'}) {
2697                                 # combined diff
2698                                 $from{'file'} = [];
2699                                 $from{'href'} = [];
2700                                 fill_from_file_info($diffinfo, @hash_parents)
2701                                         unless exists $diffinfo->{'from_file'};
2702                                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2703                                         $from{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
2704                                         if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2705                                                 $from{'href'}[$i] = href(action=>"blob",
2706                                                                          hash_base=>$hash_parents[$i],
2707                                                                          hash=>$diffinfo->{'from_id'}[$i],
2708                                                                          file_name=>$from{'file'}[$i]);
2709                                         } else {
2710                                                 $from{'href'}[$i] = undef;
2711                                         }
2712                                 }
2713                         } else {
2714                                 $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
2715                                 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2716                                         $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2717                                                              hash=>$diffinfo->{'from_id'},
2718                                                              file_name=>$from{'file'});
2719                                 } else {
2720                                         delete $from{'href'};
2721                                 }
2722                         }
2723                         $to{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
2724                         if ($diffinfo->{'status'} ne "D") { # not deleted file
2725                                 $to{'href'} = href(action=>"blob", hash_base=>$hash,
2726                                                    hash=>$diffinfo->{'to_id'},
2727                                                    file_name=>$to{'file'});
2728                         } else {
2729                                 delete $to{'href'};
2730                         }
2731                         # this is first patch for raw difftree line with $patch_idx index
2732                         # we index @$difftree array from 0, but number patches from 1
2733                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
2734                 }
2736                 # print "git diff" header
2737                 $patch_line = shift @diff_header;
2738                 if ($diffinfo->{'nparents'}) {
2740                         # combined diff
2741                         $patch_line =~ s!^(diff (.*?) )"?.*$!$1!;
2742                         if ($to{'href'}) {
2743                                 $patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
2744                                                        esc_path($to{'file'}));
2745                         } else { # file was deleted
2746                                 $patch_line .= esc_path($to{'file'});
2747                         }
2749                 } else {
2751                         $patch_line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2752                         if ($from{'href'}) {
2753                                 $patch_line .= $cgi->a({-href => $from{'href'}, -class => "path"},
2754                                                        'a/' . esc_path($from{'file'}));
2755                         } else { # file was added
2756                                 $patch_line .= 'a/' . esc_path($from{'file'});
2757                         }
2758                         $patch_line .= ' ';
2759                         if ($to{'href'}) {
2760                                 $patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
2761                                                        'b/' . esc_path($to{'file'}));
2762                         } else { # file was deleted
2763                                 $patch_line .= 'b/' . esc_path($to{'file'});
2764                         }
2766                 }
2767                 print "<div class=\"diff header\">$patch_line</div>\n";
2769                 # print extended diff header
2770                 print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
2771         EXTENDED_HEADER:
2772                 foreach $patch_line (@diff_header) {
2773                         # match <path>
2774                         if ($patch_line =~ s!^((copy|rename) from ).*$!$1! && $from{'href'}) {
2775                                 $patch_line .= $cgi->a({-href=>$from{'href'}, -class=>"path"},
2776                                                        esc_path($from{'file'}));
2777                         }
2778                         if ($patch_line =~ s!^((copy|rename) to ).*$!$1! && $to{'href'}) {
2779                                 $patch_line .= $cgi->a({-href=>$to{'href'}, -class=>"path"},
2780                                                        esc_path($to{'file'}));
2781                         }
2782                         # match single <mode>
2783                         if ($patch_line =~ m/\s(\d{6})$/) {
2784                                 $patch_line .= '<span class="info"> (' .
2785                                                file_type_long($1) .
2786                                                ')</span>';
2787                         }
2788                         # match <hash>
2789                         if ($patch_line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2790                                 # can match only for combined diff
2791                                 $patch_line = 'index ';
2792                                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2793                                         if ($from{'href'}[$i]) {
2794                                                 $patch_line .= $cgi->a({-href=>$from{'href'}[$i],
2795                                                                         -class=>"hash"},
2796                                                                        substr($diffinfo->{'from_id'}[$i],0,7));
2797                                         } else {
2798                                                 $patch_line .= '0' x 7;
2799                                         }
2800                                         # separator
2801                                         $patch_line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2802                                 }
2803                                 $patch_line .= '..';
2804                                 if ($to{'href'}) {
2805                                         $patch_line .= $cgi->a({-href=>$to{'href'}, -class=>"hash"},
2806                                                                substr($diffinfo->{'to_id'},0,7));
2807                                 } else {
2808                                         $patch_line .= '0' x 7;
2809                                 }
2811                         } elsif ($patch_line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2812                                 # can match only for ordinary diff
2813                                 my ($from_link, $to_link);
2814                                 if ($from{'href'}) {
2815                                         $from_link = $cgi->a({-href=>$from{'href'}, -class=>"hash"},
2816                                                              substr($diffinfo->{'from_id'},0,7));
2817                                 } else {
2818                                         $from_link = '0' x 7;
2819                                 }
2820                                 if ($to{'href'}) {
2821                                         $to_link = $cgi->a({-href=>$to{'href'}, -class=>"hash"},
2822                                                            substr($diffinfo->{'to_id'},0,7));
2823                                 } else {
2824                                         $to_link = '0' x 7;
2825                                 }
2826                                 #affirm {
2827                                 #       my ($from_hash, $to_hash) =
2828                                 #               ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/);
2829                                 #       my ($from_id, $to_id) =
2830                                 #               ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2831                                 #       ($from_hash eq $from_id) && ($to_hash eq $to_id);
2832                                 #} if DEBUG;
2833                                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2834                                 $patch_line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2835                         }
2836                         print $patch_line . "<br/>\n";
2837                 }
2838                 print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
2840                 # from-file/to-file diff header
2841                 $patch_line = $last_patch_line;
2842                 if (! $patch_line) {
2843                         print "</div>\n"; # class="patch"
2844                         last PATCH;
2845                 }
2846                 next PATCH if ($patch_line =~ m/^diff /);
2847                 #assert($patch_line =~ m/^---/) if DEBUG;
2848                 if (!$diffinfo->{'nparents'} && # not from-file line for combined diff
2849                     $from{'href'} && $patch_line =~ m!^--- "?a/!) {
2850                         $patch_line = '--- a/' .
2851                                       $cgi->a({-href=>$from{'href'}, -class=>"path"},
2852                                               esc_path($from{'file'}));
2853                 }
2854                 print "<div class=\"diff from_file\">$patch_line</div>\n";
2856                 $patch_line = <$fd>;
2857                 chomp $patch_line;
2859                 #assert($patch_line =~ m/^+++/) if DEBUG;
2860                 if ($to{'href'} && $patch_line =~ m!^\+\+\+ "?b/!) {
2861                         $patch_line = '+++ b/' .
2862                                       $cgi->a({-href=>$to{'href'}, -class=>"path"},
2863                                               esc_path($to{'file'}));
2864                 }
2865                 print "<div class=\"diff to_file\">$patch_line</div>\n";
2867                 # the patch itself
2868         LINE:
2869                 while ($patch_line = <$fd>) {
2870                         chomp $patch_line;
2872                         next PATCH if ($patch_line =~ m/^diff /);
2874                         print format_diff_line($patch_line, \%from, \%to);
2875                 }
2877         } continue {
2878                 print "</div>\n"; # class="patch"
2879         }
2881         if ($patch_number == 0) {
2882                 if (@hash_parents > 1) {
2883                         print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
2884                 } else {
2885                         print "<div class=\"diff nodifferences\">No differences found</div>\n";
2886                 }
2887         }
2889         print "</div>\n"; # class="patchset"
2892 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2894 sub git_project_list_body {
2895         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
2897         my ($check_forks) = gitweb_check_feature('forks');
2899         my @projects;
2900         foreach my $pr (@$projlist) {
2901                 my (@aa) = git_get_last_activity($pr->{'path'});
2902                 unless (@aa) {
2903                         next;
2904                 }
2905                 ($pr->{'age'}, $pr->{'age_string'}) = @aa;
2906                 if (!defined $pr->{'descr'}) {
2907                         my $descr = git_get_project_description($pr->{'path'}) || "";
2908                         $pr->{'descr_long'} = decode_utf8($descr);
2909                         $pr->{'descr'} = chop_str($descr, 25, 5);
2910                 }
2911                 if (!defined $pr->{'owner'}) {
2912                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2913                 }
2914                 if ($check_forks) {
2915                         my $pname = $pr->{'path'};
2916                         if (($pname =~ s/\.git$//) &&
2917                             ($pname !~ /\/$/) &&
2918                             (-d "$projectroot/$pname")) {
2919                                 $pr->{'forks'} = "-d $projectroot/$pname";
2920                         }
2921                         else {
2922                                 $pr->{'forks'} = 0;
2923                         }
2924                 }
2925                 push @projects, $pr;
2926         }
2928         $order ||= $default_projects_order;
2929         $from = 0 unless defined $from;
2930         $to = $#projects if (!defined $to || $#projects < $to);
2932         print "<table class=\"project_list\">\n";
2933         unless ($no_header) {
2934                 print "<tr>\n";
2935                 if ($check_forks) {
2936                         print "<th></th>\n";
2937                 }
2938                 if ($order eq "project") {
2939                         @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2940                         print "<th>Project</th>\n";
2941                 } else {
2942                         print "<th>" .
2943                               $cgi->a({-href => href(project=>undef, order=>'project'),
2944                                        -class => "header"}, "Project") .
2945                               "</th>\n";
2946                 }
2947                 if ($order eq "descr") {
2948                         @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2949                         print "<th>Description</th>\n";
2950                 } else {
2951                         print "<th>" .
2952                               $cgi->a({-href => href(project=>undef, order=>'descr'),
2953                                        -class => "header"}, "Description") .
2954                               "</th>\n";
2955                 }
2956                 if ($order eq "owner") {
2957                         @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2958                         print "<th>Owner</th>\n";
2959                 } else {
2960                         print "<th>" .
2961                               $cgi->a({-href => href(project=>undef, order=>'owner'),
2962                                        -class => "header"}, "Owner") .
2963                               "</th>\n";
2964                 }
2965                 if ($order eq "age") {
2966                         @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
2967                         print "<th>Last Change</th>\n";
2968                 } else {
2969                         print "<th>" .
2970                               $cgi->a({-href => href(project=>undef, order=>'age'),
2971                                        -class => "header"}, "Last Change") .
2972                               "</th>\n";
2973                 }
2974                 print "<th></th>\n" .
2975                       "</tr>\n";
2976         }
2977         my $alternate = 1;
2978         for (my $i = $from; $i <= $to; $i++) {
2979                 my $pr = $projects[$i];
2980                 if ($alternate) {
2981                         print "<tr class=\"dark\">\n";
2982                 } else {
2983                         print "<tr class=\"light\">\n";
2984                 }
2985                 $alternate ^= 1;
2986                 if ($check_forks) {
2987                         print "<td>";
2988                         if ($pr->{'forks'}) {
2989                                 print "<!-- $pr->{'forks'} -->\n";
2990                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
2991                         }
2992                         print "</td>\n";
2993                 }
2994                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2995                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2996                       "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2997                                         -class => "list", -title => $pr->{'descr_long'}},
2998                                         esc_html($pr->{'descr'})) . "</td>\n" .
2999                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
3000                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3001                       (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3002                       "<td class=\"link\">" .
3003                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
3004                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3005                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3006                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3007                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3008                       "</td>\n" .
3009                       "</tr>\n";
3010         }
3011         if (defined $extra) {
3012                 print "<tr>\n";
3013                 if ($check_forks) {
3014                         print "<td></td>\n";
3015                 }
3016                 print "<td colspan=\"5\">$extra</td>\n" .
3017                       "</tr>\n";
3018         }
3019         print "</table>\n";
3022 sub git_shortlog_body {
3023         # uses global variable $project
3024         my ($commitlist, $from, $to, $refs, $extra) = @_;
3026         my $have_snapshot = gitweb_have_snapshot();
3028         $from = 0 unless defined $from;
3029         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3031         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
3032         my $alternate = 1;
3033         for (my $i = $from; $i <= $to; $i++) {
3034                 my %co = %{$commitlist->[$i]};
3035                 my $commit = $co{'id'};
3036                 my $ref = format_ref_marker($refs, $commit);
3037                 if ($alternate) {
3038                         print "<tr class=\"dark\">\n";
3039                 } else {
3040                         print "<tr class=\"light\">\n";
3041                 }
3042                 $alternate ^= 1;
3043                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3044                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3045                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
3046                       "<td>";
3047                 print format_subject_html($co{'title'}, $co{'title_short'},
3048                                           href(action=>"commit", hash=>$commit), $ref);
3049                 print "</td>\n" .
3050                       "<td class=\"link\">" .
3051                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3052                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3053                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3054                 if ($have_snapshot) {
3055                         print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
3056                 }
3057                 print "</td>\n" .
3058                       "</tr>\n";
3059         }
3060         if (defined $extra) {
3061                 print "<tr>\n" .
3062                       "<td colspan=\"4\">$extra</td>\n" .
3063                       "</tr>\n";
3064         }
3065         print "</table>\n";
3068 sub git_history_body {
3069         # Warning: assumes constant type (blob or tree) during history
3070         my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3072         $from = 0 unless defined $from;
3073         $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3075         print "<table class=\"history\" cellspacing=\"0\">\n";
3076         my $alternate = 1;
3077         for (my $i = $from; $i <= $to; $i++) {
3078                 my %co = %{$commitlist->[$i]};
3079                 if (!%co) {
3080                         next;
3081                 }
3082                 my $commit = $co{'id'};
3084                 my $ref = format_ref_marker($refs, $commit);
3086                 if ($alternate) {
3087                         print "<tr class=\"dark\">\n";
3088                 } else {
3089                         print "<tr class=\"light\">\n";
3090                 }
3091                 $alternate ^= 1;
3092                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3093                       # shortlog uses      chop_str($co{'author_name'}, 10)
3094                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
3095                       "<td>";
3096                 # originally git_history used chop_str($co{'title'}, 50)
3097                 print format_subject_html($co{'title'}, $co{'title_short'},
3098                                           href(action=>"commit", hash=>$commit), $ref);
3099                 print "</td>\n" .
3100                       "<td class=\"link\">" .
3101                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3102                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3104                 if ($ftype eq 'blob') {
3105                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3106                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
3107                         if (defined $blob_current && defined $blob_parent &&
3108                                         $blob_current ne $blob_parent) {
3109                                 print " | " .
3110                                         $cgi->a({-href => href(action=>"blobdiff",
3111                                                                hash=>$blob_current, hash_parent=>$blob_parent,
3112                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
3113                                                                file_name=>$file_name)},
3114                                                 "diff to current");
3115                         }
3116                 }
3117                 print "</td>\n" .
3118                       "</tr>\n";
3119         }
3120         if (defined $extra) {
3121                 print "<tr>\n" .
3122                       "<td colspan=\"4\">$extra</td>\n" .
3123                       "</tr>\n";
3124         }
3125         print "</table>\n";
3128 sub git_tags_body {
3129         # uses global variable $project
3130         my ($taglist, $from, $to, $extra) = @_;
3131         $from = 0 unless defined $from;
3132         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3134         print "<table class=\"tags\" cellspacing=\"0\">\n";
3135         my $alternate = 1;
3136         for (my $i = $from; $i <= $to; $i++) {
3137                 my $entry = $taglist->[$i];
3138                 my %tag = %$entry;
3139                 my $comment = $tag{'subject'};
3140                 my $comment_short;
3141                 if (defined $comment) {
3142                         $comment_short = chop_str($comment, 30, 5);
3143                 }
3144                 if ($alternate) {
3145                         print "<tr class=\"dark\">\n";
3146                 } else {
3147                         print "<tr class=\"light\">\n";
3148                 }
3149                 $alternate ^= 1;
3150                 if (defined $tag{'age'}) {
3151                         print "<td><i>$tag{'age'}</i></td>\n";
3152                 } else {
3153                         print "<td></td>\n";
3154                 }
3155                 print "<td>" .
3156                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3157                                -class => "list name"}, esc_html($tag{'name'})) .
3158                       "</td>\n" .
3159                       "<td>";
3160                 if (defined $comment) {
3161                         print format_subject_html($comment, $comment_short,
3162                                                   href(action=>"tag", hash=>$tag{'id'}));
3163                 }
3164                 print "</td>\n" .
3165                       "<td class=\"selflink\">";
3166                 if ($tag{'type'} eq "tag") {
3167                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3168                 } else {
3169                         print "&nbsp;";
3170                 }
3171                 print "</td>\n" .
3172                       "<td class=\"link\">" . " | " .
3173                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3174                 if ($tag{'reftype'} eq "commit") {
3175                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
3176                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
3177                 } elsif ($tag{'reftype'} eq "blob") {
3178                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3179                 }
3180                 print "</td>\n" .
3181                       "</tr>";
3182         }
3183         if (defined $extra) {
3184                 print "<tr>\n" .
3185                       "<td colspan=\"5\">$extra</td>\n" .
3186                       "</tr>\n";
3187         }
3188         print "</table>\n";
3191 sub git_heads_body {
3192         # uses global variable $project
3193         my ($headlist, $head, $from, $to, $extra) = @_;
3194         $from = 0 unless defined $from;
3195         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3197         print "<table class=\"heads\" cellspacing=\"0\">\n";
3198         my $alternate = 1;
3199         for (my $i = $from; $i <= $to; $i++) {
3200                 my $entry = $headlist->[$i];
3201                 my %ref = %$entry;
3202                 my $curr = $ref{'id'} eq $head;
3203                 if ($alternate) {
3204                         print "<tr class=\"dark\">\n";
3205                 } else {
3206                         print "<tr class=\"light\">\n";
3207                 }
3208                 $alternate ^= 1;
3209                 print "<td><i>$ref{'age'}</i></td>\n" .
3210                       ($curr ? "<td class=\"current_head\">" : "<td>") .
3211                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
3212                                -class => "list name"},esc_html($ref{'name'})) .
3213                       "</td>\n" .
3214                       "<td class=\"link\">" .
3215                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
3216                       $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
3217                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
3218                       "</td>\n" .
3219                       "</tr>";
3220         }
3221         if (defined $extra) {
3222                 print "<tr>\n" .
3223                       "<td colspan=\"3\">$extra</td>\n" .
3224                       "</tr>\n";
3225         }
3226         print "</table>\n";
3229 sub git_search_grep_body {
3230         my ($commitlist, $from, $to, $extra) = @_;
3231         $from = 0 unless defined $from;
3232         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3234         print "<table class=\"grep\" cellspacing=\"0\">\n";
3235         my $alternate = 1;
3236         for (my $i = $from; $i <= $to; $i++) {
3237                 my %co = %{$commitlist->[$i]};
3238                 if (!%co) {
3239                         next;
3240                 }
3241                 my $commit = $co{'id'};
3242                 if ($alternate) {
3243                         print "<tr class=\"dark\">\n";
3244                 } else {
3245                         print "<tr class=\"light\">\n";
3246                 }
3247                 $alternate ^= 1;
3248                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3249                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3250                       "<td>" .
3251                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3252                                esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3253                 my $comment = $co{'comment'};
3254                 foreach my $line (@$comment) {
3255                         if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
3256                                 my $lead = esc_html($1) || "";
3257                                 $lead = chop_str($lead, 30, 10);
3258                                 my $match = esc_html($2) || "";
3259                                 my $trail = esc_html($3) || "";
3260                                 $trail = chop_str($trail, 30, 10);
3261                                 my $text = "$lead<span class=\"match\">$match</span>$trail";
3262                                 print chop_str($text, 80, 5) . "<br/>\n";
3263                         }
3264                 }
3265                 print "</td>\n" .
3266                       "<td class=\"link\">" .
3267                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3268                       " | " .
3269                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3270                 print "</td>\n" .
3271                       "</tr>\n";
3272         }
3273         if (defined $extra) {
3274                 print "<tr>\n" .
3275                       "<td colspan=\"3\">$extra</td>\n" .
3276                       "</tr>\n";
3277         }
3278         print "</table>\n";
3281 ## ======================================================================
3282 ## ======================================================================
3283 ## actions
3285 sub git_project_list {
3286         my $order = $cgi->param('o');
3287         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3288                 die_error(undef, "Unknown order parameter");
3289         }
3291         my @list = git_get_projects_list();
3292         if (!@list) {
3293                 die_error(undef, "No projects found");
3294         }
3296         git_header_html();
3297         if (-f $home_text) {
3298                 print "<div class=\"index_include\">\n";
3299                 open (my $fd, $home_text);
3300                 print <$fd>;
3301                 close $fd;
3302                 print "</div>\n";
3303         }
3304         git_project_list_body(\@list, $order);
3305         git_footer_html();
3308 sub git_forks {
3309         my $order = $cgi->param('o');
3310         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3311                 die_error(undef, "Unknown order parameter");
3312         }
3314         my @list = git_get_projects_list($project);
3315         if (!@list) {
3316                 die_error(undef, "No forks found");
3317         }
3319         git_header_html();
3320         git_print_page_nav('','');
3321         git_print_header_div('summary', "$project forks");
3322         git_project_list_body(\@list, $order);
3323         git_footer_html();
3326 sub git_project_index {
3327         my @projects = git_get_projects_list($project);
3329         print $cgi->header(
3330                 -type => 'text/plain',
3331                 -charset => 'utf-8',
3332                 -content_disposition => 'inline; filename="index.aux"');
3334         foreach my $pr (@projects) {
3335                 if (!exists $pr->{'owner'}) {
3336                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}");
3337                 }
3339                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3340                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3341                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3342                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3343                 $path  =~ s/ /\+/g;
3344                 $owner =~ s/ /\+/g;
3346                 print "$path $owner\n";
3347         }
3350 sub git_summary {
3351         my $descr = git_get_project_description($project) || "none";
3352         my %co = parse_commit("HEAD");
3353         my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
3354         my $head = $co{'id'};
3356         my $owner = git_get_project_owner($project);
3358         my $refs = git_get_references();
3359         # These get_*_list functions return one more to allow us to see if
3360         # there are more ...
3361         my @taglist  = git_get_tags_list(16);
3362         my @headlist = git_get_heads_list(16);
3363         my @forklist;
3364         my ($check_forks) = gitweb_check_feature('forks');
3366         if ($check_forks) {
3367                 @forklist = git_get_projects_list($project);
3368         }
3370         git_header_html();
3371         git_print_page_nav('summary','', $head);
3373         print "<div class=\"title\">&nbsp;</div>\n";
3374         print "<table cellspacing=\"0\">\n" .
3375               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3376               "<tr><td>owner</td><td>$owner</td></tr>\n";
3377         if (defined $cd{'rfc2822'}) {
3378                 print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3379         }
3381         # use per project git URL list in $projectroot/$project/cloneurl
3382         # or make project git URL from git base URL and project name
3383         my $url_tag = "URL";
3384         my @url_list = git_get_project_url_list($project);
3385         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3386         foreach my $git_url (@url_list) {
3387                 next unless $git_url;
3388                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3389                 $url_tag = "";
3390         }
3391         print "</table>\n";
3393         if (-s "$projectroot/$project/README.html") {
3394                 if (open my $fd, "$projectroot/$project/README.html") {
3395                         print "<div class=\"title\">readme</div>\n";
3396                         print $_ while (<$fd>);
3397                         close $fd;
3398                 }
3399         }
3401         # we need to request one more than 16 (0..15) to check if
3402         # those 16 are all
3403         my @commitlist = $head ? parse_commits($head, 17) : ();
3404         if (@commitlist) {
3405                 git_print_header_div('shortlog');
3406                 git_shortlog_body(\@commitlist, 0, 15, $refs,
3407                                   $#commitlist <=  15 ? undef :
3408                                   $cgi->a({-href => href(action=>"shortlog")}, "..."));
3409         }
3411         if (@taglist) {
3412                 git_print_header_div('tags');
3413                 git_tags_body(\@taglist, 0, 15,
3414                               $#taglist <=  15 ? undef :
3415                               $cgi->a({-href => href(action=>"tags")}, "..."));
3416         }
3418         if (@headlist) {
3419                 git_print_header_div('heads');
3420                 git_heads_body(\@headlist, $head, 0, 15,
3421                                $#headlist <= 15 ? undef :
3422                                $cgi->a({-href => href(action=>"heads")}, "..."));
3423         }
3425         if (@forklist) {
3426                 git_print_header_div('forks');
3427                 git_project_list_body(\@forklist, undef, 0, 15,
3428                                       $#forklist <= 15 ? undef :
3429                                       $cgi->a({-href => href(action=>"forks")}, "..."),
3430                                       'noheader');
3431         }
3433         git_footer_html();
3436 sub git_tag {
3437         my $head = git_get_head_hash($project);
3438         git_header_html();
3439         git_print_page_nav('','', $head,undef,$head);
3440         my %tag = parse_tag($hash);
3442         if (! %tag) {
3443                 die_error(undef, "Unknown tag object");
3444         }
3446         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3447         print "<div class=\"title_text\">\n" .
3448               "<table cellspacing=\"0\">\n" .
3449               "<tr>\n" .
3450               "<td>object</td>\n" .
3451               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3452                                $tag{'object'}) . "</td>\n" .
3453               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3454                                               $tag{'type'}) . "</td>\n" .
3455               "</tr>\n";
3456         if (defined($tag{'author'})) {
3457                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3458                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3459                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
3460                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3461                         "</td></tr>\n";
3462         }
3463         print "</table>\n\n" .
3464               "</div>\n";
3465         print "<div class=\"page_body\">";
3466         my $comment = $tag{'comment'};
3467         foreach my $line (@$comment) {
3468                 chomp $line;
3469                 print esc_html($line, -nbsp=>1) . "<br/>\n";
3470         }
3471         print "</div>\n";
3472         git_footer_html();
3475 sub git_blame2 {
3476         my $fd;
3477         my $ftype;
3479         my ($have_blame) = gitweb_check_feature('blame');
3480         if (!$have_blame) {
3481                 die_error('403 Permission denied', "Permission denied");
3482         }
3483         die_error('404 Not Found', "File name not defined") if (!$file_name);
3484         $hash_base ||= git_get_head_hash($project);
3485         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3486         my %co = parse_commit($hash_base)
3487                 or die_error(undef, "Reading commit failed");
3488         if (!defined $hash) {
3489                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3490                         or die_error(undef, "Error looking up file");
3491         }
3492         $ftype = git_get_type($hash);
3493         if ($ftype !~ "blob") {
3494                 die_error('400 Bad Request', "Object is not a blob");
3495         }
3496         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3497               $file_name, $hash_base)
3498                 or die_error(undef, "Open git-blame failed");
3499         git_header_html();
3500         my $formats_nav =
3501                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3502                         "blob") .
3503                 " | " .
3504                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3505                         "history") .
3506                 " | " .
3507                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3508                         "HEAD");
3509         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3510         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3511         git_print_page_path($file_name, $ftype, $hash_base);
3512         my @rev_color = (qw(light2 dark2));
3513         my $num_colors = scalar(@rev_color);
3514         my $current_color = 0;
3515         my $last_rev;
3516         print <<HTML;
3517 <div class="page_body">
3518 <table class="blame">
3519 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3520 HTML
3521         my %metainfo = ();
3522         while (1) {
3523                 $_ = <$fd>;
3524                 last unless defined $_;
3525                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
3526                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3527                 if (!exists $metainfo{$full_rev}) {
3528                         $metainfo{$full_rev} = {};
3529                 }
3530                 my $meta = $metainfo{$full_rev};
3531                 while (<$fd>) {
3532                         last if (s/^\t//);
3533                         if (/^(\S+) (.*)$/) {
3534                                 $meta->{$1} = $2;
3535                         }
3536                 }
3537                 my $data = $_;
3538                 chomp $data;
3539                 my $rev = substr($full_rev, 0, 8);
3540                 my $author = $meta->{'author'};
3541                 my %date = parse_date($meta->{'author-time'},
3542                                       $meta->{'author-tz'});
3543                 my $date = $date{'iso-tz'};
3544                 if ($group_size) {
3545                         $current_color = ++$current_color % $num_colors;
3546                 }
3547                 print "<tr class=\"$rev_color[$current_color]\">\n";
3548                 if ($group_size) {
3549                         print "<td class=\"sha1\"";
3550                         print " title=\"". esc_html($author) . ", $date\"";
3551                         print " rowspan=\"$group_size\"" if ($group_size > 1);
3552                         print ">";
3553                         print $cgi->a({-href => href(action=>"commit",
3554                                                      hash=>$full_rev,
3555                                                      file_name=>$file_name)},
3556                                       esc_html($rev));
3557                         print "</td>\n";
3558                 }
3559                 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
3560                         or die_error(undef, "Open git-rev-parse failed");
3561                 my $parent_commit = <$dd>;
3562                 close $dd;
3563                 chomp($parent_commit);
3564                 my $blamed = href(action => 'blame',
3565                                   file_name => $meta->{'filename'},
3566                                   hash_base => $parent_commit);
3567                 print "<td class=\"linenr\">";
3568                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
3569                                 -id => "l$lineno",
3570                                 -class => "linenr" },
3571                               esc_html($lineno));
3572                 print "</td>";
3573                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3574                 print "</tr>\n";
3575         }
3576         print "</table>\n";
3577         print "</div>";
3578         close $fd
3579                 or print "Reading blob failed\n";
3580         git_footer_html();
3583 sub git_blame {
3584         my $fd;
3586         my ($have_blame) = gitweb_check_feature('blame');
3587         if (!$have_blame) {
3588                 die_error('403 Permission denied', "Permission denied");
3589         }
3590         die_error('404 Not Found', "File name not defined") if (!$file_name);
3591         $hash_base ||= git_get_head_hash($project);
3592         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3593         my %co = parse_commit($hash_base)
3594                 or die_error(undef, "Reading commit failed");
3595         if (!defined $hash) {
3596                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3597                         or die_error(undef, "Error lookup file");
3598         }
3599         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3600                 or die_error(undef, "Open git-annotate failed");
3601         git_header_html();
3602         my $formats_nav =
3603                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3604                         "blob") .
3605                 " | " .
3606                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3607                         "history") .
3608                 " | " .
3609                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3610                         "HEAD");
3611         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3612         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3613         git_print_page_path($file_name, 'blob', $hash_base);
3614         print "<div class=\"page_body\">\n";
3615         print <<HTML;
3616 <table class="blame">
3617   <tr>
3618     <th>Commit</th>
3619     <th>Age</th>
3620     <th>Author</th>
3621     <th>Line</th>
3622     <th>Data</th>
3623   </tr>
3624 HTML
3625         my @line_class = (qw(light dark));
3626         my $line_class_len = scalar (@line_class);
3627         my $line_class_num = $#line_class;
3628         while (my $line = <$fd>) {
3629                 my $long_rev;
3630                 my $short_rev;
3631                 my $author;
3632                 my $time;
3633                 my $lineno;
3634                 my $data;
3635                 my $age;
3636                 my $age_str;
3637                 my $age_class;
3639                 chomp $line;
3640                 $line_class_num = ($line_class_num + 1) % $line_class_len;
3642                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
3643                         $long_rev = $1;
3644                         $author   = $2;
3645                         $time     = $3;
3646                         $lineno   = $4;
3647                         $data     = $5;
3648                 } else {
3649                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
3650                         next;
3651                 }
3652                 $short_rev  = substr ($long_rev, 0, 8);
3653                 $age        = time () - $time;
3654                 $age_str    = age_string ($age);
3655                 $age_str    =~ s/ /&nbsp;/g;
3656                 $age_class  = age_class($age);
3657                 $author     = esc_html ($author);
3658                 $author     =~ s/ /&nbsp;/g;
3660                 $data = untabify($data);
3661                 $data = esc_html ($data);
3663                 print <<HTML;
3664   <tr class="$line_class[$line_class_num]">
3665     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
3666     <td class="$age_class">$age_str</td>
3667     <td>$author</td>
3668     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
3669     <td class="pre">$data</td>
3670   </tr>
3671 HTML
3672         } # while (my $line = <$fd>)
3673         print "</table>\n\n";
3674         close $fd
3675                 or print "Reading blob failed.\n";
3676         print "</div>";
3677         git_footer_html();
3680 sub git_tags {
3681         my $head = git_get_head_hash($project);
3682         git_header_html();
3683         git_print_page_nav('','', $head,undef,$head);
3684         git_print_header_div('summary', $project);
3686         my @tagslist = git_get_tags_list();
3687         if (@tagslist) {
3688                 git_tags_body(\@tagslist);
3689         }
3690         git_footer_html();
3693 sub git_heads {
3694         my $head = git_get_head_hash($project);
3695         git_header_html();
3696         git_print_page_nav('','', $head,undef,$head);
3697         git_print_header_div('summary', $project);
3699         my @headslist = git_get_heads_list();
3700         if (@headslist) {
3701                 git_heads_body(\@headslist, $head);
3702         }
3703         git_footer_html();
3706 sub git_blob_plain {
3707         my $expires;
3709         if (!defined $hash) {
3710                 if (defined $file_name) {
3711                         my $base = $hash_base || git_get_head_hash($project);
3712                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3713                                 or die_error(undef, "Error lookup file");
3714                 } else {
3715                         die_error(undef, "No file name defined");
3716                 }
3717         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3718                 # blobs defined by non-textual hash id's can be cached
3719                 $expires = "+1d";
3720         }
3722         my $type = shift;
3723         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3724                 or die_error(undef, "Couldn't cat $file_name, $hash");
3726         $type ||= blob_mimetype($fd, $file_name);
3728         # save as filename, even when no $file_name is given
3729         my $save_as = "$hash";
3730         if (defined $file_name) {
3731                 $save_as = $file_name;
3732         } elsif ($type =~ m/^text\//) {
3733                 $save_as .= '.txt';
3734         }
3736         print $cgi->header(
3737                 -type => "$type",
3738                 -expires=>$expires,
3739                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
3740         undef $/;
3741         binmode STDOUT, ':raw';
3742         print <$fd>;
3743         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3744         $/ = "\n";
3745         close $fd;
3748 sub git_blob {
3749         my $expires;
3751         if (!defined $hash) {
3752                 if (defined $file_name) {
3753                         my $base = $hash_base || git_get_head_hash($project);
3754                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3755                                 or die_error(undef, "Error lookup file");
3756                 } else {
3757                         die_error(undef, "No file name defined");
3758                 }
3759         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3760                 # blobs defined by non-textual hash id's can be cached
3761                 $expires = "+1d";
3762         }
3764         my ($have_blame) = gitweb_check_feature('blame');
3765         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3766                 or die_error(undef, "Couldn't cat $file_name, $hash");
3767         my $mimetype = blob_mimetype($fd, $file_name);
3768         if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
3769                 close $fd;
3770                 return git_blob_plain($mimetype);
3771         }
3772         # we can have blame only for text/* mimetype
3773         $have_blame &&= ($mimetype =~ m!^text/!);
3775         git_header_html(undef, $expires);
3776         my $formats_nav = '';
3777         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3778                 if (defined $file_name) {
3779                         if ($have_blame) {
3780                                 $formats_nav .=
3781                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
3782                                                                hash=>$hash, file_name=>$file_name)},
3783                                                 "blame") .
3784                                         " | ";
3785                         }
3786                         $formats_nav .=
3787                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3788                                                        hash=>$hash, file_name=>$file_name)},
3789                                         "history") .
3790                                 " | " .
3791                                 $cgi->a({-href => href(action=>"blob_plain",
3792                                                        hash=>$hash, file_name=>$file_name)},
3793                                         "raw") .
3794                                 " | " .
3795                                 $cgi->a({-href => href(action=>"blob",
3796                                                        hash_base=>"HEAD", file_name=>$file_name)},
3797                                         "HEAD");
3798                 } else {
3799                         $formats_nav .=
3800                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
3801                 }
3802                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3803                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3804         } else {
3805                 print "<div class=\"page_nav\">\n" .
3806                       "<br/><br/></div>\n" .
3807                       "<div class=\"title\">$hash</div>\n";
3808         }
3809         git_print_page_path($file_name, "blob", $hash_base);
3810         print "<div class=\"page_body\">\n";
3811         if ($mimetype =~ m!^text/!) {
3812                 my $nr;
3813                 while (my $line = <$fd>) {
3814                         chomp $line;
3815                         $nr++;
3816                         $line = untabify($line);
3817                         printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
3818                                $nr, $nr, $nr, esc_html($line, -nbsp=>1);
3819                 }
3820         } elsif ($mimetype =~ m!^image/!) {
3821                 print qq!<img type="$mimetype"!;
3822                 if ($file_name) {
3823                         print qq! alt="$file_name" title="$file_name"!;
3824                 }
3825                 print qq! src="! .
3826                       href(action=>"blob_plain", hash=>$hash,
3827                            hash_base=>$hash_base, file_name=>$file_name) .
3828                       qq!" />\n!;
3829         }
3830         close $fd
3831                 or print "Reading blob failed.\n";
3832         print "</div>";
3833         git_footer_html();
3836 sub git_tree {
3837         my $have_snapshot = gitweb_have_snapshot();
3839         if (!defined $hash_base) {
3840                 $hash_base = "HEAD";
3841         }
3842         if (!defined $hash) {
3843                 if (defined $file_name) {
3844                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
3845                 } else {
3846                         $hash = $hash_base;
3847                 }
3848         }
3849         $/ = "\0";
3850         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
3851                 or die_error(undef, "Open git-ls-tree failed");
3852         my @entries = map { chomp; $_ } <$fd>;
3853         close $fd or die_error(undef, "Reading tree failed");
3854         $/ = "\n";
3856         my $refs = git_get_references();
3857         my $ref = format_ref_marker($refs, $hash_base);
3858         git_header_html();
3859         my $basedir = '';
3860         my ($have_blame) = gitweb_check_feature('blame');
3861         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3862                 my @views_nav = ();
3863                 if (defined $file_name) {
3864                         push @views_nav,
3865                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3866                                                        hash=>$hash, file_name=>$file_name)},
3867                                         "history"),
3868                                 $cgi->a({-href => href(action=>"tree",
3869                                                        hash_base=>"HEAD", file_name=>$file_name)},
3870                                         "HEAD"),
3871                 }
3872                 if ($have_snapshot) {
3873                         # FIXME: Should be available when we have no hash base as well.
3874                         push @views_nav,
3875                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
3876                                         "snapshot");
3877                 }
3878                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
3879                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
3880         } else {
3881                 undef $hash_base;
3882                 print "<div class=\"page_nav\">\n";
3883                 print "<br/><br/></div>\n";
3884                 print "<div class=\"title\">$hash</div>\n";
3885         }
3886         if (defined $file_name) {
3887                 $basedir = $file_name;
3888                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
3889                         $basedir .= '/';
3890                 }
3891         }
3892         git_print_page_path($file_name, 'tree', $hash_base);
3893         print "<div class=\"page_body\">\n";
3894         print "<table cellspacing=\"0\">\n";
3895         my $alternate = 1;
3896         # '..' (top directory) link if possible
3897         if (defined $hash_base &&
3898             defined $file_name && $file_name =~ m![^/]+$!) {
3899                 if ($alternate) {
3900                         print "<tr class=\"dark\">\n";
3901                 } else {
3902                         print "<tr class=\"light\">\n";
3903                 }
3904                 $alternate ^= 1;
3906                 my $up = $file_name;
3907                 $up =~ s!/?[^/]+$!!;
3908                 undef $up unless $up;
3909                 # based on git_print_tree_entry
3910                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
3911                 print '<td class="list">';
3912                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
3913                                              file_name=>$up)},
3914                               "..");
3915                 print "</td>\n";
3916                 print "<td class=\"link\"></td>\n";
3918                 print "</tr>\n";
3919         }
3920         foreach my $line (@entries) {
3921                 my %t = parse_ls_tree_line($line, -z => 1);
3923                 if ($alternate) {
3924                         print "<tr class=\"dark\">\n";
3925                 } else {
3926                         print "<tr class=\"light\">\n";
3927                 }
3928                 $alternate ^= 1;
3930                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
3932                 print "</tr>\n";
3933         }
3934         print "</table>\n" .
3935               "</div>";
3936         git_footer_html();
3939 sub git_snapshot {
3940         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
3941         my $have_snapshot = (defined $ctype && defined $suffix);
3942         if (!$have_snapshot) {
3943                 die_error('403 Permission denied', "Permission denied");
3944         }
3946         if (!defined $hash) {
3947                 $hash = git_get_head_hash($project);
3948         }
3950         my $filename = decode_utf8(basename($project)) . "-$hash.tar.$suffix";
3952         print $cgi->header(
3953                 -type => "application/$ctype",
3954                 -content_disposition => 'inline; filename="' . "$filename" . '"',
3955                 -status => '200 OK');
3957         my $git = git_cmd_str();
3958         my $name = $project;
3959         $name =~ s/\047/\047\\\047\047/g;
3960         open my $fd, "-|",
3961                 "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
3962                 or die_error(undef, "Execute git-tar-tree failed");
3963         binmode STDOUT, ':raw';
3964         print <$fd>;
3965         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3966         close $fd;
3970 sub git_log {
3971         my $head = git_get_head_hash($project);
3972         if (!defined $hash) {
3973                 $hash = $head;
3974         }
3975         if (!defined $page) {
3976                 $page = 0;
3977         }
3978         my $refs = git_get_references();
3980         my @commitlist = parse_commits($hash, 101, (100 * $page));
3982         my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
3984         git_header_html();
3985         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
3987         if (!@commitlist) {
3988                 my %co = parse_commit($hash);
3990                 git_print_header_div('summary', $project);
3991                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
3992         }
3993         my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
3994         for (my $i = 0; $i <= $to; $i++) {
3995                 my %co = %{$commitlist[$i]};
3996                 next if !%co;
3997                 my $commit = $co{'id'};
3998                 my $ref = format_ref_marker($refs, $commit);
3999                 my %ad = parse_date($co{'author_epoch'});
4000                 git_print_header_div('commit',
4001                                "<span class=\"age\">$co{'age_string'}</span>" .
4002                                esc_html($co{'title'}) . $ref,
4003                                $commit);
4004                 print "<div class=\"title_text\">\n" .
4005                       "<div class=\"log_link\">\n" .
4006                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4007                       " | " .
4008                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4009                       " | " .
4010                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4011                       "<br/>\n" .
4012                       "</div>\n" .
4013                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
4014                       "</div>\n";
4016                 print "<div class=\"log_body\">\n";
4017                 git_print_log($co{'comment'}, -final_empty_line=> 1);
4018                 print "</div>\n";
4019         }
4020         if ($#commitlist >= 100) {
4021                 print "<div class=\"page_nav\">\n";
4022                 print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
4023                                -accesskey => "n", -title => "Alt-n"}, "next");
4024                 print "</div>\n";
4025         }
4026         git_footer_html();
4029 sub git_commit {
4030         $hash ||= $hash_base || "HEAD";
4031         my %co = parse_commit($hash);
4032         if (!%co) {
4033                 die_error(undef, "Unknown commit object");
4034         }
4035         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4036         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4038         my $parent  = $co{'parent'};
4039         my $parents = $co{'parents'}; # listref
4041         # we need to prepare $formats_nav before any parameter munging
4042         my $formats_nav;
4043         if (!defined $parent) {
4044                 # --root commitdiff
4045                 $formats_nav .= '(initial)';
4046         } elsif (@$parents == 1) {
4047                 # single parent commit
4048                 $formats_nav .=
4049                         '(parent: ' .
4050                         $cgi->a({-href => href(action=>"commit",
4051                                                hash=>$parent)},
4052                                 esc_html(substr($parent, 0, 7))) .
4053                         ')';
4054         } else {
4055                 # merge commit
4056                 $formats_nav .=
4057                         '(merge: ' .
4058                         join(' ', map {
4059                                 $cgi->a({-href => href(action=>"commit",
4060                                                        hash=>$_)},
4061                                         esc_html(substr($_, 0, 7)));
4062                         } @$parents ) .
4063                         ')';
4064         }
4066         if (!defined $parent) {
4067                 $parent = "--root";
4068         }
4069         my @difftree;
4070         open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4071                 @diff_opts,
4072                 (@$parents <= 1 ? $parent : '-c'),
4073                 $hash, "--"
4074                 or die_error(undef, "Open git-diff-tree failed");
4075         @difftree = map { chomp; $_ } <$fd>;
4076         close $fd or die_error(undef, "Reading git-diff-tree failed");
4078         # non-textual hash id's can be cached
4079         my $expires;
4080         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4081                 $expires = "+1d";
4082         }
4083         my $refs = git_get_references();
4084         my $ref = format_ref_marker($refs, $co{'id'});
4086         my $have_snapshot = gitweb_have_snapshot();
4088         git_header_html(undef, $expires);
4089         git_print_page_nav('commit', '',
4090                            $hash, $co{'tree'}, $hash,
4091                            $formats_nav);
4093         if (defined $co{'parent'}) {
4094                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4095         } else {
4096                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4097         }
4098         print "<div class=\"title_text\">\n" .
4099               "<table cellspacing=\"0\">\n";
4100         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4101               "<tr>" .
4102               "<td></td><td> $ad{'rfc2822'}";
4103         if ($ad{'hour_local'} < 6) {
4104                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4105                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4106         } else {
4107                 printf(" (%02d:%02d %s)",
4108                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4109         }
4110         print "</td>" .
4111               "</tr>\n";
4112         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4113         print "<tr><td></td><td> $cd{'rfc2822'}" .
4114               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4115               "</td></tr>\n";
4116         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4117         print "<tr>" .
4118               "<td>tree</td>" .
4119               "<td class=\"sha1\">" .
4120               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4121                        class => "list"}, $co{'tree'}) .
4122               "</td>" .
4123               "<td class=\"link\">" .
4124               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4125                       "tree");
4126         if ($have_snapshot) {
4127                 print " | " .
4128                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
4129         }
4130         print "</td>" .
4131               "</tr>\n";
4133         foreach my $par (@$parents) {
4134                 print "<tr>" .
4135                       "<td>parent</td>" .
4136                       "<td class=\"sha1\">" .
4137                       $cgi->a({-href => href(action=>"commit", hash=>$par),
4138                                class => "list"}, $par) .
4139                       "</td>" .
4140                       "<td class=\"link\">" .
4141                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4142                       " | " .
4143                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4144                       "</td>" .
4145                       "</tr>\n";
4146         }
4147         print "</table>".
4148               "</div>\n";
4150         print "<div class=\"page_body\">\n";
4151         git_print_log($co{'comment'});
4152         print "</div>\n";
4154         git_difftree_body(\@difftree, $hash, @$parents);
4156         git_footer_html();
4159 sub git_object {
4160         # object is defined by:
4161         # - hash or hash_base alone
4162         # - hash_base and file_name
4163         my $type;
4165         # - hash or hash_base alone
4166         if ($hash || ($hash_base && !defined $file_name)) {
4167                 my $object_id = $hash || $hash_base;
4169                 my $git_command = git_cmd_str();
4170                 open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
4171                         or die_error('404 Not Found', "Object does not exist");
4172                 $type = <$fd>;
4173                 chomp $type;
4174                 close $fd
4175                         or die_error('404 Not Found', "Object does not exist");
4177         # - hash_base and file_name
4178         } elsif ($hash_base && defined $file_name) {
4179                 $file_name =~ s,/+$,,;
4181                 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4182                         or die_error('404 Not Found', "Base object does not exist");
4184                 # here errors should not hapen
4185                 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4186                         or die_error(undef, "Open git-ls-tree failed");
4187                 my $line = <$fd>;
4188                 close $fd;
4190                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
4191                 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4192                         die_error('404 Not Found', "File or directory for given base does not exist");
4193                 }
4194                 $type = $2;
4195                 $hash = $3;
4196         } else {
4197                 die_error('404 Not Found', "Not enough information to find object");
4198         }
4200         print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4201                                           hash=>$hash, hash_base=>$hash_base,
4202                                           file_name=>$file_name),
4203                              -status => '302 Found');
4206 sub git_blobdiff {
4207         my $format = shift || 'html';
4209         my $fd;
4210         my @difftree;
4211         my %diffinfo;
4212         my $expires;
4214         # preparing $fd and %diffinfo for git_patchset_body
4215         # new style URI
4216         if (defined $hash_base && defined $hash_parent_base) {
4217                 if (defined $file_name) {
4218                         # read raw output
4219                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4220                                 $hash_parent_base, $hash_base,
4221                                 "--", (defined $file_parent ? $file_parent : ()), $file_name
4222                                 or die_error(undef, "Open git-diff-tree failed");
4223                         @difftree = map { chomp; $_ } <$fd>;
4224                         close $fd
4225                                 or die_error(undef, "Reading git-diff-tree failed");
4226                         @difftree
4227                                 or die_error('404 Not Found', "Blob diff not found");
4229                 } elsif (defined $hash &&
4230                          $hash =~ /[0-9a-fA-F]{40}/) {
4231                         # try to find filename from $hash
4233                         # read filtered raw output
4234                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4235                                 $hash_parent_base, $hash_base, "--"
4236                                 or die_error(undef, "Open git-diff-tree failed");
4237                         @difftree =
4238                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
4239                                 # $hash == to_id
4240                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4241                                 map { chomp; $_ } <$fd>;
4242                         close $fd
4243                                 or die_error(undef, "Reading git-diff-tree failed");
4244                         @difftree
4245                                 or die_error('404 Not Found', "Blob diff not found");
4247                 } else {
4248                         die_error('404 Not Found', "Missing one of the blob diff parameters");
4249                 }
4251                 if (@difftree > 1) {
4252                         die_error('404 Not Found', "Ambiguous blob diff specification");
4253                 }
4255                 %diffinfo = parse_difftree_raw_line($difftree[0]);
4256                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
4257                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
4259                 $hash_parent ||= $diffinfo{'from_id'};
4260                 $hash        ||= $diffinfo{'to_id'};
4262                 # non-textual hash id's can be cached
4263                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4264                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4265                         $expires = '+1d';
4266                 }
4268                 # open patch output
4269                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4270                         '-p', ($format eq 'html' ? "--full-index" : ()),
4271                         $hash_parent_base, $hash_base,
4272                         "--", (defined $file_parent ? $file_parent : ()), $file_name
4273                         or die_error(undef, "Open git-diff-tree failed");
4274         }
4276         # old/legacy style URI
4277         if (!%diffinfo && # if new style URI failed
4278             defined $hash && defined $hash_parent) {
4279                 # fake git-diff-tree raw output
4280                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4281                 $diffinfo{'from_id'} = $hash_parent;
4282                 $diffinfo{'to_id'}   = $hash;
4283                 if (defined $file_name) {
4284                         if (defined $file_parent) {
4285                                 $diffinfo{'status'} = '2';
4286                                 $diffinfo{'from_file'} = $file_parent;
4287                                 $diffinfo{'to_file'}   = $file_name;
4288                         } else { # assume not renamed
4289                                 $diffinfo{'status'} = '1';
4290                                 $diffinfo{'from_file'} = $file_name;
4291                                 $diffinfo{'to_file'}   = $file_name;
4292                         }
4293                 } else { # no filename given
4294                         $diffinfo{'status'} = '2';
4295                         $diffinfo{'from_file'} = $hash_parent;
4296                         $diffinfo{'to_file'}   = $hash;
4297                 }
4299                 # non-textual hash id's can be cached
4300                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4301                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4302                         $expires = '+1d';
4303                 }
4305                 # open patch output
4306                 open $fd, "-|", git_cmd(), "diff", @diff_opts,
4307                         '-p', ($format eq 'html' ? "--full-index" : ()),
4308                         $hash_parent, $hash, "--"
4309                         or die_error(undef, "Open git-diff failed");
4310         } else  {
4311                 die_error('404 Not Found', "Missing one of the blob diff parameters")
4312                         unless %diffinfo;
4313         }
4315         # header
4316         if ($format eq 'html') {
4317                 my $formats_nav =
4318                         $cgi->a({-href => href(action=>"blobdiff_plain",
4319                                                hash=>$hash, hash_parent=>$hash_parent,
4320                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
4321                                                file_name=>$file_name, file_parent=>$file_parent)},
4322                                 "raw");
4323                 git_header_html(undef, $expires);
4324                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4325                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4326                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4327                 } else {
4328                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4329                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4330                 }
4331                 if (defined $file_name) {
4332                         git_print_page_path($file_name, "blob", $hash_base);
4333                 } else {
4334                         print "<div class=\"page_path\"></div>\n";
4335                 }
4337         } elsif ($format eq 'plain') {
4338                 print $cgi->header(
4339                         -type => 'text/plain',
4340                         -charset => 'utf-8',
4341                         -expires => $expires,
4342                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4344                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4346         } else {
4347                 die_error(undef, "Unknown blobdiff format");
4348         }
4350         # patch
4351         if ($format eq 'html') {
4352                 print "<div class=\"page_body\">\n";
4354                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4355                 close $fd;
4357                 print "</div>\n"; # class="page_body"
4358                 git_footer_html();
4360         } else {
4361                 while (my $line = <$fd>) {
4362                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4363                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4365                         print $line;
4367                         last if $line =~ m!^\+\+\+!;
4368                 }
4369                 local $/ = undef;
4370                 print <$fd>;
4371                 close $fd;
4372         }
4375 sub git_blobdiff_plain {
4376         git_blobdiff('plain');
4379 sub git_commitdiff {
4380         my $format = shift || 'html';
4381         $hash ||= $hash_base || "HEAD";
4382         my %co = parse_commit($hash);
4383         if (!%co) {
4384                 die_error(undef, "Unknown commit object");
4385         }
4387         # we need to prepare $formats_nav before any parameter munging
4388         my $formats_nav;
4389         if ($format eq 'html') {
4390                 $formats_nav =
4391                         $cgi->a({-href => href(action=>"commitdiff_plain",
4392                                                hash=>$hash, hash_parent=>$hash_parent)},
4393                                 "raw");
4395                 if (defined $hash_parent) {
4396                         # commitdiff with two commits given
4397                         my $hash_parent_short = $hash_parent;
4398                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4399                                 $hash_parent_short = substr($hash_parent, 0, 7);
4400                         }
4401                         $formats_nav .=
4402                                 ' (from: ' .
4403                                 $cgi->a({-href => href(action=>"commitdiff",
4404                                                        hash=>$hash_parent)},
4405                                         esc_html($hash_parent_short)) .
4406                                 ')';
4407                 } elsif (!$co{'parent'}) {
4408                         # --root commitdiff
4409                         $formats_nav .= ' (initial)';
4410                 } elsif (scalar @{$co{'parents'}} == 1) {
4411                         # single parent commit
4412                         $formats_nav .=
4413                                 ' (parent: ' .
4414                                 $cgi->a({-href => href(action=>"commitdiff",
4415                                                        hash=>$co{'parent'})},
4416                                         esc_html(substr($co{'parent'}, 0, 7))) .
4417                                 ')';
4418                 } else {
4419                         # merge commit
4420                         $formats_nav .=
4421                                 ' (merge: ' .
4422                                 join(' ', map {
4423                                         $cgi->a({-href => href(action=>"commitdiff",
4424                                                                hash=>$_)},
4425                                                 esc_html(substr($_, 0, 7)));
4426                                 } @{$co{'parents'}} ) .
4427                                 ')';
4428                 }
4429         }
4431         my $hash_parent_param = $hash_parent;
4432         if (!defined $hash_parent) {
4433                 $hash_parent_param =
4434                         @{$co{'parents'}} > 1 ? '-c' : $co{'parent'} || '--root';
4435         }
4437         # read commitdiff
4438         my $fd;
4439         my @difftree;
4440         if ($format eq 'html') {
4441                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4442                         "--no-commit-id", "--patch-with-raw", "--full-index",
4443                         $hash_parent_param, $hash, "--"
4444                         or die_error(undef, "Open git-diff-tree failed");
4446                 while (my $line = <$fd>) {
4447                         chomp $line;
4448                         # empty line ends raw part of diff-tree output
4449                         last unless $line;
4450                         push @difftree, scalar parse_difftree_raw_line($line);
4451                 }
4453         } elsif ($format eq 'plain') {
4454                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4455                         '-p', $hash_parent_param, $hash, "--"
4456                         or die_error(undef, "Open git-diff-tree failed");
4458         } else {
4459                 die_error(undef, "Unknown commitdiff format");
4460         }
4462         # non-textual hash id's can be cached
4463         my $expires;
4464         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4465                 $expires = "+1d";
4466         }
4468         # write commit message
4469         if ($format eq 'html') {
4470                 my $refs = git_get_references();
4471                 my $ref = format_ref_marker($refs, $co{'id'});
4473                 git_header_html(undef, $expires);
4474                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4475                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4476                 git_print_authorship(\%co);
4477                 print "<div class=\"page_body\">\n";
4478                 if (@{$co{'comment'}} > 1) {
4479                         print "<div class=\"log\">\n";
4480                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4481                         print "</div>\n"; # class="log"
4482                 }
4484         } elsif ($format eq 'plain') {
4485                 my $refs = git_get_references("tags");
4486                 my $tagname = git_get_rev_name_tags($hash);
4487                 my $filename = basename($project) . "-$hash.patch";
4489                 print $cgi->header(
4490                         -type => 'text/plain',
4491                         -charset => 'utf-8',
4492                         -expires => $expires,
4493                         -content_disposition => 'inline; filename="' . "$filename" . '"');
4494                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4495                 print <<TEXT;
4496 From: $co{'author'}
4497 Date: $ad{'rfc2822'} ($ad{'tz_local'})
4498 Subject: $co{'title'}
4499 TEXT
4500                 print "X-Git-Tag: $tagname\n" if $tagname;
4501                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4503                 foreach my $line (@{$co{'comment'}}) {
4504                         print "$line\n";
4505                 }
4506                 print "---\n\n";
4507         }
4509         # write patch
4510         if ($format eq 'html') {
4511                 git_difftree_body(\@difftree, $hash, $hash_parent || @{$co{'parents'}});
4512                 print "<br/>\n";
4514                 git_patchset_body($fd, \@difftree, $hash, $hash_parent || @{$co{'parents'}});
4515                 close $fd;
4516                 print "</div>\n"; # class="page_body"
4517                 git_footer_html();
4519         } elsif ($format eq 'plain') {
4520                 local $/ = undef;
4521                 print <$fd>;
4522                 close $fd
4523                         or print "Reading git-diff-tree failed\n";
4524         }
4527 sub git_commitdiff_plain {
4528         git_commitdiff('plain');
4531 sub git_history {
4532         if (!defined $hash_base) {
4533                 $hash_base = git_get_head_hash($project);
4534         }
4535         if (!defined $page) {
4536                 $page = 0;
4537         }
4538         my $ftype;
4539         my %co = parse_commit($hash_base);
4540         if (!%co) {
4541                 die_error(undef, "Unknown commit object");
4542         }
4544         my $refs = git_get_references();
4545         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4547         if (!defined $hash && defined $file_name) {
4548                 $hash = git_get_hash_by_path($hash_base, $file_name);
4549         }
4550         if (defined $hash) {
4551                 $ftype = git_get_type($hash);
4552         }
4554         my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
4556         my $paging_nav = '';
4557         if ($page > 0) {
4558                 $paging_nav .=
4559                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4560                                                file_name=>$file_name)},
4561                                 "first");
4562                 $paging_nav .= " &sdot; " .
4563                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4564                                                file_name=>$file_name, page=>$page-1),
4565                                  -accesskey => "p", -title => "Alt-p"}, "prev");
4566         } else {
4567                 $paging_nav .= "first";
4568                 $paging_nav .= " &sdot; prev";
4569         }
4570         if ($#commitlist >= 100) {
4571                 $paging_nav .= " &sdot; " .
4572                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4573                                                file_name=>$file_name, page=>$page+1),
4574                                  -accesskey => "n", -title => "Alt-n"}, "next");
4575         } else {
4576                 $paging_nav .= " &sdot; next";
4577         }
4578         my $next_link = '';
4579         if ($#commitlist >= 100) {
4580                 $next_link =
4581                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4582                                                file_name=>$file_name, page=>$page+1),
4583                                  -accesskey => "n", -title => "Alt-n"}, "next");
4584         }
4586         git_header_html();
4587         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
4588         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4589         git_print_page_path($file_name, $ftype, $hash_base);
4591         git_history_body(\@commitlist, 0, 99,
4592                          $refs, $hash_base, $ftype, $next_link);
4594         git_footer_html();
4597 sub git_search {
4598         my ($have_search) = gitweb_check_feature('search');
4599         if (!$have_search) {
4600                 die_error('403 Permission denied', "Permission denied");
4601         }
4602         if (!defined $searchtext) {
4603                 die_error(undef, "Text field empty");
4604         }
4605         if (!defined $hash) {
4606                 $hash = git_get_head_hash($project);
4607         }
4608         my %co = parse_commit($hash);
4609         if (!%co) {
4610                 die_error(undef, "Unknown commit object");
4611         }
4612         if (!defined $page) {
4613                 $page = 0;
4614         }
4616         $searchtype ||= 'commit';
4617         if ($searchtype eq 'pickaxe') {
4618                 # pickaxe may take all resources of your box and run for several minutes
4619                 # with every query - so decide by yourself how public you make this feature
4620                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4621                 if (!$have_pickaxe) {
4622                         die_error('403 Permission denied', "Permission denied");
4623                 }
4624         }
4626         git_header_html();
4628         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
4629                 my $greptype;
4630                 if ($searchtype eq 'commit') {
4631                         $greptype = "--grep=";
4632                 } elsif ($searchtype eq 'author') {
4633                         $greptype = "--author=";
4634                 } elsif ($searchtype eq 'committer') {
4635                         $greptype = "--committer=";
4636                 }
4637                 $greptype .= $search_regexp;
4638                 my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
4640                 my $paging_nav = '';
4641                 if ($page > 0) {
4642                         $paging_nav .=
4643                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
4644                                                        searchtext=>$searchtext, searchtype=>$searchtype)},
4645                                         "first");
4646                         $paging_nav .= " &sdot; " .
4647                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
4648                                                        searchtext=>$searchtext, searchtype=>$searchtype,
4649                                                        page=>$page-1),
4650                                          -accesskey => "p", -title => "Alt-p"}, "prev");
4651                 } else {
4652                         $paging_nav .= "first";
4653                         $paging_nav .= " &sdot; prev";
4654                 }
4655                 if ($#commitlist >= 100) {
4656                         $paging_nav .= " &sdot; " .
4657                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
4658                                                        searchtext=>$searchtext, searchtype=>$searchtype,
4659                                                        page=>$page+1),
4660                                          -accesskey => "n", -title => "Alt-n"}, "next");
4661                 } else {
4662                         $paging_nav .= " &sdot; next";
4663                 }
4664                 my $next_link = '';
4665                 if ($#commitlist >= 100) {
4666                         $next_link =
4667                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
4668                                                        searchtext=>$searchtext, searchtype=>$searchtype,
4669                                                        page=>$page+1),
4670                                          -accesskey => "n", -title => "Alt-n"}, "next");
4671                 }
4673                 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
4674                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
4675                 git_search_grep_body(\@commitlist, 0, 99, $next_link);
4676         }
4678         if ($searchtype eq 'pickaxe') {
4679                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
4680                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
4682                 print "<table cellspacing=\"0\">\n";
4683                 my $alternate = 1;
4684                 $/ = "\n";
4685                 my $git_command = git_cmd_str();
4686                 open my $fd, "-|", "$git_command rev-list $hash | " .
4687                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
4688                 undef %co;
4689                 my @files;
4690                 while (my $line = <$fd>) {
4691                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
4692                                 my %set;
4693                                 $set{'file'} = $6;
4694                                 $set{'from_id'} = $3;
4695                                 $set{'to_id'} = $4;
4696                                 $set{'id'} = $set{'to_id'};
4697                                 if ($set{'id'} =~ m/0{40}/) {
4698                                         $set{'id'} = $set{'from_id'};
4699                                 }
4700                                 if ($set{'id'} =~ m/0{40}/) {
4701                                         next;
4702                                 }
4703                                 push @files, \%set;
4704                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
4705                                 if (%co) {
4706                                         if ($alternate) {
4707                                                 print "<tr class=\"dark\">\n";
4708                                         } else {
4709                                                 print "<tr class=\"light\">\n";
4710                                         }
4711                                         $alternate ^= 1;
4712                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4713                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
4714                                               "<td>" .
4715                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4716                                                       -class => "list subject"},
4717                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
4718                                         while (my $setref = shift @files) {
4719                                                 my %set = %$setref;
4720                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
4721                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
4722                                                               -class => "list"},
4723                                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
4724                                                       "<br/>\n";
4725                                         }
4726                                         print "</td>\n" .
4727                                               "<td class=\"link\">" .
4728                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4729                                               " | " .
4730                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4731                                         print "</td>\n" .
4732                                               "</tr>\n";
4733                                 }
4734                                 %co = parse_commit($1);
4735                         }
4736                 }
4737                 close $fd;
4739                 print "</table>\n";
4740         }
4741         git_footer_html();
4744 sub git_search_help {
4745         git_header_html();
4746         git_print_page_nav('','', $hash,$hash,$hash);
4747         print <<EOT;
4748 <dl>
4749 <dt><b>commit</b></dt>
4750 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
4751 <dt><b>author</b></dt>
4752 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
4753 <dt><b>committer</b></dt>
4754 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
4755 EOT
4756         my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4757         if ($have_pickaxe) {
4758                 print <<EOT;
4759 <dt><b>pickaxe</b></dt>
4760 <dd>All commits that caused the string to appear or disappear from any file (changes that
4761 added, removed or "modified" the string) will be listed. This search can take a while and
4762 takes a lot of strain on the server, so please use it wisely.</dd>
4763 EOT
4764         }
4765         print "</dl>\n";
4766         git_footer_html();
4769 sub git_shortlog {
4770         my $head = git_get_head_hash($project);
4771         if (!defined $hash) {
4772                 $hash = $head;
4773         }
4774         if (!defined $page) {
4775                 $page = 0;
4776         }
4777         my $refs = git_get_references();
4779         my @commitlist = parse_commits($hash, 101, (100 * $page));
4781         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
4782         my $next_link = '';
4783         if ($#commitlist >= 100) {
4784                 $next_link =
4785                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
4786                                  -accesskey => "n", -title => "Alt-n"}, "next");
4787         }
4789         git_header_html();
4790         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
4791         git_print_header_div('summary', $project);
4793         git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
4795         git_footer_html();
4798 ## ......................................................................
4799 ## feeds (RSS, Atom; OPML)
4801 sub git_feed {
4802         my $format = shift || 'atom';
4803         my ($have_blame) = gitweb_check_feature('blame');
4805         # Atom: http://www.atomenabled.org/developers/syndication/
4806         # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
4807         if ($format ne 'rss' && $format ne 'atom') {
4808                 die_error(undef, "Unknown web feed format");
4809         }
4811         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
4812         my $head = $hash || 'HEAD';
4813         my @commitlist = parse_commits($head, 150);
4815         my %latest_commit;
4816         my %latest_date;
4817         my $content_type = "application/$format+xml";
4818         if (defined $cgi->http('HTTP_ACCEPT') &&
4819                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
4820                 # browser (feed reader) prefers text/xml
4821                 $content_type = 'text/xml';
4822         }
4823         if (defined($commitlist[0])) {
4824                 %latest_commit = %{$commitlist[0]};
4825                 %latest_date   = parse_date($latest_commit{'author_epoch'});
4826                 print $cgi->header(
4827                         -type => $content_type,
4828                         -charset => 'utf-8',
4829                         -last_modified => $latest_date{'rfc2822'});
4830         } else {
4831                 print $cgi->header(
4832                         -type => $content_type,
4833                         -charset => 'utf-8');
4834         }
4836         # Optimization: skip generating the body if client asks only
4837         # for Last-Modified date.
4838         return if ($cgi->request_method() eq 'HEAD');
4840         # header variables
4841         my $title = "$site_name - $project/$action";
4842         my $feed_type = 'log';
4843         if (defined $hash) {
4844                 $title .= " - '$hash'";
4845                 $feed_type = 'branch log';
4846                 if (defined $file_name) {
4847                         $title .= " :: $file_name";
4848                         $feed_type = 'history';
4849                 }
4850         } elsif (defined $file_name) {
4851                 $title .= " - $file_name";
4852                 $feed_type = 'history';
4853         }
4854         $title .= " $feed_type";
4855         my $descr = git_get_project_description($project);
4856         if (defined $descr) {
4857                 $descr = esc_html($descr);
4858         } else {
4859                 $descr = "$project " .
4860                          ($format eq 'rss' ? 'RSS' : 'Atom') .
4861                          " feed";
4862         }
4863         my $owner = git_get_project_owner($project);
4864         $owner = esc_html($owner);
4866         #header
4867         my $alt_url;
4868         if (defined $file_name) {
4869                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
4870         } elsif (defined $hash) {
4871                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
4872         } else {
4873                 $alt_url = href(-full=>1, action=>"summary");
4874         }
4875         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
4876         if ($format eq 'rss') {
4877                 print <<XML;
4878 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
4879 <channel>
4880 XML
4881                 print "<title>$title</title>\n" .
4882                       "<link>$alt_url</link>\n" .
4883                       "<description>$descr</description>\n" .
4884                       "<language>en</language>\n";
4885         } elsif ($format eq 'atom') {
4886                 print <<XML;
4887 <feed xmlns="http://www.w3.org/2005/Atom">
4888 XML
4889                 print "<title>$title</title>\n" .
4890                       "<subtitle>$descr</subtitle>\n" .
4891                       '<link rel="alternate" type="text/html" href="' .
4892                       $alt_url . '" />' . "\n" .
4893                       '<link rel="self" type="' . $content_type . '" href="' .
4894                       $cgi->self_url() . '" />' . "\n" .
4895                       "<id>" . href(-full=>1) . "</id>\n" .
4896                       # use project owner for feed author
4897                       "<author><name>$owner</name></author>\n";
4898                 if (defined $favicon) {
4899                         print "<icon>" . esc_url($favicon) . "</icon>\n";
4900                 }
4901                 if (defined $logo_url) {
4902                         # not twice as wide as tall: 72 x 27 pixels
4903                         print "<logo>" . esc_url($logo) . "</logo>\n";
4904                 }
4905                 if (! %latest_date) {
4906                         # dummy date to keep the feed valid until commits trickle in:
4907                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
4908                 } else {
4909                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
4910                 }
4911         }
4913         # contents
4914         for (my $i = 0; $i <= $#commitlist; $i++) {
4915                 my %co = %{$commitlist[$i]};
4916                 my $commit = $co{'id'};
4917                 # we read 150, we always show 30 and the ones more recent than 48 hours
4918                 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
4919                         last;
4920                 }
4921                 my %cd = parse_date($co{'author_epoch'});
4923                 # get list of changed files
4924                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4925                         $co{'parent'}, $co{'id'}, "--", (defined $file_name ? $file_name : ())
4926                         or next;
4927                 my @difftree = map { chomp; $_ } <$fd>;
4928                 close $fd
4929                         or next;
4931                 # print element (entry, item)
4932                 my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
4933                 if ($format eq 'rss') {
4934                         print "<item>\n" .
4935                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
4936                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
4937                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
4938                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
4939                               "<link>$co_url</link>\n" .
4940                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
4941                               "<content:encoded>" .
4942                               "<![CDATA[\n";
4943                 } elsif ($format eq 'atom') {
4944                         print "<entry>\n" .
4945                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
4946                               "<updated>$cd{'iso-8601'}</updated>\n" .
4947                               "<author>\n" .
4948                               "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
4949                         if ($co{'author_email'}) {
4950                                 print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
4951                         }
4952                         print "</author>\n" .
4953                               # use committer for contributor
4954                               "<contributor>\n" .
4955                               "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
4956                         if ($co{'committer_email'}) {
4957                                 print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
4958                         }
4959                         print "</contributor>\n" .
4960                               "<published>$cd{'iso-8601'}</published>\n" .
4961                               "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
4962                               "<id>$co_url</id>\n" .
4963                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
4964                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
4965                 }
4966                 my $comment = $co{'comment'};
4967                 print "<pre>\n";
4968                 foreach my $line (@$comment) {
4969                         $line = esc_html($line);
4970                         print "$line\n";
4971                 }
4972                 print "</pre><ul>\n";
4973                 foreach my $difftree_line (@difftree) {
4974                         my %difftree = parse_difftree_raw_line($difftree_line);
4975                         next if !$difftree{'from_id'};
4977                         my $file = $difftree{'file'} || $difftree{'to_file'};
4979                         print "<li>" .
4980                               "[" .
4981                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
4982                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
4983                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
4984                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
4985                                       -title => "diff"}, 'D');
4986                         if ($have_blame) {
4987                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
4988                                                              file_name=>$file, hash_base=>$commit),
4989                                               -title => "blame"}, 'B');
4990                         }
4991                         # if this is not a feed of a file history
4992                         if (!defined $file_name || $file_name ne $file) {
4993                                 print $cgi->a({-href => href(-full=>1, action=>"history",
4994                                                              file_name=>$file, hash=>$commit),
4995                                               -title => "history"}, 'H');
4996                         }
4997                         $file = esc_path($file);
4998                         print "] ".
4999                               "$file</li>\n";
5000                 }
5001                 if ($format eq 'rss') {
5002                         print "</ul>]]>\n" .
5003                               "</content:encoded>\n" .
5004                               "</item>\n";
5005                 } elsif ($format eq 'atom') {
5006                         print "</ul>\n</div>\n" .
5007                               "</content>\n" .
5008                               "</entry>\n";
5009                 }
5010         }
5012         # end of feed
5013         if ($format eq 'rss') {
5014                 print "</channel>\n</rss>\n";
5015         }       elsif ($format eq 'atom') {
5016                 print "</feed>\n";
5017         }
5020 sub git_rss {
5021         git_feed('rss');
5024 sub git_atom {
5025         git_feed('atom');
5028 sub git_opml {
5029         my @list = git_get_projects_list();
5031         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5032         print <<XML;
5033 <?xml version="1.0" encoding="utf-8"?>
5034 <opml version="1.0">
5035 <head>
5036   <title>$site_name OPML Export</title>
5037 </head>
5038 <body>
5039 <outline text="git RSS feeds">
5040 XML
5042         foreach my $pr (@list) {
5043                 my %proj = %$pr;
5044                 my $head = git_get_head_hash($proj{'path'});
5045                 if (!defined $head) {
5046                         next;
5047                 }
5048                 $git_dir = "$projectroot/$proj{'path'}";
5049                 my %co = parse_commit($head);
5050                 if (!%co) {
5051                         next;
5052                 }
5054                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5055                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
5056                 my $html = "$my_url?p=$proj{'path'};a=summary";
5057                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5058         }
5059         print <<XML;
5060 </outline>
5061 </body>
5062 </opml>
5063 XML