Code

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