Code

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