Code

fdfce311fd733ec8437de1f6975e7b552e295263
[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 # the width (in characters) of the projects list "Description" column
75 our $projects_list_description_width = 25;
77 # default order of projects list
78 # valid values are none, project, descr, owner, and age
79 our $default_projects_order = "project";
81 # show repository only if this file exists
82 # (only effective if this variable evaluates to true)
83 our $export_ok = "++GITWEB_EXPORT_OK++";
85 # only allow viewing of repositories also shown on the overview page
86 our $strict_export = "++GITWEB_STRICT_EXPORT++";
88 # list of git base URLs used for URL to where fetch project from,
89 # i.e. full URL is "$git_base_url/$project"
90 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
92 # default blob_plain mimetype and default charset for text/plain blob
93 our $default_blob_plain_mimetype = 'text/plain';
94 our $default_text_plain_charset  = undef;
96 # file to use for guessing MIME types before trying /etc/mime.types
97 # (relative to the current git repository)
98 our $mimetypes_file = undef;
100 # assume this charset if line contains non-UTF-8 characters;
101 # it should be valid encoding (see Encoding::Supported(3pm) for list),
102 # for which encoding all byte sequences are valid, for example
103 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
104 # could be even 'utf-8' for the old behavior)
105 our $fallback_encoding = 'latin1';
107 # rename detection options for git-diff and git-diff-tree
108 # - default is '-M', with the cost proportional to
109 #   (number of removed files) * (number of new files).
110 # - more costly is '-C' (which implies '-M'), with the cost proportional to
111 #   (number of changed files + number of removed files) * (number of new files)
112 # - even more costly is '-C', '--find-copies-harder' with cost
113 #   (number of files in the original tree) * (number of new files)
114 # - one might want to include '-B' option, e.g. '-B', '-M'
115 our @diff_opts = ('-M'); # taken from git_commit
117 # information about snapshot formats that gitweb is capable of serving
118 our %known_snapshot_formats = (
119         # name => {
120         #       'display' => display name,
121         #       'type' => mime type,
122         #       'suffix' => filename suffix,
123         #       'format' => --format for git-archive,
124         #       'compressor' => [compressor command and arguments]
125         #                       (array reference, optional)}
126         #
127         'tgz' => {
128                 'display' => 'tar.gz',
129                 'type' => 'application/x-gzip',
130                 'suffix' => '.tar.gz',
131                 'format' => 'tar',
132                 'compressor' => ['gzip']},
134         'tbz2' => {
135                 'display' => 'tar.bz2',
136                 'type' => 'application/x-bzip2',
137                 'suffix' => '.tar.bz2',
138                 'format' => 'tar',
139                 'compressor' => ['bzip2']},
141         'zip' => {
142                 'display' => 'zip',
143                 'type' => 'application/x-zip',
144                 'suffix' => '.zip',
145                 'format' => 'zip'},
146 );
148 # Aliases so we understand old gitweb.snapshot values in repository
149 # configuration.
150 our %known_snapshot_format_aliases = (
151         'gzip'  => 'tgz',
152         'bzip2' => 'tbz2',
154         # backward compatibility: legacy gitweb config support
155         'x-gzip' => undef, 'gz' => undef,
156         'x-bzip2' => undef, 'bz2' => undef,
157         'x-zip' => undef, '' => undef,
158 );
160 # You define site-wide feature defaults here; override them with
161 # $GITWEB_CONFIG as necessary.
162 our %feature = (
163         # feature => {
164         #       'sub' => feature-sub (subroutine),
165         #       'override' => allow-override (boolean),
166         #       'default' => [ default options...] (array reference)}
167         #
168         # if feature is overridable (it means that allow-override has true value),
169         # then feature-sub will be called with default options as parameters;
170         # return value of feature-sub indicates if to enable specified feature
171         #
172         # if there is no 'sub' key (no feature-sub), then feature cannot be
173         # overriden
174         #
175         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
177         # Enable the 'blame' blob view, showing the last commit that modified
178         # each line in the file. This can be very CPU-intensive.
180         # To enable system wide have in $GITWEB_CONFIG
181         # $feature{'blame'}{'default'} = [1];
182         # To have project specific config enable override in $GITWEB_CONFIG
183         # $feature{'blame'}{'override'} = 1;
184         # and in project config gitweb.blame = 0|1;
185         'blame' => {
186                 'sub' => \&feature_blame,
187                 'override' => 0,
188                 'default' => [0]},
190         # Enable the 'snapshot' link, providing a compressed archive of any
191         # tree. This can potentially generate high traffic if you have large
192         # project.
194         # Value is a list of formats defined in %known_snapshot_formats that
195         # you wish to offer.
196         # To disable system wide have in $GITWEB_CONFIG
197         # $feature{'snapshot'}{'default'} = [];
198         # To have project specific config enable override in $GITWEB_CONFIG
199         # $feature{'snapshot'}{'override'} = 1;
200         # and in project config, a comma-separated list of formats or "none"
201         # to disable.  Example: gitweb.snapshot = tbz2,zip;
202         'snapshot' => {
203                 'sub' => \&feature_snapshot,
204                 'override' => 0,
205                 'default' => ['tgz']},
207         # Enable text search, which will list the commits which match author,
208         # committer or commit text to a given string.  Enabled by default.
209         # Project specific override is not supported.
210         'search' => {
211                 'override' => 0,
212                 'default' => [1]},
214         # Enable grep search, which will list the files in currently selected
215         # tree containing the given string. Enabled by default. This can be
216         # potentially CPU-intensive, of course.
218         # To enable system wide have in $GITWEB_CONFIG
219         # $feature{'grep'}{'default'} = [1];
220         # To have project specific config enable override in $GITWEB_CONFIG
221         # $feature{'grep'}{'override'} = 1;
222         # and in project config gitweb.grep = 0|1;
223         'grep' => {
224                 'override' => 0,
225                 'default' => [1]},
227         # Enable the pickaxe search, which will list the commits that modified
228         # a given string in a file. This can be practical and quite faster
229         # alternative to 'blame', but still potentially CPU-intensive.
231         # To enable system wide have in $GITWEB_CONFIG
232         # $feature{'pickaxe'}{'default'} = [1];
233         # To have project specific config enable override in $GITWEB_CONFIG
234         # $feature{'pickaxe'}{'override'} = 1;
235         # and in project config gitweb.pickaxe = 0|1;
236         'pickaxe' => {
237                 'sub' => \&feature_pickaxe,
238                 'override' => 0,
239                 'default' => [1]},
241         # Make gitweb use an alternative format of the URLs which can be
242         # more readable and natural-looking: project name is embedded
243         # directly in the path and the query string contains other
244         # auxiliary information. All gitweb installations recognize
245         # URL in either format; this configures in which formats gitweb
246         # generates links.
248         # To enable system wide have in $GITWEB_CONFIG
249         # $feature{'pathinfo'}{'default'} = [1];
250         # Project specific override is not supported.
252         # Note that you will need to change the default location of CSS,
253         # favicon, logo and possibly other files to an absolute URL. Also,
254         # if gitweb.cgi serves as your indexfile, you will need to force
255         # $my_uri to contain the script name in your $GITWEB_CONFIG.
256         'pathinfo' => {
257                 'override' => 0,
258                 'default' => [0]},
260         # Make gitweb consider projects in project root subdirectories
261         # to be forks of existing projects. Given project $projname.git,
262         # projects matching $projname/*.git will not be shown in the main
263         # projects list, instead a '+' mark will be added to $projname
264         # there and a 'forks' view will be enabled for the project, listing
265         # all the forks. If project list is taken from a file, forks have
266         # to be listed after the main project.
268         # To enable system wide have in $GITWEB_CONFIG
269         # $feature{'forks'}{'default'} = [1];
270         # Project specific override is not supported.
271         'forks' => {
272                 'override' => 0,
273                 'default' => [0]},
274 );
276 sub gitweb_check_feature {
277         my ($name) = @_;
278         return unless exists $feature{$name};
279         my ($sub, $override, @defaults) = (
280                 $feature{$name}{'sub'},
281                 $feature{$name}{'override'},
282                 @{$feature{$name}{'default'}});
283         if (!$override) { return @defaults; }
284         if (!defined $sub) {
285                 warn "feature $name is not overrideable";
286                 return @defaults;
287         }
288         return $sub->(@defaults);
291 sub feature_blame {
292         my ($val) = git_get_project_config('blame', '--bool');
294         if ($val eq 'true') {
295                 return 1;
296         } elsif ($val eq 'false') {
297                 return 0;
298         }
300         return $_[0];
303 sub feature_snapshot {
304         my (@fmts) = @_;
306         my ($val) = git_get_project_config('snapshot');
308         if ($val) {
309                 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
310         }
312         return @fmts;
315 sub feature_grep {
316         my ($val) = git_get_project_config('grep', '--bool');
318         if ($val eq 'true') {
319                 return (1);
320         } elsif ($val eq 'false') {
321                 return (0);
322         }
324         return ($_[0]);
327 sub feature_pickaxe {
328         my ($val) = git_get_project_config('pickaxe', '--bool');
330         if ($val eq 'true') {
331                 return (1);
332         } elsif ($val eq 'false') {
333                 return (0);
334         }
336         return ($_[0]);
339 # checking HEAD file with -e is fragile if the repository was
340 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
341 # and then pruned.
342 sub check_head_link {
343         my ($dir) = @_;
344         my $headfile = "$dir/HEAD";
345         return ((-e $headfile) ||
346                 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
349 sub check_export_ok {
350         my ($dir) = @_;
351         return (check_head_link($dir) &&
352                 (!$export_ok || -e "$dir/$export_ok"));
355 # process alternate names for backward compatibility
356 # filter out unsupported (unknown) snapshot formats
357 sub filter_snapshot_fmts {
358         my @fmts = @_;
360         @fmts = map {
361                 exists $known_snapshot_format_aliases{$_} ?
362                        $known_snapshot_format_aliases{$_} : $_} @fmts;
363         @fmts = grep(exists $known_snapshot_formats{$_}, @fmts);
367 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
368 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
370 # version of the core git binary
371 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
373 $projects_list ||= $projectroot;
375 # ======================================================================
376 # input validation and dispatch
377 our $action = $cgi->param('a');
378 if (defined $action) {
379         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
380                 die_error(undef, "Invalid action parameter");
381         }
384 # parameters which are pathnames
385 our $project = $cgi->param('p');
386 if (defined $project) {
387         if (!validate_pathname($project) ||
388             !(-d "$projectroot/$project") ||
389             !check_head_link("$projectroot/$project") ||
390             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
391             ($strict_export && !project_in_list($project))) {
392                 undef $project;
393                 die_error(undef, "No such project");
394         }
397 our $file_name = $cgi->param('f');
398 if (defined $file_name) {
399         if (!validate_pathname($file_name)) {
400                 die_error(undef, "Invalid file parameter");
401         }
404 our $file_parent = $cgi->param('fp');
405 if (defined $file_parent) {
406         if (!validate_pathname($file_parent)) {
407                 die_error(undef, "Invalid file parent parameter");
408         }
411 # parameters which are refnames
412 our $hash = $cgi->param('h');
413 if (defined $hash) {
414         if (!validate_refname($hash)) {
415                 die_error(undef, "Invalid hash parameter");
416         }
419 our $hash_parent = $cgi->param('hp');
420 if (defined $hash_parent) {
421         if (!validate_refname($hash_parent)) {
422                 die_error(undef, "Invalid hash parent parameter");
423         }
426 our $hash_base = $cgi->param('hb');
427 if (defined $hash_base) {
428         if (!validate_refname($hash_base)) {
429                 die_error(undef, "Invalid hash base parameter");
430         }
433 my %allowed_options = (
434         "--no-merges" => [ qw(rss atom log shortlog history) ],
435 );
437 our @extra_options = $cgi->param('opt');
438 if (defined @extra_options) {
439         foreach(@extra_options)
440         {
441                 if (not grep(/^$_$/, keys %allowed_options)) {
442                         die_error(undef, "Invalid option parameter");
443                 }
444                 if (not grep(/^$action$/, @{$allowed_options{$_}})) {
445                         die_error(undef, "Invalid option parameter for this action");
446                 }
447         }
450 our $hash_parent_base = $cgi->param('hpb');
451 if (defined $hash_parent_base) {
452         if (!validate_refname($hash_parent_base)) {
453                 die_error(undef, "Invalid hash parent base parameter");
454         }
457 # other parameters
458 our $page = $cgi->param('pg');
459 if (defined $page) {
460         if ($page =~ m/[^0-9]/) {
461                 die_error(undef, "Invalid page parameter");
462         }
465 our $searchtype = $cgi->param('st');
466 if (defined $searchtype) {
467         if ($searchtype =~ m/[^a-z]/) {
468                 die_error(undef, "Invalid searchtype parameter");
469         }
472 our $searchtext = $cgi->param('s');
473 our $search_regexp;
474 if (defined $searchtext) {
475         if ($searchtype ne 'grep' and $searchtype ne 'pickaxe' and $searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
476                 die_error(undef, "Invalid search parameter");
477         }
478         if (length($searchtext) < 2) {
479                 die_error(undef, "At least two characters are required for search parameter");
480         }
481         $search_regexp = quotemeta $searchtext;
484 # now read PATH_INFO and use it as alternative to parameters
485 sub evaluate_path_info {
486         return if defined $project;
487         my $path_info = $ENV{"PATH_INFO"};
488         return if !$path_info;
489         $path_info =~ s,^/+,,;
490         return if !$path_info;
491         # find which part of PATH_INFO is project
492         $project = $path_info;
493         $project =~ s,/+$,,;
494         while ($project && !check_head_link("$projectroot/$project")) {
495                 $project =~ s,/*[^/]*$,,;
496         }
497         # validate project
498         $project = validate_pathname($project);
499         if (!$project ||
500             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
501             ($strict_export && !project_in_list($project))) {
502                 undef $project;
503                 return;
504         }
505         # do not change any parameters if an action is given using the query string
506         return if $action;
507         $path_info =~ s,^$project/*,,;
508         my ($refname, $pathname) = split(/:/, $path_info, 2);
509         if (defined $pathname) {
510                 # we got "project.git/branch:filename" or "project.git/branch:dir/"
511                 # we could use git_get_type(branch:pathname), but it needs $git_dir
512                 $pathname =~ s,^/+,,;
513                 if (!$pathname || substr($pathname, -1) eq "/") {
514                         $action  ||= "tree";
515                         $pathname =~ s,/$,,;
516                 } else {
517                         $action  ||= "blob_plain";
518                 }
519                 $hash_base ||= validate_refname($refname);
520                 $file_name ||= validate_pathname($pathname);
521         } elsif (defined $refname) {
522                 # we got "project.git/branch"
523                 $action ||= "shortlog";
524                 $hash   ||= validate_refname($refname);
525         }
527 evaluate_path_info();
529 # path to the current git repository
530 our $git_dir;
531 $git_dir = "$projectroot/$project" if $project;
533 # dispatch
534 my %actions = (
535         "blame" => \&git_blame2,
536         "blobdiff" => \&git_blobdiff,
537         "blobdiff_plain" => \&git_blobdiff_plain,
538         "blob" => \&git_blob,
539         "blob_plain" => \&git_blob_plain,
540         "commitdiff" => \&git_commitdiff,
541         "commitdiff_plain" => \&git_commitdiff_plain,
542         "commit" => \&git_commit,
543         "forks" => \&git_forks,
544         "heads" => \&git_heads,
545         "history" => \&git_history,
546         "log" => \&git_log,
547         "rss" => \&git_rss,
548         "atom" => \&git_atom,
549         "search" => \&git_search,
550         "search_help" => \&git_search_help,
551         "shortlog" => \&git_shortlog,
552         "summary" => \&git_summary,
553         "tag" => \&git_tag,
554         "tags" => \&git_tags,
555         "tree" => \&git_tree,
556         "snapshot" => \&git_snapshot,
557         "object" => \&git_object,
558         # those below don't need $project
559         "opml" => \&git_opml,
560         "project_list" => \&git_project_list,
561         "project_index" => \&git_project_index,
562 );
564 if (!defined $action) {
565         if (defined $hash) {
566                 $action = git_get_type($hash);
567         } elsif (defined $hash_base && defined $file_name) {
568                 $action = git_get_type("$hash_base:$file_name");
569         } elsif (defined $project) {
570                 $action = 'summary';
571         } else {
572                 $action = 'project_list';
573         }
575 if (!defined($actions{$action})) {
576         die_error(undef, "Unknown action");
578 if ($action !~ m/^(opml|project_list|project_index)$/ &&
579     !$project) {
580         die_error(undef, "Project needed");
582 $actions{$action}->();
583 exit;
585 ## ======================================================================
586 ## action links
588 sub href(%) {
589         my %params = @_;
590         # default is to use -absolute url() i.e. $my_uri
591         my $href = $params{-full} ? $my_url : $my_uri;
593         # XXX: Warning: If you touch this, check the search form for updating,
594         # too.
596         my @mapping = (
597                 project => "p",
598                 action => "a",
599                 file_name => "f",
600                 file_parent => "fp",
601                 extra_options => "opt",
602                 hash => "h",
603                 hash_parent => "hp",
604                 hash_base => "hb",
605                 hash_parent_base => "hpb",
606                 page => "pg",
607                 order => "o",
608                 searchtext => "s",
609                 searchtype => "st",
610                 snapshot_format => "sf",
611         );
612         my %mapping = @mapping;
614         $params{'project'} = $project unless exists $params{'project'};
616         my ($use_pathinfo) = gitweb_check_feature('pathinfo');
617         if ($use_pathinfo) {
618                 # use PATH_INFO for project name
619                 $href .= "/$params{'project'}" if defined $params{'project'};
620                 delete $params{'project'};
622                 # Summary just uses the project path URL
623                 if (defined $params{'action'} && $params{'action'} eq 'summary') {
624                         delete $params{'action'};
625                 }
626         }
628         # now encode the parameters explicitly
629         my @result = ();
630         for (my $i = 0; $i < @mapping; $i += 2) {
631                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
632                 if (defined $params{$name}) {
633                         push @result, $symbol . "=" . esc_param($params{$name});
634                 }
635         }
636         $href .= "?" . join(';', @result) if scalar @result;
638         return $href;
642 ## ======================================================================
643 ## validation, quoting/unquoting and escaping
645 sub validate_pathname {
646         my $input = shift || return undef;
648         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
649         # at the beginning, at the end, and between slashes.
650         # also this catches doubled slashes
651         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
652                 return undef;
653         }
654         # no null characters
655         if ($input =~ m!\0!) {
656                 return undef;
657         }
658         return $input;
661 sub validate_refname {
662         my $input = shift || return undef;
664         # textual hashes are O.K.
665         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
666                 return $input;
667         }
668         # it must be correct pathname
669         $input = validate_pathname($input)
670                 or return undef;
671         # restrictions on ref name according to git-check-ref-format
672         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
673                 return undef;
674         }
675         return $input;
678 # decode sequences of octets in utf8 into Perl's internal form,
679 # which is utf-8 with utf8 flag set if needed.  gitweb writes out
680 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
681 sub to_utf8 {
682         my $str = shift;
683         my $res;
684         eval { $res = decode_utf8($str, Encode::FB_CROAK); };
685         if (defined $res) {
686                 return $res;
687         } else {
688                 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
689         }
692 # quote unsafe chars, but keep the slash, even when it's not
693 # correct, but quoted slashes look too horrible in bookmarks
694 sub esc_param {
695         my $str = shift;
696         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
697         $str =~ s/\+/%2B/g;
698         $str =~ s/ /\+/g;
699         return $str;
702 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
703 sub esc_url {
704         my $str = shift;
705         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
706         $str =~ s/\+/%2B/g;
707         $str =~ s/ /\+/g;
708         return $str;
711 # replace invalid utf8 character with SUBSTITUTION sequence
712 sub esc_html ($;%) {
713         my $str = shift;
714         my %opts = @_;
716         $str = to_utf8($str);
717         $str = $cgi->escapeHTML($str);
718         if ($opts{'-nbsp'}) {
719                 $str =~ s/ /&nbsp;/g;
720         }
721         $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
722         return $str;
725 # quote control characters and escape filename to HTML
726 sub esc_path {
727         my $str = shift;
728         my %opts = @_;
730         $str = to_utf8($str);
731         $str = $cgi->escapeHTML($str);
732         if ($opts{'-nbsp'}) {
733                 $str =~ s/ /&nbsp;/g;
734         }
735         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
736         return $str;
739 # Make control characters "printable", using character escape codes (CEC)
740 sub quot_cec {
741         my $cntrl = shift;
742         my %es = ( # character escape codes, aka escape sequences
743                    "\t" => '\t',   # tab            (HT)
744                    "\n" => '\n',   # line feed      (LF)
745                    "\r" => '\r',   # carrige return (CR)
746                    "\f" => '\f',   # form feed      (FF)
747                    "\b" => '\b',   # backspace      (BS)
748                    "\a" => '\a',   # alarm (bell)   (BEL)
749                    "\e" => '\e',   # escape         (ESC)
750                    "\013" => '\v', # vertical tab   (VT)
751                    "\000" => '\0', # nul character  (NUL)
752                    );
753         my $chr = ( (exists $es{$cntrl})
754                     ? $es{$cntrl}
755                     : sprintf('\%03o', ord($cntrl)) );
756         return "<span class=\"cntrl\">$chr</span>";
759 # Alternatively use unicode control pictures codepoints,
760 # Unicode "printable representation" (PR)
761 sub quot_upr {
762         my $cntrl = shift;
763         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
764         return "<span class=\"cntrl\">$chr</span>";
767 # git may return quoted and escaped filenames
768 sub unquote {
769         my $str = shift;
771         sub unq {
772                 my $seq = shift;
773                 my %es = ( # character escape codes, aka escape sequences
774                         't' => "\t",   # tab            (HT, TAB)
775                         'n' => "\n",   # newline        (NL)
776                         'r' => "\r",   # return         (CR)
777                         'f' => "\f",   # form feed      (FF)
778                         'b' => "\b",   # backspace      (BS)
779                         'a' => "\a",   # alarm (bell)   (BEL)
780                         'e' => "\e",   # escape         (ESC)
781                         'v' => "\013", # vertical tab   (VT)
782                 );
784                 if ($seq =~ m/^[0-7]{1,3}$/) {
785                         # octal char sequence
786                         return chr(oct($seq));
787                 } elsif (exists $es{$seq}) {
788                         # C escape sequence, aka character escape code
789                         return $es{$seq}
790                 }
791                 # quoted ordinary character
792                 return $seq;
793         }
795         if ($str =~ m/^"(.*)"$/) {
796                 # needs unquoting
797                 $str = $1;
798                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
799         }
800         return $str;
803 # escape tabs (convert tabs to spaces)
804 sub untabify {
805         my $line = shift;
807         while ((my $pos = index($line, "\t")) != -1) {
808                 if (my $count = (8 - ($pos % 8))) {
809                         my $spaces = ' ' x $count;
810                         $line =~ s/\t/$spaces/;
811                 }
812         }
814         return $line;
817 sub project_in_list {
818         my $project = shift;
819         my @list = git_get_projects_list();
820         return @list && scalar(grep { $_->{'path'} eq $project } @list);
823 ## ----------------------------------------------------------------------
824 ## HTML aware string manipulation
826 sub chop_str {
827         my $str = shift;
828         my $len = shift;
829         my $add_len = shift || 10;
831         # allow only $len chars, but don't cut a word if it would fit in $add_len
832         # if it doesn't fit, cut it if it's still longer than the dots we would add
833         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
834         my $body = $1;
835         my $tail = $2;
836         if (length($tail) > 4) {
837                 $tail = " ...";
838                 $body =~ s/&[^;]*$//; # remove chopped character entities
839         }
840         return "$body$tail";
843 ## ----------------------------------------------------------------------
844 ## functions returning short strings
846 # CSS class for given age value (in seconds)
847 sub age_class {
848         my $age = shift;
850         if (!defined $age) {
851                 return "noage";
852         } elsif ($age < 60*60*2) {
853                 return "age0";
854         } elsif ($age < 60*60*24*2) {
855                 return "age1";
856         } else {
857                 return "age2";
858         }
861 # convert age in seconds to "nn units ago" string
862 sub age_string {
863         my $age = shift;
864         my $age_str;
866         if ($age > 60*60*24*365*2) {
867                 $age_str = (int $age/60/60/24/365);
868                 $age_str .= " years ago";
869         } elsif ($age > 60*60*24*(365/12)*2) {
870                 $age_str = int $age/60/60/24/(365/12);
871                 $age_str .= " months ago";
872         } elsif ($age > 60*60*24*7*2) {
873                 $age_str = int $age/60/60/24/7;
874                 $age_str .= " weeks ago";
875         } elsif ($age > 60*60*24*2) {
876                 $age_str = int $age/60/60/24;
877                 $age_str .= " days ago";
878         } elsif ($age > 60*60*2) {
879                 $age_str = int $age/60/60;
880                 $age_str .= " hours ago";
881         } elsif ($age > 60*2) {
882                 $age_str = int $age/60;
883                 $age_str .= " min ago";
884         } elsif ($age > 2) {
885                 $age_str = int $age;
886                 $age_str .= " sec ago";
887         } else {
888                 $age_str .= " right now";
889         }
890         return $age_str;
893 # convert file mode in octal to symbolic file mode string
894 sub mode_str {
895         my $mode = oct shift;
897         if (S_ISDIR($mode & S_IFMT)) {
898                 return 'drwxr-xr-x';
899         } elsif (S_ISLNK($mode)) {
900                 return 'lrwxrwxrwx';
901         } elsif (S_ISREG($mode)) {
902                 # git cares only about the executable bit
903                 if ($mode & S_IXUSR) {
904                         return '-rwxr-xr-x';
905                 } else {
906                         return '-rw-r--r--';
907                 };
908         } else {
909                 return '----------';
910         }
913 # convert file mode in octal to file type string
914 sub file_type {
915         my $mode = shift;
917         if ($mode !~ m/^[0-7]+$/) {
918                 return $mode;
919         } else {
920                 $mode = oct $mode;
921         }
923         if (S_ISDIR($mode & S_IFMT)) {
924                 return "directory";
925         } elsif (S_ISLNK($mode)) {
926                 return "symlink";
927         } elsif (S_ISREG($mode)) {
928                 return "file";
929         } else {
930                 return "unknown";
931         }
934 # convert file mode in octal to file type description string
935 sub file_type_long {
936         my $mode = shift;
938         if ($mode !~ m/^[0-7]+$/) {
939                 return $mode;
940         } else {
941                 $mode = oct $mode;
942         }
944         if (S_ISDIR($mode & S_IFMT)) {
945                 return "directory";
946         } elsif (S_ISLNK($mode)) {
947                 return "symlink";
948         } elsif (S_ISREG($mode)) {
949                 if ($mode & S_IXUSR) {
950                         return "executable";
951                 } else {
952                         return "file";
953                 };
954         } else {
955                 return "unknown";
956         }
960 ## ----------------------------------------------------------------------
961 ## functions returning short HTML fragments, or transforming HTML fragments
962 ## which don't belong to other sections
964 # format line of commit message.
965 sub format_log_line_html {
966         my $line = shift;
968         $line = esc_html($line, -nbsp=>1);
969         if ($line =~ m/([0-9a-fA-F]{8,40})/) {
970                 my $hash_text = $1;
971                 my $link =
972                         $cgi->a({-href => href(action=>"object", hash=>$hash_text),
973                                 -class => "text"}, $hash_text);
974                 $line =~ s/$hash_text/$link/;
975         }
976         return $line;
979 # format marker of refs pointing to given object
980 sub format_ref_marker {
981         my ($refs, $id) = @_;
982         my $markers = '';
984         if (defined $refs->{$id}) {
985                 foreach my $ref (@{$refs->{$id}}) {
986                         my ($type, $name) = qw();
987                         # e.g. tags/v2.6.11 or heads/next
988                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
989                                 $type = $1;
990                                 $name = $2;
991                         } else {
992                                 $type = "ref";
993                                 $name = $ref;
994                         }
996                         $markers .= " <span class=\"$type\" title=\"$ref\">" .
997                                     esc_html($name) . "</span>";
998                 }
999         }
1001         if ($markers) {
1002                 return ' <span class="refs">'. $markers . '</span>';
1003         } else {
1004                 return "";
1005         }
1008 # format, perhaps shortened and with markers, title line
1009 sub format_subject_html {
1010         my ($long, $short, $href, $extra) = @_;
1011         $extra = '' unless defined($extra);
1013         if (length($short) < length($long)) {
1014                 return $cgi->a({-href => $href, -class => "list subject",
1015                                 -title => to_utf8($long)},
1016                        esc_html($short) . $extra);
1017         } else {
1018                 return $cgi->a({-href => $href, -class => "list subject"},
1019                        esc_html($long)  . $extra);
1020         }
1023 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1024 sub format_git_diff_header_line {
1025         my $line = shift;
1026         my $diffinfo = shift;
1027         my ($from, $to) = @_;
1029         if ($diffinfo->{'nparents'}) {
1030                 # combined diff
1031                 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1032                 if ($to->{'href'}) {
1033                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1034                                          esc_path($to->{'file'}));
1035                 } else { # file was deleted (no href)
1036                         $line .= esc_path($to->{'file'});
1037                 }
1038         } else {
1039                 # "ordinary" diff
1040                 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1041                 if ($from->{'href'}) {
1042                         $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1043                                          'a/' . esc_path($from->{'file'}));
1044                 } else { # file was added (no href)
1045                         $line .= 'a/' . esc_path($from->{'file'});
1046                 }
1047                 $line .= ' ';
1048                 if ($to->{'href'}) {
1049                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1050                                          'b/' . esc_path($to->{'file'}));
1051                 } else { # file was deleted
1052                         $line .= 'b/' . esc_path($to->{'file'});
1053                 }
1054         }
1056         return "<div class=\"diff header\">$line</div>\n";
1059 # format extended diff header line, before patch itself
1060 sub format_extended_diff_header_line {
1061         my $line = shift;
1062         my $diffinfo = shift;
1063         my ($from, $to) = @_;
1065         # match <path>
1066         if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1067                 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1068                                        esc_path($from->{'file'}));
1069         }
1070         if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1071                 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1072                                  esc_path($to->{'file'}));
1073         }
1074         # match single <mode>
1075         if ($line =~ m/\s(\d{6})$/) {
1076                 $line .= '<span class="info"> (' .
1077                          file_type_long($1) .
1078                          ')</span>';
1079         }
1080         # match <hash>
1081         if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1082                 # can match only for combined diff
1083                 $line = 'index ';
1084                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1085                         if ($from->{'href'}[$i]) {
1086                                 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1087                                                   -class=>"hash"},
1088                                                  substr($diffinfo->{'from_id'}[$i],0,7));
1089                         } else {
1090                                 $line .= '0' x 7;
1091                         }
1092                         # separator
1093                         $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1094                 }
1095                 $line .= '..';
1096                 if ($to->{'href'}) {
1097                         $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1098                                          substr($diffinfo->{'to_id'},0,7));
1099                 } else {
1100                         $line .= '0' x 7;
1101                 }
1103         } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1104                 # can match only for ordinary diff
1105                 my ($from_link, $to_link);
1106                 if ($from->{'href'}) {
1107                         $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1108                                              substr($diffinfo->{'from_id'},0,7));
1109                 } else {
1110                         $from_link = '0' x 7;
1111                 }
1112                 if ($to->{'href'}) {
1113                         $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1114                                            substr($diffinfo->{'to_id'},0,7));
1115                 } else {
1116                         $to_link = '0' x 7;
1117                 }
1118                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1119                 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1120         }
1122         return $line . "<br/>\n";
1125 # format from-file/to-file diff header
1126 sub format_diff_from_to_header {
1127         my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1128         my $line;
1129         my $result = '';
1131         $line = $from_line;
1132         #assert($line =~ m/^---/) if DEBUG;
1133         # no extra formatting for "^--- /dev/null"
1134         if (! $diffinfo->{'nparents'}) {
1135                 # ordinary (single parent) diff
1136                 if ($line =~ m!^--- "?a/!) {
1137                         if ($from->{'href'}) {
1138                                 $line = '--- a/' .
1139                                         $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1140                                                 esc_path($from->{'file'}));
1141                         } else {
1142                                 $line = '--- a/' .
1143                                         esc_path($from->{'file'});
1144                         }
1145                 }
1146                 $result .= qq!<div class="diff from_file">$line</div>\n!;
1148         } else {
1149                 # combined diff (merge commit)
1150                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1151                         if ($from->{'href'}[$i]) {
1152                                 $line = '--- ' .
1153                                         $cgi->a({-href=>href(action=>"blobdiff",
1154                                                              hash_parent=>$diffinfo->{'from_id'}[$i],
1155                                                              hash_parent_base=>$parents[$i],
1156                                                              file_parent=>$from->{'file'}[$i],
1157                                                              hash=>$diffinfo->{'to_id'},
1158                                                              hash_base=>$hash,
1159                                                              file_name=>$to->{'file'}),
1160                                                  -class=>"path",
1161                                                  -title=>"diff" . ($i+1)},
1162                                                 $i+1) .
1163                                         '/' .
1164                                         $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1165                                                 esc_path($from->{'file'}[$i]));
1166                         } else {
1167                                 $line = '--- /dev/null';
1168                         }
1169                         $result .= qq!<div class="diff from_file">$line</div>\n!;
1170                 }
1171         }
1173         $line = $to_line;
1174         #assert($line =~ m/^\+\+\+/) if DEBUG;
1175         # no extra formatting for "^+++ /dev/null"
1176         if ($line =~ m!^\+\+\+ "?b/!) {
1177                 if ($to->{'href'}) {
1178                         $line = '+++ b/' .
1179                                 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1180                                         esc_path($to->{'file'}));
1181                 } else {
1182                         $line = '+++ b/' .
1183                                 esc_path($to->{'file'});
1184                 }
1185         }
1186         $result .= qq!<div class="diff to_file">$line</div>\n!;
1188         return $result;
1191 # create note for patch simplified by combined diff
1192 sub format_diff_cc_simplified {
1193         my ($diffinfo, @parents) = @_;
1194         my $result = '';
1196         $result .= "<div class=\"diff header\">" .
1197                    "diff --cc ";
1198         if (!is_deleted($diffinfo)) {
1199                 $result .= $cgi->a({-href => href(action=>"blob",
1200                                                   hash_base=>$hash,
1201                                                   hash=>$diffinfo->{'to_id'},
1202                                                   file_name=>$diffinfo->{'to_file'}),
1203                                     -class => "path"},
1204                                    esc_path($diffinfo->{'to_file'}));
1205         } else {
1206                 $result .= esc_path($diffinfo->{'to_file'});
1207         }
1208         $result .= "</div>\n" . # class="diff header"
1209                    "<div class=\"diff nodifferences\">" .
1210                    "Simple merge" .
1211                    "</div>\n"; # class="diff nodifferences"
1213         return $result;
1216 # format patch (diff) line (not to be used for diff headers)
1217 sub format_diff_line {
1218         my $line = shift;
1219         my ($from, $to) = @_;
1220         my $diff_class = "";
1222         chomp $line;
1224         if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1225                 # combined diff
1226                 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1227                 if ($line =~ m/^\@{3}/) {
1228                         $diff_class = " chunk_header";
1229                 } elsif ($line =~ m/^\\/) {
1230                         $diff_class = " incomplete";
1231                 } elsif ($prefix =~ tr/+/+/) {
1232                         $diff_class = " add";
1233                 } elsif ($prefix =~ tr/-/-/) {
1234                         $diff_class = " rem";
1235                 }
1236         } else {
1237                 # assume ordinary diff
1238                 my $char = substr($line, 0, 1);
1239                 if ($char eq '+') {
1240                         $diff_class = " add";
1241                 } elsif ($char eq '-') {
1242                         $diff_class = " rem";
1243                 } elsif ($char eq '@') {
1244                         $diff_class = " chunk_header";
1245                 } elsif ($char eq "\\") {
1246                         $diff_class = " incomplete";
1247                 }
1248         }
1249         $line = untabify($line);
1250         if ($from && $to && $line =~ m/^\@{2} /) {
1251                 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1252                         $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1254                 $from_lines = 0 unless defined $from_lines;
1255                 $to_lines   = 0 unless defined $to_lines;
1257                 if ($from->{'href'}) {
1258                         $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1259                                              -class=>"list"}, $from_text);
1260                 }
1261                 if ($to->{'href'}) {
1262                         $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1263                                              -class=>"list"}, $to_text);
1264                 }
1265                 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1266                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1267                 return "<div class=\"diff$diff_class\">$line</div>\n";
1268         } elsif ($from && $to && $line =~ m/^\@{3}/) {
1269                 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1270                 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1272                 @from_text = split(' ', $ranges);
1273                 for (my $i = 0; $i < @from_text; ++$i) {
1274                         ($from_start[$i], $from_nlines[$i]) =
1275                                 (split(',', substr($from_text[$i], 1)), 0);
1276                 }
1278                 $to_text   = pop @from_text;
1279                 $to_start  = pop @from_start;
1280                 $to_nlines = pop @from_nlines;
1282                 $line = "<span class=\"chunk_info\">$prefix ";
1283                 for (my $i = 0; $i < @from_text; ++$i) {
1284                         if ($from->{'href'}[$i]) {
1285                                 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1286                                                   -class=>"list"}, $from_text[$i]);
1287                         } else {
1288                                 $line .= $from_text[$i];
1289                         }
1290                         $line .= " ";
1291                 }
1292                 if ($to->{'href'}) {
1293                         $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1294                                           -class=>"list"}, $to_text);
1295                 } else {
1296                         $line .= $to_text;
1297                 }
1298                 $line .= " $prefix</span>" .
1299                          "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1300                 return "<div class=\"diff$diff_class\">$line</div>\n";
1301         }
1302         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1305 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1306 # linked.  Pass the hash of the tree/commit to snapshot.
1307 sub format_snapshot_links {
1308         my ($hash) = @_;
1309         my @snapshot_fmts = gitweb_check_feature('snapshot');
1310         @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1311         my $num_fmts = @snapshot_fmts;
1312         if ($num_fmts > 1) {
1313                 # A parenthesized list of links bearing format names.
1314                 # e.g. "snapshot (_tar.gz_ _zip_)"
1315                 return "snapshot (" . join(' ', map
1316                         $cgi->a({
1317                                 -href => href(
1318                                         action=>"snapshot",
1319                                         hash=>$hash,
1320                                         snapshot_format=>$_
1321                                 )
1322                         }, $known_snapshot_formats{$_}{'display'})
1323                 , @snapshot_fmts) . ")";
1324         } elsif ($num_fmts == 1) {
1325                 # A single "snapshot" link whose tooltip bears the format name.
1326                 # i.e. "_snapshot_"
1327                 my ($fmt) = @snapshot_fmts;
1328                 return
1329                         $cgi->a({
1330                                 -href => href(
1331                                         action=>"snapshot",
1332                                         hash=>$hash,
1333                                         snapshot_format=>$fmt
1334                                 ),
1335                                 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1336                         }, "snapshot");
1337         } else { # $num_fmts == 0
1338                 return undef;
1339         }
1342 ## ----------------------------------------------------------------------
1343 ## git utility subroutines, invoking git commands
1345 # returns path to the core git executable and the --git-dir parameter as list
1346 sub git_cmd {
1347         return $GIT, '--git-dir='.$git_dir;
1350 # returns path to the core git executable and the --git-dir parameter as string
1351 sub git_cmd_str {
1352         return join(' ', git_cmd());
1355 # get HEAD ref of given project as hash
1356 sub git_get_head_hash {
1357         my $project = shift;
1358         my $o_git_dir = $git_dir;
1359         my $retval = undef;
1360         $git_dir = "$projectroot/$project";
1361         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1362                 my $head = <$fd>;
1363                 close $fd;
1364                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1365                         $retval = $1;
1366                 }
1367         }
1368         if (defined $o_git_dir) {
1369                 $git_dir = $o_git_dir;
1370         }
1371         return $retval;
1374 # get type of given object
1375 sub git_get_type {
1376         my $hash = shift;
1378         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1379         my $type = <$fd>;
1380         close $fd or return;
1381         chomp $type;
1382         return $type;
1385 sub git_get_project_config {
1386         my ($key, $type) = @_;
1388         return unless ($key);
1389         $key =~ s/^gitweb\.//;
1390         return if ($key =~ m/\W/);
1392         my @x = (git_cmd(), 'config');
1393         if (defined $type) { push @x, $type; }
1394         push @x, "--get";
1395         push @x, "gitweb.$key";
1396         my $val = qx(@x);
1397         chomp $val;
1398         return ($val);
1401 # get hash of given path at given ref
1402 sub git_get_hash_by_path {
1403         my $base = shift;
1404         my $path = shift || return undef;
1405         my $type = shift;
1407         $path =~ s,/+$,,;
1409         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1410                 or die_error(undef, "Open git-ls-tree failed");
1411         my $line = <$fd>;
1412         close $fd or return undef;
1414         if (!defined $line) {
1415                 # there is no tree or hash given by $path at $base
1416                 return undef;
1417         }
1419         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1420         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1421         if (defined $type && $type ne $2) {
1422                 # type doesn't match
1423                 return undef;
1424         }
1425         return $3;
1428 # get path of entry with given hash at given tree-ish (ref)
1429 # used to get 'from' filename for combined diff (merge commit) for renames
1430 sub git_get_path_by_hash {
1431         my $base = shift || return;
1432         my $hash = shift || return;
1434         local $/ = "\0";
1436         open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1437                 or return undef;
1438         while (my $line = <$fd>) {
1439                 chomp $line;
1441                 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
1442                 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
1443                 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1444                         close $fd;
1445                         return $1;
1446                 }
1447         }
1448         close $fd;
1449         return undef;
1452 ## ......................................................................
1453 ## git utility functions, directly accessing git repository
1455 sub git_get_project_description {
1456         my $path = shift;
1458         open my $fd, "$projectroot/$path/description" or return undef;
1459         my $descr = <$fd>;
1460         close $fd;
1461         if (defined $descr) {
1462                 chomp $descr;
1463         }
1464         return $descr;
1467 sub git_get_project_url_list {
1468         my $path = shift;
1470         open my $fd, "$projectroot/$path/cloneurl" or return;
1471         my @git_project_url_list = map { chomp; $_ } <$fd>;
1472         close $fd;
1474         return wantarray ? @git_project_url_list : \@git_project_url_list;
1477 sub git_get_projects_list {
1478         my ($filter) = @_;
1479         my @list;
1481         $filter ||= '';
1482         $filter =~ s/\.git$//;
1484         my ($check_forks) = gitweb_check_feature('forks');
1486         if (-d $projects_list) {
1487                 # search in directory
1488                 my $dir = $projects_list . ($filter ? "/$filter" : '');
1489                 # remove the trailing "/"
1490                 $dir =~ s!/+$!!;
1491                 my $pfxlen = length("$dir");
1493                 File::Find::find({
1494                         follow_fast => 1, # follow symbolic links
1495                         dangling_symlinks => 0, # ignore dangling symlinks, silently
1496                         wanted => sub {
1497                                 # skip project-list toplevel, if we get it.
1498                                 return if (m!^[/.]$!);
1499                                 # only directories can be git repositories
1500                                 return unless (-d $_);
1502                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
1503                                 # we check related file in $projectroot
1504                                 if ($check_forks and $subdir =~ m#/.#) {
1505                                         $File::Find::prune = 1;
1506                                 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1507                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1508                                         $File::Find::prune = 1;
1509                                 }
1510                         },
1511                 }, "$dir");
1513         } elsif (-f $projects_list) {
1514                 # read from file(url-encoded):
1515                 # 'git%2Fgit.git Linus+Torvalds'
1516                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1517                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1518                 my %paths;
1519                 open my ($fd), $projects_list or return;
1520         PROJECT:
1521                 while (my $line = <$fd>) {
1522                         chomp $line;
1523                         my ($path, $owner) = split ' ', $line;
1524                         $path = unescape($path);
1525                         $owner = unescape($owner);
1526                         if (!defined $path) {
1527                                 next;
1528                         }
1529                         if ($filter ne '') {
1530                                 # looking for forks;
1531                                 my $pfx = substr($path, 0, length($filter));
1532                                 if ($pfx ne $filter) {
1533                                         next PROJECT;
1534                                 }
1535                                 my $sfx = substr($path, length($filter));
1536                                 if ($sfx !~ /^\/.*\.git$/) {
1537                                         next PROJECT;
1538                                 }
1539                         } elsif ($check_forks) {
1540                         PATH:
1541                                 foreach my $filter (keys %paths) {
1542                                         # looking for forks;
1543                                         my $pfx = substr($path, 0, length($filter));
1544                                         if ($pfx ne $filter) {
1545                                                 next PATH;
1546                                         }
1547                                         my $sfx = substr($path, length($filter));
1548                                         if ($sfx !~ /^\/.*\.git$/) {
1549                                                 next PATH;
1550                                         }
1551                                         # is a fork, don't include it in
1552                                         # the list
1553                                         next PROJECT;
1554                                 }
1555                         }
1556                         if (check_export_ok("$projectroot/$path")) {
1557                                 my $pr = {
1558                                         path => $path,
1559                                         owner => to_utf8($owner),
1560                                 };
1561                                 push @list, $pr;
1562                                 (my $forks_path = $path) =~ s/\.git$//;
1563                                 $paths{$forks_path}++;
1564                         }
1565                 }
1566                 close $fd;
1567         }
1568         return @list;
1571 our $gitweb_project_owner = undef;
1572 sub git_get_project_list_from_file {
1574         return if (defined $gitweb_project_owner);
1576         $gitweb_project_owner = {};
1577         # read from file (url-encoded):
1578         # 'git%2Fgit.git Linus+Torvalds'
1579         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1580         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1581         if (-f $projects_list) {
1582                 open (my $fd , $projects_list);
1583                 while (my $line = <$fd>) {
1584                         chomp $line;
1585                         my ($pr, $ow) = split ' ', $line;
1586                         $pr = unescape($pr);
1587                         $ow = unescape($ow);
1588                         $gitweb_project_owner->{$pr} = to_utf8($ow);
1589                 }
1590                 close $fd;
1591         }
1594 sub git_get_project_owner {
1595         my $project = shift;
1596         my $owner;
1598         return undef unless $project;
1600         if (!defined $gitweb_project_owner) {
1601                 git_get_project_list_from_file();
1602         }
1604         if (exists $gitweb_project_owner->{$project}) {
1605                 $owner = $gitweb_project_owner->{$project};
1606         }
1607         if (!defined $owner) {
1608                 $owner = get_file_owner("$projectroot/$project");
1609         }
1611         return $owner;
1614 sub git_get_last_activity {
1615         my ($path) = @_;
1616         my $fd;
1618         $git_dir = "$projectroot/$path";
1619         open($fd, "-|", git_cmd(), 'for-each-ref',
1620              '--format=%(committer)',
1621              '--sort=-committerdate',
1622              '--count=1',
1623              'refs/heads') or return;
1624         my $most_recent = <$fd>;
1625         close $fd or return;
1626         if (defined $most_recent &&
1627             $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1628                 my $timestamp = $1;
1629                 my $age = time - $timestamp;
1630                 return ($age, age_string($age));
1631         }
1632         return (undef, undef);
1635 sub git_get_references {
1636         my $type = shift || "";
1637         my %refs;
1638         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1639         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1640         open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1641                 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1642                 or return;
1644         while (my $line = <$fd>) {
1645                 chomp $line;
1646                 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1647                         if (defined $refs{$1}) {
1648                                 push @{$refs{$1}}, $2;
1649                         } else {
1650                                 $refs{$1} = [ $2 ];
1651                         }
1652                 }
1653         }
1654         close $fd or return;
1655         return \%refs;
1658 sub git_get_rev_name_tags {
1659         my $hash = shift || return undef;
1661         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1662                 or return;
1663         my $name_rev = <$fd>;
1664         close $fd;
1666         if ($name_rev =~ m|^$hash tags/(.*)$|) {
1667                 return $1;
1668         } else {
1669                 # catches also '$hash undefined' output
1670                 return undef;
1671         }
1674 ## ----------------------------------------------------------------------
1675 ## parse to hash functions
1677 sub parse_date {
1678         my $epoch = shift;
1679         my $tz = shift || "-0000";
1681         my %date;
1682         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1683         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1684         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1685         $date{'hour'} = $hour;
1686         $date{'minute'} = $min;
1687         $date{'mday'} = $mday;
1688         $date{'day'} = $days[$wday];
1689         $date{'month'} = $months[$mon];
1690         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1691                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1692         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1693                              $mday, $months[$mon], $hour ,$min;
1694         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1695                              1900+$year, $mon, $mday, $hour ,$min, $sec;
1697         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1698         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1699         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1700         $date{'hour_local'} = $hour;
1701         $date{'minute_local'} = $min;
1702         $date{'tz_local'} = $tz;
1703         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1704                                   1900+$year, $mon+1, $mday,
1705                                   $hour, $min, $sec, $tz);
1706         return %date;
1709 sub parse_tag {
1710         my $tag_id = shift;
1711         my %tag;
1712         my @comment;
1714         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1715         $tag{'id'} = $tag_id;
1716         while (my $line = <$fd>) {
1717                 chomp $line;
1718                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1719                         $tag{'object'} = $1;
1720                 } elsif ($line =~ m/^type (.+)$/) {
1721                         $tag{'type'} = $1;
1722                 } elsif ($line =~ m/^tag (.+)$/) {
1723                         $tag{'name'} = $1;
1724                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1725                         $tag{'author'} = $1;
1726                         $tag{'epoch'} = $2;
1727                         $tag{'tz'} = $3;
1728                 } elsif ($line =~ m/--BEGIN/) {
1729                         push @comment, $line;
1730                         last;
1731                 } elsif ($line eq "") {
1732                         last;
1733                 }
1734         }
1735         push @comment, <$fd>;
1736         $tag{'comment'} = \@comment;
1737         close $fd or return;
1738         if (!defined $tag{'name'}) {
1739                 return
1740         };
1741         return %tag
1744 sub parse_commit_text {
1745         my ($commit_text, $withparents) = @_;
1746         my @commit_lines = split '\n', $commit_text;
1747         my %co;
1749         pop @commit_lines; # Remove '\0'
1751         if (! @commit_lines) {
1752                 return;
1753         }
1755         my $header = shift @commit_lines;
1756         if ($header !~ m/^[0-9a-fA-F]{40}/) {
1757                 return;
1758         }
1759         ($co{'id'}, my @parents) = split ' ', $header;
1760         while (my $line = shift @commit_lines) {
1761                 last if $line eq "\n";
1762                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1763                         $co{'tree'} = $1;
1764                 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1765                         push @parents, $1;
1766                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1767                         $co{'author'} = $1;
1768                         $co{'author_epoch'} = $2;
1769                         $co{'author_tz'} = $3;
1770                         if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1771                                 $co{'author_name'}  = $1;
1772                                 $co{'author_email'} = $2;
1773                         } else {
1774                                 $co{'author_name'} = $co{'author'};
1775                         }
1776                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1777                         $co{'committer'} = $1;
1778                         $co{'committer_epoch'} = $2;
1779                         $co{'committer_tz'} = $3;
1780                         $co{'committer_name'} = $co{'committer'};
1781                         if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1782                                 $co{'committer_name'}  = $1;
1783                                 $co{'committer_email'} = $2;
1784                         } else {
1785                                 $co{'committer_name'} = $co{'committer'};
1786                         }
1787                 }
1788         }
1789         if (!defined $co{'tree'}) {
1790                 return;
1791         };
1792         $co{'parents'} = \@parents;
1793         $co{'parent'} = $parents[0];
1795         foreach my $title (@commit_lines) {
1796                 $title =~ s/^    //;
1797                 if ($title ne "") {
1798                         $co{'title'} = chop_str($title, 80, 5);
1799                         # remove leading stuff of merges to make the interesting part visible
1800                         if (length($title) > 50) {
1801                                 $title =~ s/^Automatic //;
1802                                 $title =~ s/^merge (of|with) /Merge ... /i;
1803                                 if (length($title) > 50) {
1804                                         $title =~ s/(http|rsync):\/\///;
1805                                 }
1806                                 if (length($title) > 50) {
1807                                         $title =~ s/(master|www|rsync)\.//;
1808                                 }
1809                                 if (length($title) > 50) {
1810                                         $title =~ s/kernel.org:?//;
1811                                 }
1812                                 if (length($title) > 50) {
1813                                         $title =~ s/\/pub\/scm//;
1814                                 }
1815                         }
1816                         $co{'title_short'} = chop_str($title, 50, 5);
1817                         last;
1818                 }
1819         }
1820         if ($co{'title'} eq "") {
1821                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1822         }
1823         # remove added spaces
1824         foreach my $line (@commit_lines) {
1825                 $line =~ s/^    //;
1826         }
1827         $co{'comment'} = \@commit_lines;
1829         my $age = time - $co{'committer_epoch'};
1830         $co{'age'} = $age;
1831         $co{'age_string'} = age_string($age);
1832         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1833         if ($age > 60*60*24*7*2) {
1834                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1835                 $co{'age_string_age'} = $co{'age_string'};
1836         } else {
1837                 $co{'age_string_date'} = $co{'age_string'};
1838                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1839         }
1840         return %co;
1843 sub parse_commit {
1844         my ($commit_id) = @_;
1845         my %co;
1847         local $/ = "\0";
1849         open my $fd, "-|", git_cmd(), "rev-list",
1850                 "--parents",
1851                 "--header",
1852                 "--max-count=1",
1853                 $commit_id,
1854                 "--",
1855                 or die_error(undef, "Open git-rev-list failed");
1856         %co = parse_commit_text(<$fd>, 1);
1857         close $fd;
1859         return %co;
1862 sub parse_commits {
1863         my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1864         my @cos;
1866         $maxcount ||= 1;
1867         $skip ||= 0;
1869         local $/ = "\0";
1871         open my $fd, "-|", git_cmd(), "rev-list",
1872                 "--header",
1873                 ($arg ? ($arg) : ()),
1874                 ("--max-count=" . $maxcount),
1875                 ("--skip=" . $skip),
1876                 @extra_options,
1877                 $commit_id,
1878                 "--",
1879                 ($filename ? ($filename) : ())
1880                 or die_error(undef, "Open git-rev-list failed");
1881         while (my $line = <$fd>) {
1882                 my %co = parse_commit_text($line);
1883                 push @cos, \%co;
1884         }
1885         close $fd;
1887         return wantarray ? @cos : \@cos;
1890 # parse ref from ref_file, given by ref_id, with given type
1891 sub parse_ref {
1892         my $ref_file = shift;
1893         my $ref_id = shift;
1894         my $type = shift || git_get_type($ref_id);
1895         my %ref_item;
1897         $ref_item{'type'} = $type;
1898         $ref_item{'id'} = $ref_id;
1899         $ref_item{'epoch'} = 0;
1900         $ref_item{'age'} = "unknown";
1901         if ($type eq "tag") {
1902                 my %tag = parse_tag($ref_id);
1903                 $ref_item{'comment'} = $tag{'comment'};
1904                 if ($tag{'type'} eq "commit") {
1905                         my %co = parse_commit($tag{'object'});
1906                         $ref_item{'epoch'} = $co{'committer_epoch'};
1907                         $ref_item{'age'} = $co{'age_string'};
1908                 } elsif (defined($tag{'epoch'})) {
1909                         my $age = time - $tag{'epoch'};
1910                         $ref_item{'epoch'} = $tag{'epoch'};
1911                         $ref_item{'age'} = age_string($age);
1912                 }
1913                 $ref_item{'reftype'} = $tag{'type'};
1914                 $ref_item{'name'} = $tag{'name'};
1915                 $ref_item{'refid'} = $tag{'object'};
1916         } elsif ($type eq "commit"){
1917                 my %co = parse_commit($ref_id);
1918                 $ref_item{'reftype'} = "commit";
1919                 $ref_item{'name'} = $ref_file;
1920                 $ref_item{'title'} = $co{'title'};
1921                 $ref_item{'refid'} = $ref_id;
1922                 $ref_item{'epoch'} = $co{'committer_epoch'};
1923                 $ref_item{'age'} = $co{'age_string'};
1924         } else {
1925                 $ref_item{'reftype'} = $type;
1926                 $ref_item{'name'} = $ref_file;
1927                 $ref_item{'refid'} = $ref_id;
1928         }
1930         return %ref_item;
1933 # parse line of git-diff-tree "raw" output
1934 sub parse_difftree_raw_line {
1935         my $line = shift;
1936         my %res;
1938         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1939         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1940         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1941                 $res{'from_mode'} = $1;
1942                 $res{'to_mode'} = $2;
1943                 $res{'from_id'} = $3;
1944                 $res{'to_id'} = $4;
1945                 $res{'status'} = $5;
1946                 $res{'similarity'} = $6;
1947                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1948                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1949                 } else {
1950                         $res{'file'} = unquote($7);
1951                 }
1952         }
1953         # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
1954         # combined diff (for merge commit)
1955         elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
1956                 $res{'nparents'}  = length($1);
1957                 $res{'from_mode'} = [ split(' ', $2) ];
1958                 $res{'to_mode'} = pop @{$res{'from_mode'}};
1959                 $res{'from_id'} = [ split(' ', $3) ];
1960                 $res{'to_id'} = pop @{$res{'from_id'}};
1961                 $res{'status'} = [ split('', $4) ];
1962                 $res{'to_file'} = unquote($5);
1963         }
1964         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1965         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1966                 $res{'commit'} = $1;
1967         }
1969         return wantarray ? %res : \%res;
1972 # parse line of git-ls-tree output
1973 sub parse_ls_tree_line ($;%) {
1974         my $line = shift;
1975         my %opts = @_;
1976         my %res;
1978         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1979         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1981         $res{'mode'} = $1;
1982         $res{'type'} = $2;
1983         $res{'hash'} = $3;
1984         if ($opts{'-z'}) {
1985                 $res{'name'} = $4;
1986         } else {
1987                 $res{'name'} = unquote($4);
1988         }
1990         return wantarray ? %res : \%res;
1993 # generates _two_ hashes, references to which are passed as 2 and 3 argument
1994 sub parse_from_to_diffinfo {
1995         my ($diffinfo, $from, $to, @parents) = @_;
1997         if ($diffinfo->{'nparents'}) {
1998                 # combined diff
1999                 $from->{'file'} = [];
2000                 $from->{'href'} = [];
2001                 fill_from_file_info($diffinfo, @parents)
2002                         unless exists $diffinfo->{'from_file'};
2003                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2004                         $from->{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
2005                         if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2006                                 $from->{'href'}[$i] = href(action=>"blob",
2007                                                            hash_base=>$parents[$i],
2008                                                            hash=>$diffinfo->{'from_id'}[$i],
2009                                                            file_name=>$from->{'file'}[$i]);
2010                         } else {
2011                                 $from->{'href'}[$i] = undef;
2012                         }
2013                 }
2014         } else {
2015                 $from->{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
2016                 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2017                         $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2018                                                hash=>$diffinfo->{'from_id'},
2019                                                file_name=>$from->{'file'});
2020                 } else {
2021                         delete $from->{'href'};
2022                 }
2023         }
2025         $to->{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
2026         if (!is_deleted($diffinfo)) { # file exists in result
2027                 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2028                                      hash=>$diffinfo->{'to_id'},
2029                                      file_name=>$to->{'file'});
2030         } else {
2031                 delete $to->{'href'};
2032         }
2035 ## ......................................................................
2036 ## parse to array of hashes functions
2038 sub git_get_heads_list {
2039         my $limit = shift;
2040         my @headslist;
2042         open my $fd, '-|', git_cmd(), 'for-each-ref',
2043                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2044                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2045                 'refs/heads'
2046                 or return;
2047         while (my $line = <$fd>) {
2048                 my %ref_item;
2050                 chomp $line;
2051                 my ($refinfo, $committerinfo) = split(/\0/, $line);
2052                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2053                 my ($committer, $epoch, $tz) =
2054                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2055                 $name =~ s!^refs/heads/!!;
2057                 $ref_item{'name'}  = $name;
2058                 $ref_item{'id'}    = $hash;
2059                 $ref_item{'title'} = $title || '(no commit message)';
2060                 $ref_item{'epoch'} = $epoch;
2061                 if ($epoch) {
2062                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2063                 } else {
2064                         $ref_item{'age'} = "unknown";
2065                 }
2067                 push @headslist, \%ref_item;
2068         }
2069         close $fd;
2071         return wantarray ? @headslist : \@headslist;
2074 sub git_get_tags_list {
2075         my $limit = shift;
2076         my @tagslist;
2078         open my $fd, '-|', git_cmd(), 'for-each-ref',
2079                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2080                 '--format=%(objectname) %(objecttype) %(refname) '.
2081                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2082                 'refs/tags'
2083                 or return;
2084         while (my $line = <$fd>) {
2085                 my %ref_item;
2087                 chomp $line;
2088                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2089                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2090                 my ($creator, $epoch, $tz) =
2091                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2092                 $name =~ s!^refs/tags/!!;
2094                 $ref_item{'type'} = $type;
2095                 $ref_item{'id'} = $id;
2096                 $ref_item{'name'} = $name;
2097                 if ($type eq "tag") {
2098                         $ref_item{'subject'} = $title;
2099                         $ref_item{'reftype'} = $reftype;
2100                         $ref_item{'refid'}   = $refid;
2101                 } else {
2102                         $ref_item{'reftype'} = $type;
2103                         $ref_item{'refid'}   = $id;
2104                 }
2106                 if ($type eq "tag" || $type eq "commit") {
2107                         $ref_item{'epoch'} = $epoch;
2108                         if ($epoch) {
2109                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2110                         } else {
2111                                 $ref_item{'age'} = "unknown";
2112                         }
2113                 }
2115                 push @tagslist, \%ref_item;
2116         }
2117         close $fd;
2119         return wantarray ? @tagslist : \@tagslist;
2122 ## ----------------------------------------------------------------------
2123 ## filesystem-related functions
2125 sub get_file_owner {
2126         my $path = shift;
2128         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2129         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2130         if (!defined $gcos) {
2131                 return undef;
2132         }
2133         my $owner = $gcos;
2134         $owner =~ s/[,;].*$//;
2135         return to_utf8($owner);
2138 ## ......................................................................
2139 ## mimetype related functions
2141 sub mimetype_guess_file {
2142         my $filename = shift;
2143         my $mimemap = shift;
2144         -r $mimemap or return undef;
2146         my %mimemap;
2147         open(MIME, $mimemap) or return undef;
2148         while (<MIME>) {
2149                 next if m/^#/; # skip comments
2150                 my ($mime, $exts) = split(/\t+/);
2151                 if (defined $exts) {
2152                         my @exts = split(/\s+/, $exts);
2153                         foreach my $ext (@exts) {
2154                                 $mimemap{$ext} = $mime;
2155                         }
2156                 }
2157         }
2158         close(MIME);
2160         $filename =~ /\.([^.]*)$/;
2161         return $mimemap{$1};
2164 sub mimetype_guess {
2165         my $filename = shift;
2166         my $mime;
2167         $filename =~ /\./ or return undef;
2169         if ($mimetypes_file) {
2170                 my $file = $mimetypes_file;
2171                 if ($file !~ m!^/!) { # if it is relative path
2172                         # it is relative to project
2173                         $file = "$projectroot/$project/$file";
2174                 }
2175                 $mime = mimetype_guess_file($filename, $file);
2176         }
2177         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2178         return $mime;
2181 sub blob_mimetype {
2182         my $fd = shift;
2183         my $filename = shift;
2185         if ($filename) {
2186                 my $mime = mimetype_guess($filename);
2187                 $mime and return $mime;
2188         }
2190         # just in case
2191         return $default_blob_plain_mimetype unless $fd;
2193         if (-T $fd) {
2194                 return 'text/plain' .
2195                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
2196         } elsif (! $filename) {
2197                 return 'application/octet-stream';
2198         } elsif ($filename =~ m/\.png$/i) {
2199                 return 'image/png';
2200         } elsif ($filename =~ m/\.gif$/i) {
2201                 return 'image/gif';
2202         } elsif ($filename =~ m/\.jpe?g$/i) {
2203                 return 'image/jpeg';
2204         } else {
2205                 return 'application/octet-stream';
2206         }
2209 ## ======================================================================
2210 ## functions printing HTML: header, footer, error page
2212 sub git_header_html {
2213         my $status = shift || "200 OK";
2214         my $expires = shift;
2216         my $title = "$site_name";
2217         if (defined $project) {
2218                 $title .= " - " . to_utf8($project);
2219                 if (defined $action) {
2220                         $title .= "/$action";
2221                         if (defined $file_name) {
2222                                 $title .= " - " . esc_path($file_name);
2223                                 if ($action eq "tree" && $file_name !~ m|/$|) {
2224                                         $title .= "/";
2225                                 }
2226                         }
2227                 }
2228         }
2229         my $content_type;
2230         # require explicit support from the UA if we are to send the page as
2231         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2232         # we have to do this because MSIE sometimes globs '*/*', pretending to
2233         # support xhtml+xml but choking when it gets what it asked for.
2234         if (defined $cgi->http('HTTP_ACCEPT') &&
2235             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2236             $cgi->Accept('application/xhtml+xml') != 0) {
2237                 $content_type = 'application/xhtml+xml';
2238         } else {
2239                 $content_type = 'text/html';
2240         }
2241         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2242                            -status=> $status, -expires => $expires);
2243         my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2244         print <<EOF;
2245 <?xml version="1.0" encoding="utf-8"?>
2246 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2247 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2248 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2249 <!-- git core binaries version $git_version -->
2250 <head>
2251 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2252 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2253 <meta name="robots" content="index, nofollow"/>
2254 <title>$title</title>
2255 EOF
2256 # print out each stylesheet that exist
2257         if (defined $stylesheet) {
2258 #provides backwards capability for those people who define style sheet in a config file
2259                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2260         } else {
2261                 foreach my $stylesheet (@stylesheets) {
2262                         next unless $stylesheet;
2263                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2264                 }
2265         }
2266         if (defined $project) {
2267                 printf('<link rel="alternate" title="%s log RSS feed" '.
2268                        'href="%s" type="application/rss+xml" />'."\n",
2269                        esc_param($project), href(action=>"rss"));
2270                 printf('<link rel="alternate" title="%s log Atom feed" '.
2271                        'href="%s" type="application/atom+xml" />'."\n",
2272                        esc_param($project), href(action=>"atom"));
2273         } else {
2274                 printf('<link rel="alternate" title="%s projects list" '.
2275                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
2276                        $site_name, href(project=>undef, action=>"project_index"));
2277                 printf('<link rel="alternate" title="%s projects feeds" '.
2278                        'href="%s" type="text/x-opml"/>'."\n",
2279                        $site_name, href(project=>undef, action=>"opml"));
2280         }
2281         if (defined $favicon) {
2282                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
2283         }
2285         print "</head>\n" .
2286               "<body>\n";
2288         if (-f $site_header) {
2289                 open (my $fd, $site_header);
2290                 print <$fd>;
2291                 close $fd;
2292         }
2294         print "<div class=\"page_header\">\n" .
2295               $cgi->a({-href => esc_url($logo_url),
2296                        -title => $logo_label},
2297                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2298         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2299         if (defined $project) {
2300                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2301                 if (defined $action) {
2302                         print " / $action";
2303                 }
2304                 print "\n";
2305         }
2306         print "</div>\n";
2308         my ($have_search) = gitweb_check_feature('search');
2309         if ((defined $project) && ($have_search)) {
2310                 if (!defined $searchtext) {
2311                         $searchtext = "";
2312                 }
2313                 my $search_hash;
2314                 if (defined $hash_base) {
2315                         $search_hash = $hash_base;
2316                 } elsif (defined $hash) {
2317                         $search_hash = $hash;
2318                 } else {
2319                         $search_hash = "HEAD";
2320                 }
2321                 my $action = $my_uri;
2322                 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2323                 if ($use_pathinfo) {
2324                         $action .= "/$project";
2325                 } else {
2326                         $cgi->param("p", $project);
2327                 }
2328                 $cgi->param("a", "search");
2329                 $cgi->param("h", $search_hash);
2330                 print $cgi->startform(-method => "get", -action => $action) .
2331                       "<div class=\"search\">\n" .
2332                       (!$use_pathinfo && $cgi->hidden(-name => "p") . "\n") .
2333                       $cgi->hidden(-name => "a") . "\n" .
2334                       $cgi->hidden(-name => "h") . "\n" .
2335                       $cgi->popup_menu(-name => 'st', -default => 'commit',
2336                                        -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2337                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2338                       " search:\n",
2339                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2340                       "</div>" .
2341                       $cgi->end_form() . "\n";
2342         }
2345 sub git_footer_html {
2346         print "<div class=\"page_footer\">\n";
2347         if (defined $project) {
2348                 my $descr = git_get_project_description($project);
2349                 if (defined $descr) {
2350                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2351                 }
2352                 print $cgi->a({-href => href(action=>"rss"),
2353                               -class => "rss_logo"}, "RSS") . " ";
2354                 print $cgi->a({-href => href(action=>"atom"),
2355                               -class => "rss_logo"}, "Atom") . "\n";
2356         } else {
2357                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
2358                               -class => "rss_logo"}, "OPML") . " ";
2359                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2360                               -class => "rss_logo"}, "TXT") . "\n";
2361         }
2362         print "</div>\n" ;
2364         if (-f $site_footer) {
2365                 open (my $fd, $site_footer);
2366                 print <$fd>;
2367                 close $fd;
2368         }
2370         print "</body>\n" .
2371               "</html>";
2374 sub die_error {
2375         my $status = shift || "403 Forbidden";
2376         my $error = shift || "Malformed query, file missing or permission denied";
2378         git_header_html($status);
2379         print <<EOF;
2380 <div class="page_body">
2381 <br /><br />
2382 $status - $error
2383 <br />
2384 </div>
2385 EOF
2386         git_footer_html();
2387         exit;
2390 ## ----------------------------------------------------------------------
2391 ## functions printing or outputting HTML: navigation
2393 sub git_print_page_nav {
2394         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2395         $extra = '' if !defined $extra; # pager or formats
2397         my @navs = qw(summary shortlog log commit commitdiff tree);
2398         if ($suppress) {
2399                 @navs = grep { $_ ne $suppress } @navs;
2400         }
2402         my %arg = map { $_ => {action=>$_} } @navs;
2403         if (defined $head) {
2404                 for (qw(commit commitdiff)) {
2405                         $arg{$_}{'hash'} = $head;
2406                 }
2407                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2408                         for (qw(shortlog log)) {
2409                                 $arg{$_}{'hash'} = $head;
2410                         }
2411                 }
2412         }
2413         $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2414         $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2416         print "<div class=\"page_nav\">\n" .
2417                 (join " | ",
2418                  map { $_ eq $current ?
2419                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2420                  } @navs);
2421         print "<br/>\n$extra<br/>\n" .
2422               "</div>\n";
2425 sub format_paging_nav {
2426         my ($action, $hash, $head, $page, $nrevs) = @_;
2427         my $paging_nav;
2430         if ($hash ne $head || $page) {
2431                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2432         } else {
2433                 $paging_nav .= "HEAD";
2434         }
2436         if ($page > 0) {
2437                 $paging_nav .= " &sdot; " .
2438                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
2439                                  -accesskey => "p", -title => "Alt-p"}, "prev");
2440         } else {
2441                 $paging_nav .= " &sdot; prev";
2442         }
2444         if ($nrevs >= (100 * ($page+1)-1)) {
2445                 $paging_nav .= " &sdot; " .
2446                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
2447                                  -accesskey => "n", -title => "Alt-n"}, "next");
2448         } else {
2449                 $paging_nav .= " &sdot; next";
2450         }
2452         return $paging_nav;
2455 ## ......................................................................
2456 ## functions printing or outputting HTML: div
2458 sub git_print_header_div {
2459         my ($action, $title, $hash, $hash_base) = @_;
2460         my %args = ();
2462         $args{'action'} = $action;
2463         $args{'hash'} = $hash if $hash;
2464         $args{'hash_base'} = $hash_base if $hash_base;
2466         print "<div class=\"header\">\n" .
2467               $cgi->a({-href => href(%args), -class => "title"},
2468               $title ? $title : $action) .
2469               "\n</div>\n";
2472 #sub git_print_authorship (\%) {
2473 sub git_print_authorship {
2474         my $co = shift;
2476         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2477         print "<div class=\"author_date\">" .
2478               esc_html($co->{'author_name'}) .
2479               " [$ad{'rfc2822'}";
2480         if ($ad{'hour_local'} < 6) {
2481                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2482                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2483         } else {
2484                 printf(" (%02d:%02d %s)",
2485                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2486         }
2487         print "]</div>\n";
2490 sub git_print_page_path {
2491         my $name = shift;
2492         my $type = shift;
2493         my $hb = shift;
2496         print "<div class=\"page_path\">";
2497         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2498                       -title => 'tree root'}, to_utf8("[$project]"));
2499         print " / ";
2500         if (defined $name) {
2501                 my @dirname = split '/', $name;
2502                 my $basename = pop @dirname;
2503                 my $fullname = '';
2505                 foreach my $dir (@dirname) {
2506                         $fullname .= ($fullname ? '/' : '') . $dir;
2507                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2508                                                      hash_base=>$hb),
2509                                       -title => $fullname}, esc_path($dir));
2510                         print " / ";
2511                 }
2512                 if (defined $type && $type eq 'blob') {
2513                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2514                                                      hash_base=>$hb),
2515                                       -title => $name}, esc_path($basename));
2516                 } elsif (defined $type && $type eq 'tree') {
2517                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2518                                                      hash_base=>$hb),
2519                                       -title => $name}, esc_path($basename));
2520                         print " / ";
2521                 } else {
2522                         print esc_path($basename);
2523                 }
2524         }
2525         print "<br/></div>\n";
2528 # sub git_print_log (\@;%) {
2529 sub git_print_log ($;%) {
2530         my $log = shift;
2531         my %opts = @_;
2533         if ($opts{'-remove_title'}) {
2534                 # remove title, i.e. first line of log
2535                 shift @$log;
2536         }
2537         # remove leading empty lines
2538         while (defined $log->[0] && $log->[0] eq "") {
2539                 shift @$log;
2540         }
2542         # print log
2543         my $signoff = 0;
2544         my $empty = 0;
2545         foreach my $line (@$log) {
2546                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2547                         $signoff = 1;
2548                         $empty = 0;
2549                         if (! $opts{'-remove_signoff'}) {
2550                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2551                                 next;
2552                         } else {
2553                                 # remove signoff lines
2554                                 next;
2555                         }
2556                 } else {
2557                         $signoff = 0;
2558                 }
2560                 # print only one empty line
2561                 # do not print empty line after signoff
2562                 if ($line eq "") {
2563                         next if ($empty || $signoff);
2564                         $empty = 1;
2565                 } else {
2566                         $empty = 0;
2567                 }
2569                 print format_log_line_html($line) . "<br/>\n";
2570         }
2572         if ($opts{'-final_empty_line'}) {
2573                 # end with single empty line
2574                 print "<br/>\n" unless $empty;
2575         }
2578 # return link target (what link points to)
2579 sub git_get_link_target {
2580         my $hash = shift;
2581         my $link_target;
2583         # read link
2584         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2585                 or return;
2586         {
2587                 local $/;
2588                 $link_target = <$fd>;
2589         }
2590         close $fd
2591                 or return;
2593         return $link_target;
2596 # given link target, and the directory (basedir) the link is in,
2597 # return target of link relative to top directory (top tree);
2598 # return undef if it is not possible (including absolute links).
2599 sub normalize_link_target {
2600         my ($link_target, $basedir, $hash_base) = @_;
2602         # we can normalize symlink target only if $hash_base is provided
2603         return unless $hash_base;
2605         # absolute symlinks (beginning with '/') cannot be normalized
2606         return if (substr($link_target, 0, 1) eq '/');
2608         # normalize link target to path from top (root) tree (dir)
2609         my $path;
2610         if ($basedir) {
2611                 $path = $basedir . '/' . $link_target;
2612         } else {
2613                 # we are in top (root) tree (dir)
2614                 $path = $link_target;
2615         }
2617         # remove //, /./, and /../
2618         my @path_parts;
2619         foreach my $part (split('/', $path)) {
2620                 # discard '.' and ''
2621                 next if (!$part || $part eq '.');
2622                 # handle '..'
2623                 if ($part eq '..') {
2624                         if (@path_parts) {
2625                                 pop @path_parts;
2626                         } else {
2627                                 # link leads outside repository (outside top dir)
2628                                 return;
2629                         }
2630                 } else {
2631                         push @path_parts, $part;
2632                 }
2633         }
2634         $path = join('/', @path_parts);
2636         return $path;
2639 # print tree entry (row of git_tree), but without encompassing <tr> element
2640 sub git_print_tree_entry {
2641         my ($t, $basedir, $hash_base, $have_blame) = @_;
2643         my %base_key = ();
2644         $base_key{'hash_base'} = $hash_base if defined $hash_base;
2646         # The format of a table row is: mode list link.  Where mode is
2647         # the mode of the entry, list is the name of the entry, an href,
2648         # and link is the action links of the entry.
2650         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2651         if ($t->{'type'} eq "blob") {
2652                 print "<td class=\"list\">" .
2653                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2654                                                file_name=>"$basedir$t->{'name'}", %base_key),
2655                                 -class => "list"}, esc_path($t->{'name'}));
2656                 if (S_ISLNK(oct $t->{'mode'})) {
2657                         my $link_target = git_get_link_target($t->{'hash'});
2658                         if ($link_target) {
2659                                 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2660                                 if (defined $norm_target) {
2661                                         print " -> " .
2662                                               $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2663                                                                      file_name=>$norm_target),
2664                                                        -title => $norm_target}, esc_path($link_target));
2665                                 } else {
2666                                         print " -> " . esc_path($link_target);
2667                                 }
2668                         }
2669                 }
2670                 print "</td>\n";
2671                 print "<td class=\"link\">";
2672                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2673                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2674                               "blob");
2675                 if ($have_blame) {
2676                         print " | " .
2677                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2678                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
2679                                       "blame");
2680                 }
2681                 if (defined $hash_base) {
2682                         print " | " .
2683                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2684                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2685                                       "history");
2686                 }
2687                 print " | " .
2688                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2689                                                file_name=>"$basedir$t->{'name'}")},
2690                                 "raw");
2691                 print "</td>\n";
2693         } elsif ($t->{'type'} eq "tree") {
2694                 print "<td class=\"list\">";
2695                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2696                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2697                               esc_path($t->{'name'}));
2698                 print "</td>\n";
2699                 print "<td class=\"link\">";
2700                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2701                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2702                               "tree");
2703                 if (defined $hash_base) {
2704                         print " | " .
2705                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2706                                                      file_name=>"$basedir$t->{'name'}")},
2707                                       "history");
2708                 }
2709                 print "</td>\n";
2710         }
2713 ## ......................................................................
2714 ## functions printing large fragments of HTML
2716 sub fill_from_file_info {
2717         my ($diff, @parents) = @_;
2719         $diff->{'from_file'} = [ ];
2720         $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
2721         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2722                 if ($diff->{'status'}[$i] eq 'R' ||
2723                     $diff->{'status'}[$i] eq 'C') {
2724                         $diff->{'from_file'}[$i] =
2725                                 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
2726                 }
2727         }
2729         return $diff;
2732 # parameters can be strings, or references to arrays of strings
2733 sub from_ids_eq {
2734         my ($a, $b) = @_;
2736         if (ref($a) eq "ARRAY" && ref($b) eq "ARRAY" && @$a == @$b) {
2737                 for (my $i = 0; $i < @$a; ++$i) {
2738                         return 0 unless ($a->[$i] eq $b->[$i]);
2739                 }
2740                 return 1;
2741         } elsif (!ref($a) && !ref($b)) {
2742                 return $a eq $b;
2743         } else {
2744                 return 0;
2745         }
2748 sub is_deleted {
2749         my $diffinfo = shift;
2751         return $diffinfo->{'to_id'} eq ('0' x 40);
2754 sub git_difftree_body {
2755         my ($difftree, $hash, @parents) = @_;
2756         my ($parent) = $parents[0];
2757         my ($have_blame) = gitweb_check_feature('blame');
2758         print "<div class=\"list_head\">\n";
2759         if ($#{$difftree} > 10) {
2760                 print(($#{$difftree} + 1) . " files changed:\n");
2761         }
2762         print "</div>\n";
2764         print "<table class=\"" .
2765               (@parents > 1 ? "combined " : "") .
2766               "diff_tree\">\n";
2768         # header only for combined diff in 'commitdiff' view
2769         my $has_header = @parents > 1 && $action eq 'commitdiff';
2770         if ($has_header) {
2771                 # table header
2772                 print "<thead><tr>\n" .
2773                        "<th></th><th></th>\n"; # filename, patchN link
2774                 for (my $i = 0; $i < @parents; $i++) {
2775                         my $par = $parents[$i];
2776                         print "<th>" .
2777                               $cgi->a({-href => href(action=>"commitdiff",
2778                                                      hash=>$hash, hash_parent=>$par),
2779                                        -title => 'commitdiff to parent number ' .
2780                                                   ($i+1) . ': ' . substr($par,0,7)},
2781                                       $i+1) .
2782                               "&nbsp;</th>\n";
2783                 }
2784                 print "</tr></thead>\n<tbody>\n";
2785         }
2787         my $alternate = 1;
2788         my $patchno = 0;
2789         foreach my $line (@{$difftree}) {
2790                 my $diff;
2791                 if (ref($line) eq "HASH") {
2792                         # pre-parsed (or generated by hand)
2793                         $diff = $line;
2794                 } else {
2795                         $diff = parse_difftree_raw_line($line);
2796                 }
2798                 if ($alternate) {
2799                         print "<tr class=\"dark\">\n";
2800                 } else {
2801                         print "<tr class=\"light\">\n";
2802                 }
2803                 $alternate ^= 1;
2805                 if (exists $diff->{'nparents'}) { # combined diff
2807                         fill_from_file_info($diff, @parents)
2808                                 unless exists $diff->{'from_file'};
2810                         if (!is_deleted($diff)) {
2811                                 # file exists in the result (child) commit
2812                                 print "<td>" .
2813                                       $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2814                                                              file_name=>$diff->{'to_file'},
2815                                                              hash_base=>$hash),
2816                                               -class => "list"}, esc_path($diff->{'to_file'})) .
2817                                       "</td>\n";
2818                         } else {
2819                                 print "<td>" .
2820                                       esc_path($diff->{'to_file'}) .
2821                                       "</td>\n";
2822                         }
2824                         if ($action eq 'commitdiff') {
2825                                 # link to patch
2826                                 $patchno++;
2827                                 print "<td class=\"link\">" .
2828                                       $cgi->a({-href => "#patch$patchno"}, "patch") .
2829                                       " | " .
2830                                       "</td>\n";
2831                         }
2833                         my $has_history = 0;
2834                         my $not_deleted = 0;
2835                         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2836                                 my $hash_parent = $parents[$i];
2837                                 my $from_hash = $diff->{'from_id'}[$i];
2838                                 my $from_path = $diff->{'from_file'}[$i];
2839                                 my $status = $diff->{'status'}[$i];
2841                                 $has_history ||= ($status ne 'A');
2842                                 $not_deleted ||= ($status ne 'D');
2844                                 if ($status eq 'A') {
2845                                         print "<td  class=\"link\" align=\"right\"> | </td>\n";
2846                                 } elsif ($status eq 'D') {
2847                                         print "<td class=\"link\">" .
2848                                               $cgi->a({-href => href(action=>"blob",
2849                                                                      hash_base=>$hash,
2850                                                                      hash=>$from_hash,
2851                                                                      file_name=>$from_path)},
2852                                                       "blob" . ($i+1)) .
2853                                               " | </td>\n";
2854                                 } else {
2855                                         if ($diff->{'to_id'} eq $from_hash) {
2856                                                 print "<td class=\"link nochange\">";
2857                                         } else {
2858                                                 print "<td class=\"link\">";
2859                                         }
2860                                         print $cgi->a({-href => href(action=>"blobdiff",
2861                                                                      hash=>$diff->{'to_id'},
2862                                                                      hash_parent=>$from_hash,
2863                                                                      hash_base=>$hash,
2864                                                                      hash_parent_base=>$hash_parent,
2865                                                                      file_name=>$diff->{'to_file'},
2866                                                                      file_parent=>$from_path)},
2867                                                       "diff" . ($i+1)) .
2868                                               " | </td>\n";
2869                                 }
2870                         }
2872                         print "<td class=\"link\">";
2873                         if ($not_deleted) {
2874                                 print $cgi->a({-href => href(action=>"blob",
2875                                                              hash=>$diff->{'to_id'},
2876                                                              file_name=>$diff->{'to_file'},
2877                                                              hash_base=>$hash)},
2878                                               "blob");
2879                                 print " | " if ($has_history);
2880                         }
2881                         if ($has_history) {
2882                                 print $cgi->a({-href => href(action=>"history",
2883                                                              file_name=>$diff->{'to_file'},
2884                                                              hash_base=>$hash)},
2885                                               "history");
2886                         }
2887                         print "</td>\n";
2889                         print "</tr>\n";
2890                         next; # instead of 'else' clause, to avoid extra indent
2891                 }
2892                 # else ordinary diff
2894                 my ($to_mode_oct, $to_mode_str, $to_file_type);
2895                 my ($from_mode_oct, $from_mode_str, $from_file_type);
2896                 if ($diff->{'to_mode'} ne ('0' x 6)) {
2897                         $to_mode_oct = oct $diff->{'to_mode'};
2898                         if (S_ISREG($to_mode_oct)) { # only for regular file
2899                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2900                         }
2901                         $to_file_type = file_type($diff->{'to_mode'});
2902                 }
2903                 if ($diff->{'from_mode'} ne ('0' x 6)) {
2904                         $from_mode_oct = oct $diff->{'from_mode'};
2905                         if (S_ISREG($to_mode_oct)) { # only for regular file
2906                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2907                         }
2908                         $from_file_type = file_type($diff->{'from_mode'});
2909                 }
2911                 if ($diff->{'status'} eq "A") { # created
2912                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2913                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2914                         $mode_chng   .= "]</span>";
2915                         print "<td>";
2916                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2917                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
2918                                       -class => "list"}, esc_path($diff->{'file'}));
2919                         print "</td>\n";
2920                         print "<td>$mode_chng</td>\n";
2921                         print "<td class=\"link\">";
2922                         if ($action eq 'commitdiff') {
2923                                 # link to patch
2924                                 $patchno++;
2925                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2926                                 print " | ";
2927                         }
2928                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2929                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
2930                                       "blob");
2931                         print "</td>\n";
2933                 } elsif ($diff->{'status'} eq "D") { # deleted
2934                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2935                         print "<td>";
2936                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2937                                                      hash_base=>$parent, file_name=>$diff->{'file'}),
2938                                        -class => "list"}, esc_path($diff->{'file'}));
2939                         print "</td>\n";
2940                         print "<td>$mode_chng</td>\n";
2941                         print "<td class=\"link\">";
2942                         if ($action eq 'commitdiff') {
2943                                 # link to patch
2944                                 $patchno++;
2945                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2946                                 print " | ";
2947                         }
2948                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2949                                                      hash_base=>$parent, file_name=>$diff->{'file'})},
2950                                       "blob") . " | ";
2951                         if ($have_blame) {
2952                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2953                                                              file_name=>$diff->{'file'})},
2954                                               "blame") . " | ";
2955                         }
2956                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2957                                                      file_name=>$diff->{'file'})},
2958                                       "history");
2959                         print "</td>\n";
2961                 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
2962                         my $mode_chnge = "";
2963                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2964                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2965                                 if ($from_file_type ne $to_file_type) {
2966                                         $mode_chnge .= " from $from_file_type to $to_file_type";
2967                                 }
2968                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2969                                         if ($from_mode_str && $to_mode_str) {
2970                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2971                                         } elsif ($to_mode_str) {
2972                                                 $mode_chnge .= " mode: $to_mode_str";
2973                                         }
2974                                 }
2975                                 $mode_chnge .= "]</span>\n";
2976                         }
2977                         print "<td>";
2978                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2979                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
2980                                       -class => "list"}, esc_path($diff->{'file'}));
2981                         print "</td>\n";
2982                         print "<td>$mode_chnge</td>\n";
2983                         print "<td class=\"link\">";
2984                         if ($action eq 'commitdiff') {
2985                                 # link to patch
2986                                 $patchno++;
2987                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2988                                       " | ";
2989                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
2990                                 # "commit" view and modified file (not onlu mode changed)
2991                                 print $cgi->a({-href => href(action=>"blobdiff",
2992                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
2993                                                              hash_base=>$hash, hash_parent_base=>$parent,
2994                                                              file_name=>$diff->{'file'})},
2995                                               "diff") .
2996                                       " | ";
2997                         }
2998                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2999                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
3000                                        "blob") . " | ";
3001                         if ($have_blame) {
3002                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3003                                                              file_name=>$diff->{'file'})},
3004                                               "blame") . " | ";
3005                         }
3006                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3007                                                      file_name=>$diff->{'file'})},
3008                                       "history");
3009                         print "</td>\n";
3011                 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3012                         my %status_name = ('R' => 'moved', 'C' => 'copied');
3013                         my $nstatus = $status_name{$diff->{'status'}};
3014                         my $mode_chng = "";
3015                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3016                                 # mode also for directories, so we cannot use $to_mode_str
3017                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3018                         }
3019                         print "<td>" .
3020                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3021                                                      hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3022                                       -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3023                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3024                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3025                                                      hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3026                                       -class => "list"}, esc_path($diff->{'from_file'})) .
3027                               " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3028                               "<td class=\"link\">";
3029                         if ($action eq 'commitdiff') {
3030                                 # link to patch
3031                                 $patchno++;
3032                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3033                                       " | ";
3034                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3035                                 # "commit" view and modified file (not only pure rename or copy)
3036                                 print $cgi->a({-href => href(action=>"blobdiff",
3037                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3038                                                              hash_base=>$hash, hash_parent_base=>$parent,
3039                                                              file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3040                                               "diff") .
3041                                       " | ";
3042                         }
3043                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3044                                                      hash_base=>$parent, file_name=>$diff->{'to_file'})},
3045                                       "blob") . " | ";
3046                         if ($have_blame) {
3047                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3048                                                              file_name=>$diff->{'to_file'})},
3049                                               "blame") . " | ";
3050                         }
3051                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3052                                                     file_name=>$diff->{'to_file'})},
3053                                       "history");
3054                         print "</td>\n";
3056                 } # we should not encounter Unmerged (U) or Unknown (X) status
3057                 print "</tr>\n";
3058         }
3059         print "</tbody>" if $has_header;
3060         print "</table>\n";
3063 sub git_patchset_body {
3064         my ($fd, $difftree, $hash, @hash_parents) = @_;
3065         my ($hash_parent) = $hash_parents[0];
3067         my $patch_idx = 0;
3068         my $patch_number = 0;
3069         my $patch_line;
3070         my $diffinfo;
3071         my (%from, %to);
3073         print "<div class=\"patchset\">\n";
3075         # skip to first patch
3076         while ($patch_line = <$fd>) {
3077                 chomp $patch_line;
3079                 last if ($patch_line =~ m/^diff /);
3080         }
3082  PATCH:
3083         while ($patch_line) {
3084                 my @diff_header;
3085                 my ($from_id, $to_id);
3087                 # git diff header
3088                 #assert($patch_line =~ m/^diff /) if DEBUG;
3089                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3090                 $patch_number++;
3091                 push @diff_header, $patch_line;
3093                 # extended diff header
3094         EXTENDED_HEADER:
3095                 while ($patch_line = <$fd>) {
3096                         chomp $patch_line;
3098                         last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3100                         if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
3101                                 $from_id = $1;
3102                                 $to_id   = $2;
3103                         } elsif ($patch_line =~ m/^index ((?:[0-9a-fA-F]{40},)+[0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
3104                                 $from_id = [ split(',', $1) ];
3105                                 $to_id   = $2;
3106                         }
3108                         push @diff_header, $patch_line;
3109                 }
3110                 my $last_patch_line = $patch_line;
3112                 # check if current patch belong to current raw line
3113                 # and parse raw git-diff line if needed
3114                 if (defined $diffinfo &&
3115                     defined $from_id && defined $to_id &&
3116                     from_ids_eq($diffinfo->{'from_id'}, $from_id) &&
3117                     $diffinfo->{'to_id'} eq $to_id) {
3118                         # this is continuation of a split patch
3119                         print "<div class=\"patch cont\">\n";
3120                 } else {
3121                         # advance raw git-diff output if needed
3122                         $patch_idx++ if defined $diffinfo;
3124                         # compact combined diff output can have some patches skipped
3125                         # find which patch (using pathname of result) we are at now
3126                         my $to_name;
3127                         if ($diff_header[0] =~ m!^diff --cc "?(.*)"?$!) {
3128                                 $to_name = $1;
3129                         }
3131                         do {
3132                                 # read and prepare patch information
3133                                 if (ref($difftree->[$patch_idx]) eq "HASH") {
3134                                         # pre-parsed (or generated by hand)
3135                                         $diffinfo = $difftree->[$patch_idx];
3136                                 } else {
3137                                         $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
3138                                 }
3140                                 # check if current raw line has no patch (it got simplified)
3141                                 if (defined $to_name && $to_name ne $diffinfo->{'to_file'}) {
3142                                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3143                                               format_diff_cc_simplified($diffinfo, @hash_parents) .
3144                                               "</div>\n";  # class="patch"
3146                                         $patch_idx++;
3147                                         $patch_number++;
3148                                 }
3149                         } until (!defined $to_name || $to_name eq $diffinfo->{'to_file'} ||
3150                                  $patch_idx > $#$difftree);
3151                         # modifies %from, %to hashes
3152                         parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3153                         if ($diffinfo->{'nparents'}) {
3154                                 # combined diff
3155                                 $from{'file'} = [];
3156                                 $from{'href'} = [];
3157                                 fill_from_file_info($diffinfo, @hash_parents)
3158                                         unless exists $diffinfo->{'from_file'};
3159                                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3160                                         $from{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
3161                                         if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3162                                                 $from{'href'}[$i] = href(action=>"blob",
3163                                                                          hash_base=>$hash_parents[$i],
3164                                                                          hash=>$diffinfo->{'from_id'}[$i],
3165                                                                          file_name=>$from{'file'}[$i]);
3166                                         } else {
3167                                                 $from{'href'}[$i] = undef;
3168                                         }
3169                                 }
3170                         } else {
3171                                 $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
3172                                 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3173                                         $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3174                                                              hash=>$diffinfo->{'from_id'},
3175                                                              file_name=>$from{'file'});
3176                                 } else {
3177                                         delete $from{'href'};
3178                                 }
3179                         }
3181                         $to{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
3182                         if (!is_deleted($diffinfo)) { # file exists in result
3183                                 $to{'href'} = href(action=>"blob", hash_base=>$hash,
3184                                                    hash=>$diffinfo->{'to_id'},
3185                                                    file_name=>$to{'file'});
3186                         } else {
3187                                 delete $to{'href'};
3188                         }
3189                         # this is first patch for raw difftree line with $patch_idx index
3190                         # we index @$difftree array from 0, but number patches from 1
3191                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3192                 }
3194                 # print "git diff" header
3195                 $patch_line = shift @diff_header;
3196                 print format_git_diff_header_line($patch_line, $diffinfo,
3197                                                   \%from, \%to);
3199                 # print extended diff header
3200                 print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
3201         EXTENDED_HEADER:
3202                 foreach $patch_line (@diff_header) {
3203                         print format_extended_diff_header_line($patch_line, $diffinfo,
3204                                                                \%from, \%to);
3205                 }
3206                 print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
3208                 # from-file/to-file diff header
3209                 $patch_line = $last_patch_line;
3210                 if (! $patch_line) {
3211                         print "</div>\n"; # class="patch"
3212                         last PATCH;
3213                 }
3214                 next PATCH if ($patch_line =~ m/^diff /);
3215                 #assert($patch_line =~ m/^---/) if DEBUG;
3216                 #assert($patch_line eq $last_patch_line) if DEBUG;
3218                 $patch_line = <$fd>;
3219                 chomp $patch_line;
3220                 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3222                 print format_diff_from_to_header($last_patch_line, $patch_line,
3223                                                  $diffinfo, \%from, \%to,
3224                                                  @hash_parents);
3226                 # the patch itself
3227         LINE:
3228                 while ($patch_line = <$fd>) {
3229                         chomp $patch_line;
3231                         next PATCH if ($patch_line =~ m/^diff /);
3233                         print format_diff_line($patch_line, \%from, \%to);
3234                 }
3236         } continue {
3237                 print "</div>\n"; # class="patch"
3238         }
3240         # for compact combined (--cc) format, with chunk and patch simpliciaction
3241         # patchset might be empty, but there might be unprocessed raw lines
3242         for ($patch_idx++ if $patch_number > 0;
3243              $patch_idx < @$difftree;
3244              $patch_idx++) {
3245                 # read and prepare patch information
3246                 if (ref($difftree->[$patch_idx]) eq "HASH") {
3247                         # pre-parsed (or generated by hand)
3248                         $diffinfo = $difftree->[$patch_idx];
3249                 } else {
3250                         $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
3251                 }
3253                 # generate anchor for "patch" links in difftree / whatchanged part
3254                 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3255                       format_diff_cc_simplified($diffinfo, @hash_parents) .
3256                       "</div>\n";  # class="patch"
3258                 $patch_number++;
3259         }
3261         if ($patch_number == 0) {
3262                 if (@hash_parents > 1) {
3263                         print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3264                 } else {
3265                         print "<div class=\"diff nodifferences\">No differences found</div>\n";
3266                 }
3267         }
3269         print "</div>\n"; # class="patchset"
3272 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3274 sub git_project_list_body {
3275         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3277         my ($check_forks) = gitweb_check_feature('forks');
3279         my @projects;
3280         foreach my $pr (@$projlist) {
3281                 my (@aa) = git_get_last_activity($pr->{'path'});
3282                 unless (@aa) {
3283                         next;
3284                 }
3285                 ($pr->{'age'}, $pr->{'age_string'}) = @aa;
3286                 if (!defined $pr->{'descr'}) {
3287                         my $descr = git_get_project_description($pr->{'path'}) || "";
3288                         $pr->{'descr_long'} = to_utf8($descr);
3289                         $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3290                 }
3291                 if (!defined $pr->{'owner'}) {
3292                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3293                 }
3294                 if ($check_forks) {
3295                         my $pname = $pr->{'path'};
3296                         if (($pname =~ s/\.git$//) &&
3297                             ($pname !~ /\/$/) &&
3298                             (-d "$projectroot/$pname")) {
3299                                 $pr->{'forks'} = "-d $projectroot/$pname";
3300                         }
3301                         else {
3302                                 $pr->{'forks'} = 0;
3303                         }
3304                 }
3305                 push @projects, $pr;
3306         }
3308         $order ||= $default_projects_order;
3309         $from = 0 unless defined $from;
3310         $to = $#projects if (!defined $to || $#projects < $to);
3312         print "<table class=\"project_list\">\n";
3313         unless ($no_header) {
3314                 print "<tr>\n";
3315                 if ($check_forks) {
3316                         print "<th></th>\n";
3317                 }
3318                 if ($order eq "project") {
3319                         @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
3320                         print "<th>Project</th>\n";
3321                 } else {
3322                         print "<th>" .
3323                               $cgi->a({-href => href(project=>undef, order=>'project'),
3324                                        -class => "header"}, "Project") .
3325                               "</th>\n";
3326                 }
3327                 if ($order eq "descr") {
3328                         @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
3329                         print "<th>Description</th>\n";
3330                 } else {
3331                         print "<th>" .
3332                               $cgi->a({-href => href(project=>undef, order=>'descr'),
3333                                        -class => "header"}, "Description") .
3334                               "</th>\n";
3335                 }
3336                 if ($order eq "owner") {
3337                         @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
3338                         print "<th>Owner</th>\n";
3339                 } else {
3340                         print "<th>" .
3341                               $cgi->a({-href => href(project=>undef, order=>'owner'),
3342                                        -class => "header"}, "Owner") .
3343                               "</th>\n";
3344                 }
3345                 if ($order eq "age") {
3346                         @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
3347                         print "<th>Last Change</th>\n";
3348                 } else {
3349                         print "<th>" .
3350                               $cgi->a({-href => href(project=>undef, order=>'age'),
3351                                        -class => "header"}, "Last Change") .
3352                               "</th>\n";
3353                 }
3354                 print "<th></th>\n" .
3355                       "</tr>\n";
3356         }
3357         my $alternate = 1;
3358         for (my $i = $from; $i <= $to; $i++) {
3359                 my $pr = $projects[$i];
3360                 if ($alternate) {
3361                         print "<tr class=\"dark\">\n";
3362                 } else {
3363                         print "<tr class=\"light\">\n";
3364                 }
3365                 $alternate ^= 1;
3366                 if ($check_forks) {
3367                         print "<td>";
3368                         if ($pr->{'forks'}) {
3369                                 print "<!-- $pr->{'forks'} -->\n";
3370                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3371                         }
3372                         print "</td>\n";
3373                 }
3374                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3375                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3376                       "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3377                                         -class => "list", -title => $pr->{'descr_long'}},
3378                                         esc_html($pr->{'descr'})) . "</td>\n" .
3379                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
3380                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3381                       (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3382                       "<td class=\"link\">" .
3383                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
3384                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3385                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3386                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3387                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3388                       "</td>\n" .
3389                       "</tr>\n";
3390         }
3391         if (defined $extra) {
3392                 print "<tr>\n";
3393                 if ($check_forks) {
3394                         print "<td></td>\n";
3395                 }
3396                 print "<td colspan=\"5\">$extra</td>\n" .
3397                       "</tr>\n";
3398         }
3399         print "</table>\n";
3402 sub git_shortlog_body {
3403         # uses global variable $project
3404         my ($commitlist, $from, $to, $refs, $extra) = @_;
3406         $from = 0 unless defined $from;
3407         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3409         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
3410         my $alternate = 1;
3411         for (my $i = $from; $i <= $to; $i++) {
3412                 my %co = %{$commitlist->[$i]};
3413                 my $commit = $co{'id'};
3414                 my $ref = format_ref_marker($refs, $commit);
3415                 if ($alternate) {
3416                         print "<tr class=\"dark\">\n";
3417                 } else {
3418                         print "<tr class=\"light\">\n";
3419                 }
3420                 $alternate ^= 1;
3421                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3422                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3423                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
3424                       "<td>";
3425                 print format_subject_html($co{'title'}, $co{'title_short'},
3426                                           href(action=>"commit", hash=>$commit), $ref);
3427                 print "</td>\n" .
3428                       "<td class=\"link\">" .
3429                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3430                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3431                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3432                 my $snapshot_links = format_snapshot_links($commit);
3433                 if (defined $snapshot_links) {
3434                         print " | " . $snapshot_links;
3435                 }
3436                 print "</td>\n" .
3437                       "</tr>\n";
3438         }
3439         if (defined $extra) {
3440                 print "<tr>\n" .
3441                       "<td colspan=\"4\">$extra</td>\n" .
3442                       "</tr>\n";
3443         }
3444         print "</table>\n";
3447 sub git_history_body {
3448         # Warning: assumes constant type (blob or tree) during history
3449         my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3451         $from = 0 unless defined $from;
3452         $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3454         print "<table class=\"history\" cellspacing=\"0\">\n";
3455         my $alternate = 1;
3456         for (my $i = $from; $i <= $to; $i++) {
3457                 my %co = %{$commitlist->[$i]};
3458                 if (!%co) {
3459                         next;
3460                 }
3461                 my $commit = $co{'id'};
3463                 my $ref = format_ref_marker($refs, $commit);
3465                 if ($alternate) {
3466                         print "<tr class=\"dark\">\n";
3467                 } else {
3468                         print "<tr class=\"light\">\n";
3469                 }
3470                 $alternate ^= 1;
3471                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3472                       # shortlog uses      chop_str($co{'author_name'}, 10)
3473                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
3474                       "<td>";
3475                 # originally git_history used chop_str($co{'title'}, 50)
3476                 print format_subject_html($co{'title'}, $co{'title_short'},
3477                                           href(action=>"commit", hash=>$commit), $ref);
3478                 print "</td>\n" .
3479                       "<td class=\"link\">" .
3480                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3481                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3483                 if ($ftype eq 'blob') {
3484                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3485                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
3486                         if (defined $blob_current && defined $blob_parent &&
3487                                         $blob_current ne $blob_parent) {
3488                                 print " | " .
3489                                         $cgi->a({-href => href(action=>"blobdiff",
3490                                                                hash=>$blob_current, hash_parent=>$blob_parent,
3491                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
3492                                                                file_name=>$file_name)},
3493                                                 "diff to current");
3494                         }
3495                 }
3496                 print "</td>\n" .
3497                       "</tr>\n";
3498         }
3499         if (defined $extra) {
3500                 print "<tr>\n" .
3501                       "<td colspan=\"4\">$extra</td>\n" .
3502                       "</tr>\n";
3503         }
3504         print "</table>\n";
3507 sub git_tags_body {
3508         # uses global variable $project
3509         my ($taglist, $from, $to, $extra) = @_;
3510         $from = 0 unless defined $from;
3511         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3513         print "<table class=\"tags\" cellspacing=\"0\">\n";
3514         my $alternate = 1;
3515         for (my $i = $from; $i <= $to; $i++) {
3516                 my $entry = $taglist->[$i];
3517                 my %tag = %$entry;
3518                 my $comment = $tag{'subject'};
3519                 my $comment_short;
3520                 if (defined $comment) {
3521                         $comment_short = chop_str($comment, 30, 5);
3522                 }
3523                 if ($alternate) {
3524                         print "<tr class=\"dark\">\n";
3525                 } else {
3526                         print "<tr class=\"light\">\n";
3527                 }
3528                 $alternate ^= 1;
3529                 if (defined $tag{'age'}) {
3530                         print "<td><i>$tag{'age'}</i></td>\n";
3531                 } else {
3532                         print "<td></td>\n";
3533                 }
3534                 print "<td>" .
3535                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3536                                -class => "list name"}, esc_html($tag{'name'})) .
3537                       "</td>\n" .
3538                       "<td>";
3539                 if (defined $comment) {
3540                         print format_subject_html($comment, $comment_short,
3541                                                   href(action=>"tag", hash=>$tag{'id'}));
3542                 }
3543                 print "</td>\n" .
3544                       "<td class=\"selflink\">";
3545                 if ($tag{'type'} eq "tag") {
3546                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3547                 } else {
3548                         print "&nbsp;";
3549                 }
3550                 print "</td>\n" .
3551                       "<td class=\"link\">" . " | " .
3552                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3553                 if ($tag{'reftype'} eq "commit") {
3554                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
3555                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
3556                 } elsif ($tag{'reftype'} eq "blob") {
3557                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3558                 }
3559                 print "</td>\n" .
3560                       "</tr>";
3561         }
3562         if (defined $extra) {
3563                 print "<tr>\n" .
3564                       "<td colspan=\"5\">$extra</td>\n" .
3565                       "</tr>\n";
3566         }
3567         print "</table>\n";
3570 sub git_heads_body {
3571         # uses global variable $project
3572         my ($headlist, $head, $from, $to, $extra) = @_;
3573         $from = 0 unless defined $from;
3574         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3576         print "<table class=\"heads\" cellspacing=\"0\">\n";
3577         my $alternate = 1;
3578         for (my $i = $from; $i <= $to; $i++) {
3579                 my $entry = $headlist->[$i];
3580                 my %ref = %$entry;
3581                 my $curr = $ref{'id'} eq $head;
3582                 if ($alternate) {
3583                         print "<tr class=\"dark\">\n";
3584                 } else {
3585                         print "<tr class=\"light\">\n";
3586                 }
3587                 $alternate ^= 1;
3588                 print "<td><i>$ref{'age'}</i></td>\n" .
3589                       ($curr ? "<td class=\"current_head\">" : "<td>") .
3590                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
3591                                -class => "list name"},esc_html($ref{'name'})) .
3592                       "</td>\n" .
3593                       "<td class=\"link\">" .
3594                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
3595                       $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
3596                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
3597                       "</td>\n" .
3598                       "</tr>";
3599         }
3600         if (defined $extra) {
3601                 print "<tr>\n" .
3602                       "<td colspan=\"3\">$extra</td>\n" .
3603                       "</tr>\n";
3604         }
3605         print "</table>\n";
3608 sub git_search_grep_body {
3609         my ($commitlist, $from, $to, $extra) = @_;
3610         $from = 0 unless defined $from;
3611         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3613         print "<table class=\"grep\" cellspacing=\"0\">\n";
3614         my $alternate = 1;
3615         for (my $i = $from; $i <= $to; $i++) {
3616                 my %co = %{$commitlist->[$i]};
3617                 if (!%co) {
3618                         next;
3619                 }
3620                 my $commit = $co{'id'};
3621                 if ($alternate) {
3622                         print "<tr class=\"dark\">\n";
3623                 } else {
3624                         print "<tr class=\"light\">\n";
3625                 }
3626                 $alternate ^= 1;
3627                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3628                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3629                       "<td>" .
3630                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3631                                esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3632                 my $comment = $co{'comment'};
3633                 foreach my $line (@$comment) {
3634                         if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
3635                                 my $lead = esc_html($1) || "";
3636                                 $lead = chop_str($lead, 30, 10);
3637                                 my $match = esc_html($2) || "";
3638                                 my $trail = esc_html($3) || "";
3639                                 $trail = chop_str($trail, 30, 10);
3640                                 my $text = "$lead<span class=\"match\">$match</span>$trail";
3641                                 print chop_str($text, 80, 5) . "<br/>\n";
3642                         }
3643                 }
3644                 print "</td>\n" .
3645                       "<td class=\"link\">" .
3646                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3647                       " | " .
3648                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3649                 print "</td>\n" .
3650                       "</tr>\n";
3651         }
3652         if (defined $extra) {
3653                 print "<tr>\n" .
3654                       "<td colspan=\"3\">$extra</td>\n" .
3655                       "</tr>\n";
3656         }
3657         print "</table>\n";
3660 ## ======================================================================
3661 ## ======================================================================
3662 ## actions
3664 sub git_project_list {
3665         my $order = $cgi->param('o');
3666         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3667                 die_error(undef, "Unknown order parameter");
3668         }
3670         my @list = git_get_projects_list();
3671         if (!@list) {
3672                 die_error(undef, "No projects found");
3673         }
3675         git_header_html();
3676         if (-f $home_text) {
3677                 print "<div class=\"index_include\">\n";
3678                 open (my $fd, $home_text);
3679                 print <$fd>;
3680                 close $fd;
3681                 print "</div>\n";
3682         }
3683         git_project_list_body(\@list, $order);
3684         git_footer_html();
3687 sub git_forks {
3688         my $order = $cgi->param('o');
3689         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3690                 die_error(undef, "Unknown order parameter");
3691         }
3693         my @list = git_get_projects_list($project);
3694         if (!@list) {
3695                 die_error(undef, "No forks found");
3696         }
3698         git_header_html();
3699         git_print_page_nav('','');
3700         git_print_header_div('summary', "$project forks");
3701         git_project_list_body(\@list, $order);
3702         git_footer_html();
3705 sub git_project_index {
3706         my @projects = git_get_projects_list($project);
3708         print $cgi->header(
3709                 -type => 'text/plain',
3710                 -charset => 'utf-8',
3711                 -content_disposition => 'inline; filename="index.aux"');
3713         foreach my $pr (@projects) {
3714                 if (!exists $pr->{'owner'}) {
3715                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
3716                 }
3718                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3719                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3720                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3721                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3722                 $path  =~ s/ /\+/g;
3723                 $owner =~ s/ /\+/g;
3725                 print "$path $owner\n";
3726         }
3729 sub git_summary {
3730         my $descr = git_get_project_description($project) || "none";
3731         my %co = parse_commit("HEAD");
3732         my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
3733         my $head = $co{'id'};
3735         my $owner = git_get_project_owner($project);
3737         my $refs = git_get_references();
3738         # These get_*_list functions return one more to allow us to see if
3739         # there are more ...
3740         my @taglist  = git_get_tags_list(16);
3741         my @headlist = git_get_heads_list(16);
3742         my @forklist;
3743         my ($check_forks) = gitweb_check_feature('forks');
3745         if ($check_forks) {
3746                 @forklist = git_get_projects_list($project);
3747         }
3749         git_header_html();
3750         git_print_page_nav('summary','', $head);
3752         print "<div class=\"title\">&nbsp;</div>\n";
3753         print "<table cellspacing=\"0\">\n" .
3754               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3755               "<tr><td>owner</td><td>$owner</td></tr>\n";
3756         if (defined $cd{'rfc2822'}) {
3757                 print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3758         }
3760         # use per project git URL list in $projectroot/$project/cloneurl
3761         # or make project git URL from git base URL and project name
3762         my $url_tag = "URL";
3763         my @url_list = git_get_project_url_list($project);
3764         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3765         foreach my $git_url (@url_list) {
3766                 next unless $git_url;
3767                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3768                 $url_tag = "";
3769         }
3770         print "</table>\n";
3772         if (-s "$projectroot/$project/README.html") {
3773                 if (open my $fd, "$projectroot/$project/README.html") {
3774                         print "<div class=\"title\">readme</div>\n";
3775                         print $_ while (<$fd>);
3776                         close $fd;
3777                 }
3778         }
3780         # we need to request one more than 16 (0..15) to check if
3781         # those 16 are all
3782         my @commitlist = $head ? parse_commits($head, 17) : ();
3783         if (@commitlist) {
3784                 git_print_header_div('shortlog');
3785                 git_shortlog_body(\@commitlist, 0, 15, $refs,
3786                                   $#commitlist <=  15 ? undef :
3787                                   $cgi->a({-href => href(action=>"shortlog")}, "..."));
3788         }
3790         if (@taglist) {
3791                 git_print_header_div('tags');
3792                 git_tags_body(\@taglist, 0, 15,
3793                               $#taglist <=  15 ? undef :
3794                               $cgi->a({-href => href(action=>"tags")}, "..."));
3795         }
3797         if (@headlist) {
3798                 git_print_header_div('heads');
3799                 git_heads_body(\@headlist, $head, 0, 15,
3800                                $#headlist <= 15 ? undef :
3801                                $cgi->a({-href => href(action=>"heads")}, "..."));
3802         }
3804         if (@forklist) {
3805                 git_print_header_div('forks');
3806                 git_project_list_body(\@forklist, undef, 0, 15,
3807                                       $#forklist <= 15 ? undef :
3808                                       $cgi->a({-href => href(action=>"forks")}, "..."),
3809                                       'noheader');
3810         }
3812         git_footer_html();
3815 sub git_tag {
3816         my $head = git_get_head_hash($project);
3817         git_header_html();
3818         git_print_page_nav('','', $head,undef,$head);
3819         my %tag = parse_tag($hash);
3821         if (! %tag) {
3822                 die_error(undef, "Unknown tag object");
3823         }
3825         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3826         print "<div class=\"title_text\">\n" .
3827               "<table cellspacing=\"0\">\n" .
3828               "<tr>\n" .
3829               "<td>object</td>\n" .
3830               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3831                                $tag{'object'}) . "</td>\n" .
3832               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3833                                               $tag{'type'}) . "</td>\n" .
3834               "</tr>\n";
3835         if (defined($tag{'author'})) {
3836                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3837                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3838                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
3839                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3840                         "</td></tr>\n";
3841         }
3842         print "</table>\n\n" .
3843               "</div>\n";
3844         print "<div class=\"page_body\">";
3845         my $comment = $tag{'comment'};
3846         foreach my $line (@$comment) {
3847                 chomp $line;
3848                 print esc_html($line, -nbsp=>1) . "<br/>\n";
3849         }
3850         print "</div>\n";
3851         git_footer_html();
3854 sub git_blame2 {
3855         my $fd;
3856         my $ftype;
3858         my ($have_blame) = gitweb_check_feature('blame');
3859         if (!$have_blame) {
3860                 die_error('403 Permission denied', "Permission denied");
3861         }
3862         die_error('404 Not Found', "File name not defined") if (!$file_name);
3863         $hash_base ||= git_get_head_hash($project);
3864         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3865         my %co = parse_commit($hash_base)
3866                 or die_error(undef, "Reading commit failed");
3867         if (!defined $hash) {
3868                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3869                         or die_error(undef, "Error looking up file");
3870         }
3871         $ftype = git_get_type($hash);
3872         if ($ftype !~ "blob") {
3873                 die_error('400 Bad Request', "Object is not a blob");
3874         }
3875         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3876               $file_name, $hash_base)
3877                 or die_error(undef, "Open git-blame failed");
3878         git_header_html();
3879         my $formats_nav =
3880                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3881                         "blob") .
3882                 " | " .
3883                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3884                         "history") .
3885                 " | " .
3886                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3887                         "HEAD");
3888         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3889         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3890         git_print_page_path($file_name, $ftype, $hash_base);
3891         my @rev_color = (qw(light2 dark2));
3892         my $num_colors = scalar(@rev_color);
3893         my $current_color = 0;
3894         my $last_rev;
3895         print <<HTML;
3896 <div class="page_body">
3897 <table class="blame">
3898 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3899 HTML
3900         my %metainfo = ();
3901         while (1) {
3902                 $_ = <$fd>;
3903                 last unless defined $_;
3904                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
3905                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3906                 if (!exists $metainfo{$full_rev}) {
3907                         $metainfo{$full_rev} = {};
3908                 }
3909                 my $meta = $metainfo{$full_rev};
3910                 while (<$fd>) {
3911                         last if (s/^\t//);
3912                         if (/^(\S+) (.*)$/) {
3913                                 $meta->{$1} = $2;
3914                         }
3915                 }
3916                 my $data = $_;
3917                 chomp $data;
3918                 my $rev = substr($full_rev, 0, 8);
3919                 my $author = $meta->{'author'};
3920                 my %date = parse_date($meta->{'author-time'},
3921                                       $meta->{'author-tz'});
3922                 my $date = $date{'iso-tz'};
3923                 if ($group_size) {
3924                         $current_color = ++$current_color % $num_colors;
3925                 }
3926                 print "<tr class=\"$rev_color[$current_color]\">\n";
3927                 if ($group_size) {
3928                         print "<td class=\"sha1\"";
3929                         print " title=\"". esc_html($author) . ", $date\"";
3930                         print " rowspan=\"$group_size\"" if ($group_size > 1);
3931                         print ">";
3932                         print $cgi->a({-href => href(action=>"commit",
3933                                                      hash=>$full_rev,
3934                                                      file_name=>$file_name)},
3935                                       esc_html($rev));
3936                         print "</td>\n";
3937                 }
3938                 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
3939                         or die_error(undef, "Open git-rev-parse failed");
3940                 my $parent_commit = <$dd>;
3941                 close $dd;
3942                 chomp($parent_commit);
3943                 my $blamed = href(action => 'blame',
3944                                   file_name => $meta->{'filename'},
3945                                   hash_base => $parent_commit);
3946                 print "<td class=\"linenr\">";
3947                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
3948                                 -id => "l$lineno",
3949                                 -class => "linenr" },
3950                               esc_html($lineno));
3951                 print "</td>";
3952                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3953                 print "</tr>\n";
3954         }
3955         print "</table>\n";
3956         print "</div>";
3957         close $fd
3958                 or print "Reading blob failed\n";
3959         git_footer_html();
3962 sub git_blame {
3963         my $fd;
3965         my ($have_blame) = gitweb_check_feature('blame');
3966         if (!$have_blame) {
3967                 die_error('403 Permission denied', "Permission denied");
3968         }
3969         die_error('404 Not Found', "File name not defined") if (!$file_name);
3970         $hash_base ||= git_get_head_hash($project);
3971         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3972         my %co = parse_commit($hash_base)
3973                 or die_error(undef, "Reading commit failed");
3974         if (!defined $hash) {
3975                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3976                         or die_error(undef, "Error lookup file");
3977         }
3978         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3979                 or die_error(undef, "Open git-annotate failed");
3980         git_header_html();
3981         my $formats_nav =
3982                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3983                         "blob") .
3984                 " | " .
3985                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3986                         "history") .
3987                 " | " .
3988                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3989                         "HEAD");
3990         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3991         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3992         git_print_page_path($file_name, 'blob', $hash_base);
3993         print "<div class=\"page_body\">\n";
3994         print <<HTML;
3995 <table class="blame">
3996   <tr>
3997     <th>Commit</th>
3998     <th>Age</th>
3999     <th>Author</th>
4000     <th>Line</th>
4001     <th>Data</th>
4002   </tr>
4003 HTML
4004         my @line_class = (qw(light dark));
4005         my $line_class_len = scalar (@line_class);
4006         my $line_class_num = $#line_class;
4007         while (my $line = <$fd>) {
4008                 my $long_rev;
4009                 my $short_rev;
4010                 my $author;
4011                 my $time;
4012                 my $lineno;
4013                 my $data;
4014                 my $age;
4015                 my $age_str;
4016                 my $age_class;
4018                 chomp $line;
4019                 $line_class_num = ($line_class_num + 1) % $line_class_len;
4021                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
4022                         $long_rev = $1;
4023                         $author   = $2;
4024                         $time     = $3;
4025                         $lineno   = $4;
4026                         $data     = $5;
4027                 } else {
4028                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
4029                         next;
4030                 }
4031                 $short_rev  = substr ($long_rev, 0, 8);
4032                 $age        = time () - $time;
4033                 $age_str    = age_string ($age);
4034                 $age_str    =~ s/ /&nbsp;/g;
4035                 $age_class  = age_class($age);
4036                 $author     = esc_html ($author);
4037                 $author     =~ s/ /&nbsp;/g;
4039                 $data = untabify($data);
4040                 $data = esc_html ($data);
4042                 print <<HTML;
4043   <tr class="$line_class[$line_class_num]">
4044     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
4045     <td class="$age_class">$age_str</td>
4046     <td>$author</td>
4047     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
4048     <td class="pre">$data</td>
4049   </tr>
4050 HTML
4051         } # while (my $line = <$fd>)
4052         print "</table>\n\n";
4053         close $fd
4054                 or print "Reading blob failed.\n";
4055         print "</div>";
4056         git_footer_html();
4059 sub git_tags {
4060         my $head = git_get_head_hash($project);
4061         git_header_html();
4062         git_print_page_nav('','', $head,undef,$head);
4063         git_print_header_div('summary', $project);
4065         my @tagslist = git_get_tags_list();
4066         if (@tagslist) {
4067                 git_tags_body(\@tagslist);
4068         }
4069         git_footer_html();
4072 sub git_heads {
4073         my $head = git_get_head_hash($project);
4074         git_header_html();
4075         git_print_page_nav('','', $head,undef,$head);
4076         git_print_header_div('summary', $project);
4078         my @headslist = git_get_heads_list();
4079         if (@headslist) {
4080                 git_heads_body(\@headslist, $head);
4081         }
4082         git_footer_html();
4085 sub git_blob_plain {
4086         my $expires;
4088         if (!defined $hash) {
4089                 if (defined $file_name) {
4090                         my $base = $hash_base || git_get_head_hash($project);
4091                         $hash = git_get_hash_by_path($base, $file_name, "blob")
4092                                 or die_error(undef, "Error lookup file");
4093                 } else {
4094                         die_error(undef, "No file name defined");
4095                 }
4096         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4097                 # blobs defined by non-textual hash id's can be cached
4098                 $expires = "+1d";
4099         }
4101         my $type = shift;
4102         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4103                 or die_error(undef, "Couldn't cat $file_name, $hash");
4105         $type ||= blob_mimetype($fd, $file_name);
4107         # save as filename, even when no $file_name is given
4108         my $save_as = "$hash";
4109         if (defined $file_name) {
4110                 $save_as = $file_name;
4111         } elsif ($type =~ m/^text\//) {
4112                 $save_as .= '.txt';
4113         }
4115         print $cgi->header(
4116                 -type => "$type",
4117                 -expires=>$expires,
4118                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
4119         undef $/;
4120         binmode STDOUT, ':raw';
4121         print <$fd>;
4122         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4123         $/ = "\n";
4124         close $fd;
4127 sub git_blob {
4128         my $expires;
4130         if (!defined $hash) {
4131                 if (defined $file_name) {
4132                         my $base = $hash_base || git_get_head_hash($project);
4133                         $hash = git_get_hash_by_path($base, $file_name, "blob")
4134                                 or die_error(undef, "Error lookup file");
4135                 } else {
4136                         die_error(undef, "No file name defined");
4137                 }
4138         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4139                 # blobs defined by non-textual hash id's can be cached
4140                 $expires = "+1d";
4141         }
4143         my ($have_blame) = gitweb_check_feature('blame');
4144         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4145                 or die_error(undef, "Couldn't cat $file_name, $hash");
4146         my $mimetype = blob_mimetype($fd, $file_name);
4147         if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
4148                 close $fd;
4149                 return git_blob_plain($mimetype);
4150         }
4151         # we can have blame only for text/* mimetype
4152         $have_blame &&= ($mimetype =~ m!^text/!);
4154         git_header_html(undef, $expires);
4155         my $formats_nav = '';
4156         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4157                 if (defined $file_name) {
4158                         if ($have_blame) {
4159                                 $formats_nav .=
4160                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
4161                                                                hash=>$hash, file_name=>$file_name)},
4162                                                 "blame") .
4163                                         " | ";
4164                         }
4165                         $formats_nav .=
4166                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4167                                                        hash=>$hash, file_name=>$file_name)},
4168                                         "history") .
4169                                 " | " .
4170                                 $cgi->a({-href => href(action=>"blob_plain",
4171                                                        hash=>$hash, file_name=>$file_name)},
4172                                         "raw") .
4173                                 " | " .
4174                                 $cgi->a({-href => href(action=>"blob",
4175                                                        hash_base=>"HEAD", file_name=>$file_name)},
4176                                         "HEAD");
4177                 } else {
4178                         $formats_nav .=
4179                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
4180                 }
4181                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4182                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4183         } else {
4184                 print "<div class=\"page_nav\">\n" .
4185                       "<br/><br/></div>\n" .
4186                       "<div class=\"title\">$hash</div>\n";
4187         }
4188         git_print_page_path($file_name, "blob", $hash_base);
4189         print "<div class=\"page_body\">\n";
4190         if ($mimetype =~ m!^text/!) {
4191                 my $nr;
4192                 while (my $line = <$fd>) {
4193                         chomp $line;
4194                         $nr++;
4195                         $line = untabify($line);
4196                         printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4197                                $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4198                 }
4199         } elsif ($mimetype =~ m!^image/!) {
4200                 print qq!<img type="$mimetype"!;
4201                 if ($file_name) {
4202                         print qq! alt="$file_name" title="$file_name"!;
4203                 }
4204                 print qq! src="! .
4205                       href(action=>"blob_plain", hash=>$hash,
4206                            hash_base=>$hash_base, file_name=>$file_name) .
4207                       qq!" />\n!;
4208         }
4209         close $fd
4210                 or print "Reading blob failed.\n";
4211         print "</div>";
4212         git_footer_html();
4215 sub git_tree {
4216         if (!defined $hash_base) {
4217                 $hash_base = "HEAD";
4218         }
4219         if (!defined $hash) {
4220                 if (defined $file_name) {
4221                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4222                 } else {
4223                         $hash = $hash_base;
4224                 }
4225         }
4226         $/ = "\0";
4227         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4228                 or die_error(undef, "Open git-ls-tree failed");
4229         my @entries = map { chomp; $_ } <$fd>;
4230         close $fd or die_error(undef, "Reading tree failed");
4231         $/ = "\n";
4233         my $refs = git_get_references();
4234         my $ref = format_ref_marker($refs, $hash_base);
4235         git_header_html();
4236         my $basedir = '';
4237         my ($have_blame) = gitweb_check_feature('blame');
4238         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4239                 my @views_nav = ();
4240                 if (defined $file_name) {
4241                         push @views_nav,
4242                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4243                                                        hash=>$hash, file_name=>$file_name)},
4244                                         "history"),
4245                                 $cgi->a({-href => href(action=>"tree",
4246                                                        hash_base=>"HEAD", file_name=>$file_name)},
4247                                         "HEAD"),
4248                 }
4249                 my $snapshot_links = format_snapshot_links($hash);
4250                 if (defined $snapshot_links) {
4251                         # FIXME: Should be available when we have no hash base as well.
4252                         push @views_nav, $snapshot_links;
4253                 }
4254                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4255                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4256         } else {
4257                 undef $hash_base;
4258                 print "<div class=\"page_nav\">\n";
4259                 print "<br/><br/></div>\n";
4260                 print "<div class=\"title\">$hash</div>\n";
4261         }
4262         if (defined $file_name) {
4263                 $basedir = $file_name;
4264                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4265                         $basedir .= '/';
4266                 }
4267         }
4268         git_print_page_path($file_name, 'tree', $hash_base);
4269         print "<div class=\"page_body\">\n";
4270         print "<table cellspacing=\"0\">\n";
4271         my $alternate = 1;
4272         # '..' (top directory) link if possible
4273         if (defined $hash_base &&
4274             defined $file_name && $file_name =~ m![^/]+$!) {
4275                 if ($alternate) {
4276                         print "<tr class=\"dark\">\n";
4277                 } else {
4278                         print "<tr class=\"light\">\n";
4279                 }
4280                 $alternate ^= 1;
4282                 my $up = $file_name;
4283                 $up =~ s!/?[^/]+$!!;
4284                 undef $up unless $up;
4285                 # based on git_print_tree_entry
4286                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4287                 print '<td class="list">';
4288                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4289                                              file_name=>$up)},
4290                               "..");
4291                 print "</td>\n";
4292                 print "<td class=\"link\"></td>\n";
4294                 print "</tr>\n";
4295         }
4296         foreach my $line (@entries) {
4297                 my %t = parse_ls_tree_line($line, -z => 1);
4299                 if ($alternate) {
4300                         print "<tr class=\"dark\">\n";
4301                 } else {
4302                         print "<tr class=\"light\">\n";
4303                 }
4304                 $alternate ^= 1;
4306                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4308                 print "</tr>\n";
4309         }
4310         print "</table>\n" .
4311               "</div>";
4312         git_footer_html();
4315 sub git_snapshot {
4316         my @supported_fmts = gitweb_check_feature('snapshot');
4317         @supported_fmts = filter_snapshot_fmts(@supported_fmts);
4319         my $format = $cgi->param('sf');
4320         unless ($format =~ m/[a-z0-9]+/
4321                 && exists($known_snapshot_formats{$format})
4322                 && grep($_ eq $format, @supported_fmts)) {
4323                 die_error(undef, "Unsupported snapshot format");
4324         }
4326         if (!defined $hash) {
4327                 $hash = git_get_head_hash($project);
4328         }
4330         my $git_command = git_cmd_str();
4331         my $name = $project;
4332         $name =~ s,([^/])/*\.git$,$1,;
4333         $name = basename($name);
4334         my $filename = to_utf8($name);
4335         $name =~ s/\047/\047\\\047\047/g;
4336         my $cmd;
4337         $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4338         $cmd = "$git_command archive " .
4339                 "--format=$known_snapshot_formats{$format}{'format'}" .
4340                 "--prefix=\'$name\'/ $hash";
4341         if (exists $known_snapshot_formats{$format}{'compressor'}) {
4342                 $cmd .= ' | ' . join ' ', @{$known_snapshot_formats{$format}{'compressor'}};
4343         }
4345         print $cgi->header(
4346                 -type => $known_snapshot_formats{$format}{'type'},
4347                 -content_disposition => 'inline; filename="' . "$filename" . '"',
4348                 -status => '200 OK');
4350         open my $fd, "-|", $cmd
4351                 or die_error(undef, "Execute git-archive failed");
4352         binmode STDOUT, ':raw';
4353         print <$fd>;
4354         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4355         close $fd;
4358 sub git_log {
4359         my $head = git_get_head_hash($project);
4360         if (!defined $hash) {
4361                 $hash = $head;
4362         }
4363         if (!defined $page) {
4364                 $page = 0;
4365         }
4366         my $refs = git_get_references();
4368         my @commitlist = parse_commits($hash, 101, (100 * $page));
4370         my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
4372         git_header_html();
4373         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4375         if (!@commitlist) {
4376                 my %co = parse_commit($hash);
4378                 git_print_header_div('summary', $project);
4379                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4380         }
4381         my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4382         for (my $i = 0; $i <= $to; $i++) {
4383                 my %co = %{$commitlist[$i]};
4384                 next if !%co;
4385                 my $commit = $co{'id'};
4386                 my $ref = format_ref_marker($refs, $commit);
4387                 my %ad = parse_date($co{'author_epoch'});
4388                 git_print_header_div('commit',
4389                                "<span class=\"age\">$co{'age_string'}</span>" .
4390                                esc_html($co{'title'}) . $ref,
4391                                $commit);
4392                 print "<div class=\"title_text\">\n" .
4393                       "<div class=\"log_link\">\n" .
4394                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4395                       " | " .
4396                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4397                       " | " .
4398                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4399                       "<br/>\n" .
4400                       "</div>\n" .
4401                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
4402                       "</div>\n";
4404                 print "<div class=\"log_body\">\n";
4405                 git_print_log($co{'comment'}, -final_empty_line=> 1);
4406                 print "</div>\n";
4407         }
4408         if ($#commitlist >= 100) {
4409                 print "<div class=\"page_nav\">\n";
4410                 print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
4411                                -accesskey => "n", -title => "Alt-n"}, "next");
4412                 print "</div>\n";
4413         }
4414         git_footer_html();
4417 sub git_commit {
4418         $hash ||= $hash_base || "HEAD";
4419         my %co = parse_commit($hash);
4420         if (!%co) {
4421                 die_error(undef, "Unknown commit object");
4422         }
4423         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4424         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4426         my $parent  = $co{'parent'};
4427         my $parents = $co{'parents'}; # listref
4429         # we need to prepare $formats_nav before any parameter munging
4430         my $formats_nav;
4431         if (!defined $parent) {
4432                 # --root commitdiff
4433                 $formats_nav .= '(initial)';
4434         } elsif (@$parents == 1) {
4435                 # single parent commit
4436                 $formats_nav .=
4437                         '(parent: ' .
4438                         $cgi->a({-href => href(action=>"commit",
4439                                                hash=>$parent)},
4440                                 esc_html(substr($parent, 0, 7))) .
4441                         ')';
4442         } else {
4443                 # merge commit
4444                 $formats_nav .=
4445                         '(merge: ' .
4446                         join(' ', map {
4447                                 $cgi->a({-href => href(action=>"commit",
4448                                                        hash=>$_)},
4449                                         esc_html(substr($_, 0, 7)));
4450                         } @$parents ) .
4451                         ')';
4452         }
4454         if (!defined $parent) {
4455                 $parent = "--root";
4456         }
4457         my @difftree;
4458         open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4459                 @diff_opts,
4460                 (@$parents <= 1 ? $parent : '-c'),
4461                 $hash, "--"
4462                 or die_error(undef, "Open git-diff-tree failed");
4463         @difftree = map { chomp; $_ } <$fd>;
4464         close $fd or die_error(undef, "Reading git-diff-tree failed");
4466         # non-textual hash id's can be cached
4467         my $expires;
4468         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4469                 $expires = "+1d";
4470         }
4471         my $refs = git_get_references();
4472         my $ref = format_ref_marker($refs, $co{'id'});
4474         git_header_html(undef, $expires);
4475         git_print_page_nav('commit', '',
4476                            $hash, $co{'tree'}, $hash,
4477                            $formats_nav);
4479         if (defined $co{'parent'}) {
4480                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4481         } else {
4482                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4483         }
4484         print "<div class=\"title_text\">\n" .
4485               "<table cellspacing=\"0\">\n";
4486         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4487               "<tr>" .
4488               "<td></td><td> $ad{'rfc2822'}";
4489         if ($ad{'hour_local'} < 6) {
4490                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4491                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4492         } else {
4493                 printf(" (%02d:%02d %s)",
4494                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4495         }
4496         print "</td>" .
4497               "</tr>\n";
4498         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4499         print "<tr><td></td><td> $cd{'rfc2822'}" .
4500               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4501               "</td></tr>\n";
4502         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4503         print "<tr>" .
4504               "<td>tree</td>" .
4505               "<td class=\"sha1\">" .
4506               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4507                        class => "list"}, $co{'tree'}) .
4508               "</td>" .
4509               "<td class=\"link\">" .
4510               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4511                       "tree");
4512         my $snapshot_links = format_snapshot_links($hash);
4513         if (defined $snapshot_links) {
4514                 print " | " . $snapshot_links;
4515         }
4516         print "</td>" .
4517               "</tr>\n";
4519         foreach my $par (@$parents) {
4520                 print "<tr>" .
4521                       "<td>parent</td>" .
4522                       "<td class=\"sha1\">" .
4523                       $cgi->a({-href => href(action=>"commit", hash=>$par),
4524                                class => "list"}, $par) .
4525                       "</td>" .
4526                       "<td class=\"link\">" .
4527                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4528                       " | " .
4529                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4530                       "</td>" .
4531                       "</tr>\n";
4532         }
4533         print "</table>".
4534               "</div>\n";
4536         print "<div class=\"page_body\">\n";
4537         git_print_log($co{'comment'});
4538         print "</div>\n";
4540         git_difftree_body(\@difftree, $hash, @$parents);
4542         git_footer_html();
4545 sub git_object {
4546         # object is defined by:
4547         # - hash or hash_base alone
4548         # - hash_base and file_name
4549         my $type;
4551         # - hash or hash_base alone
4552         if ($hash || ($hash_base && !defined $file_name)) {
4553                 my $object_id = $hash || $hash_base;
4555                 my $git_command = git_cmd_str();
4556                 open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
4557                         or die_error('404 Not Found', "Object does not exist");
4558                 $type = <$fd>;
4559                 chomp $type;
4560                 close $fd
4561                         or die_error('404 Not Found', "Object does not exist");
4563         # - hash_base and file_name
4564         } elsif ($hash_base && defined $file_name) {
4565                 $file_name =~ s,/+$,,;
4567                 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4568                         or die_error('404 Not Found', "Base object does not exist");
4570                 # here errors should not hapen
4571                 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4572                         or die_error(undef, "Open git-ls-tree failed");
4573                 my $line = <$fd>;
4574                 close $fd;
4576                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
4577                 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4578                         die_error('404 Not Found', "File or directory for given base does not exist");
4579                 }
4580                 $type = $2;
4581                 $hash = $3;
4582         } else {
4583                 die_error('404 Not Found', "Not enough information to find object");
4584         }
4586         print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4587                                           hash=>$hash, hash_base=>$hash_base,
4588                                           file_name=>$file_name),
4589                              -status => '302 Found');
4592 sub git_blobdiff {
4593         my $format = shift || 'html';
4595         my $fd;
4596         my @difftree;
4597         my %diffinfo;
4598         my $expires;
4600         # preparing $fd and %diffinfo for git_patchset_body
4601         # new style URI
4602         if (defined $hash_base && defined $hash_parent_base) {
4603                 if (defined $file_name) {
4604                         # read raw output
4605                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4606                                 $hash_parent_base, $hash_base,
4607                                 "--", (defined $file_parent ? $file_parent : ()), $file_name
4608                                 or die_error(undef, "Open git-diff-tree failed");
4609                         @difftree = map { chomp; $_ } <$fd>;
4610                         close $fd
4611                                 or die_error(undef, "Reading git-diff-tree failed");
4612                         @difftree
4613                                 or die_error('404 Not Found', "Blob diff not found");
4615                 } elsif (defined $hash &&
4616                          $hash =~ /[0-9a-fA-F]{40}/) {
4617                         # try to find filename from $hash
4619                         # read filtered raw output
4620                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4621                                 $hash_parent_base, $hash_base, "--"
4622                                 or die_error(undef, "Open git-diff-tree failed");
4623                         @difftree =
4624                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
4625                                 # $hash == to_id
4626                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4627                                 map { chomp; $_ } <$fd>;
4628                         close $fd
4629                                 or die_error(undef, "Reading git-diff-tree failed");
4630                         @difftree
4631                                 or die_error('404 Not Found', "Blob diff not found");
4633                 } else {
4634                         die_error('404 Not Found', "Missing one of the blob diff parameters");
4635                 }
4637                 if (@difftree > 1) {
4638                         die_error('404 Not Found', "Ambiguous blob diff specification");
4639                 }
4641                 %diffinfo = parse_difftree_raw_line($difftree[0]);
4642                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
4643                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
4645                 $hash_parent ||= $diffinfo{'from_id'};
4646                 $hash        ||= $diffinfo{'to_id'};
4648                 # non-textual hash id's can be cached
4649                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4650                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4651                         $expires = '+1d';
4652                 }
4654                 # open patch output
4655                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4656                         '-p', ($format eq 'html' ? "--full-index" : ()),
4657                         $hash_parent_base, $hash_base,
4658                         "--", (defined $file_parent ? $file_parent : ()), $file_name
4659                         or die_error(undef, "Open git-diff-tree failed");
4660         }
4662         # old/legacy style URI
4663         if (!%diffinfo && # if new style URI failed
4664             defined $hash && defined $hash_parent) {
4665                 # fake git-diff-tree raw output
4666                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4667                 $diffinfo{'from_id'} = $hash_parent;
4668                 $diffinfo{'to_id'}   = $hash;
4669                 if (defined $file_name) {
4670                         if (defined $file_parent) {
4671                                 $diffinfo{'status'} = '2';
4672                                 $diffinfo{'from_file'} = $file_parent;
4673                                 $diffinfo{'to_file'}   = $file_name;
4674                         } else { # assume not renamed
4675                                 $diffinfo{'status'} = '1';
4676                                 $diffinfo{'from_file'} = $file_name;
4677                                 $diffinfo{'to_file'}   = $file_name;
4678                         }
4679                 } else { # no filename given
4680                         $diffinfo{'status'} = '2';
4681                         $diffinfo{'from_file'} = $hash_parent;
4682                         $diffinfo{'to_file'}   = $hash;
4683                 }
4685                 # non-textual hash id's can be cached
4686                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4687                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4688                         $expires = '+1d';
4689                 }
4691                 # open patch output
4692                 open $fd, "-|", git_cmd(), "diff", @diff_opts,
4693                         '-p', ($format eq 'html' ? "--full-index" : ()),
4694                         $hash_parent, $hash, "--"
4695                         or die_error(undef, "Open git-diff failed");
4696         } else  {
4697                 die_error('404 Not Found', "Missing one of the blob diff parameters")
4698                         unless %diffinfo;
4699         }
4701         # header
4702         if ($format eq 'html') {
4703                 my $formats_nav =
4704                         $cgi->a({-href => href(action=>"blobdiff_plain",
4705                                                hash=>$hash, hash_parent=>$hash_parent,
4706                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
4707                                                file_name=>$file_name, file_parent=>$file_parent)},
4708                                 "raw");
4709                 git_header_html(undef, $expires);
4710                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4711                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4712                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4713                 } else {
4714                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4715                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4716                 }
4717                 if (defined $file_name) {
4718                         git_print_page_path($file_name, "blob", $hash_base);
4719                 } else {
4720                         print "<div class=\"page_path\"></div>\n";
4721                 }
4723         } elsif ($format eq 'plain') {
4724                 print $cgi->header(
4725                         -type => 'text/plain',
4726                         -charset => 'utf-8',
4727                         -expires => $expires,
4728                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4730                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4732         } else {
4733                 die_error(undef, "Unknown blobdiff format");
4734         }
4736         # patch
4737         if ($format eq 'html') {
4738                 print "<div class=\"page_body\">\n";
4740                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4741                 close $fd;
4743                 print "</div>\n"; # class="page_body"
4744                 git_footer_html();
4746         } else {
4747                 while (my $line = <$fd>) {
4748                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4749                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4751                         print $line;
4753                         last if $line =~ m!^\+\+\+!;
4754                 }
4755                 local $/ = undef;
4756                 print <$fd>;
4757                 close $fd;
4758         }
4761 sub git_blobdiff_plain {
4762         git_blobdiff('plain');
4765 sub git_commitdiff {
4766         my $format = shift || 'html';
4767         $hash ||= $hash_base || "HEAD";
4768         my %co = parse_commit($hash);
4769         if (!%co) {
4770                 die_error(undef, "Unknown commit object");
4771         }
4773         # choose format for commitdiff for merge
4774         if (! defined $hash_parent && @{$co{'parents'}} > 1) {
4775                 $hash_parent = '--cc';
4776         }
4777         # we need to prepare $formats_nav before almost any parameter munging
4778         my $formats_nav;
4779         if ($format eq 'html') {
4780                 $formats_nav =
4781                         $cgi->a({-href => href(action=>"commitdiff_plain",
4782                                                hash=>$hash, hash_parent=>$hash_parent)},
4783                                 "raw");
4785                 if (defined $hash_parent &&
4786                     $hash_parent ne '-c' && $hash_parent ne '--cc') {
4787                         # commitdiff with two commits given
4788                         my $hash_parent_short = $hash_parent;
4789                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4790                                 $hash_parent_short = substr($hash_parent, 0, 7);
4791                         }
4792                         $formats_nav .=
4793                                 ' (from';
4794                         for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
4795                                 if ($co{'parents'}[$i] eq $hash_parent) {
4796                                         $formats_nav .= ' parent ' . ($i+1);
4797                                         last;
4798                                 }
4799                         }
4800                         $formats_nav .= ': ' .
4801                                 $cgi->a({-href => href(action=>"commitdiff",
4802                                                        hash=>$hash_parent)},
4803                                         esc_html($hash_parent_short)) .
4804                                 ')';
4805                 } elsif (!$co{'parent'}) {
4806                         # --root commitdiff
4807                         $formats_nav .= ' (initial)';
4808                 } elsif (scalar @{$co{'parents'}} == 1) {
4809                         # single parent commit
4810                         $formats_nav .=
4811                                 ' (parent: ' .
4812                                 $cgi->a({-href => href(action=>"commitdiff",
4813                                                        hash=>$co{'parent'})},
4814                                         esc_html(substr($co{'parent'}, 0, 7))) .
4815                                 ')';
4816                 } else {
4817                         # merge commit
4818                         if ($hash_parent eq '--cc') {
4819                                 $formats_nav .= ' | ' .
4820                                         $cgi->a({-href => href(action=>"commitdiff",
4821                                                                hash=>$hash, hash_parent=>'-c')},
4822                                                 'combined');
4823                         } else { # $hash_parent eq '-c'
4824                                 $formats_nav .= ' | ' .
4825                                         $cgi->a({-href => href(action=>"commitdiff",
4826                                                                hash=>$hash, hash_parent=>'--cc')},
4827                                                 'compact');
4828                         }
4829                         $formats_nav .=
4830                                 ' (merge: ' .
4831                                 join(' ', map {
4832                                         $cgi->a({-href => href(action=>"commitdiff",
4833                                                                hash=>$_)},
4834                                                 esc_html(substr($_, 0, 7)));
4835                                 } @{$co{'parents'}} ) .
4836                                 ')';
4837                 }
4838         }
4840         my $hash_parent_param = $hash_parent;
4841         if (!defined $hash_parent_param) {
4842                 # --cc for multiple parents, --root for parentless
4843                 $hash_parent_param =
4844                         @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
4845         }
4847         # read commitdiff
4848         my $fd;
4849         my @difftree;
4850         if ($format eq 'html') {
4851                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4852                         "--no-commit-id", "--patch-with-raw", "--full-index",
4853                         $hash_parent_param, $hash, "--"
4854                         or die_error(undef, "Open git-diff-tree failed");
4856                 while (my $line = <$fd>) {
4857                         chomp $line;
4858                         # empty line ends raw part of diff-tree output
4859                         last unless $line;
4860                         push @difftree, scalar parse_difftree_raw_line($line);
4861                 }
4863         } elsif ($format eq 'plain') {
4864                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4865                         '-p', $hash_parent_param, $hash, "--"
4866                         or die_error(undef, "Open git-diff-tree failed");
4868         } else {
4869                 die_error(undef, "Unknown commitdiff format");
4870         }
4872         # non-textual hash id's can be cached
4873         my $expires;
4874         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4875                 $expires = "+1d";
4876         }
4878         # write commit message
4879         if ($format eq 'html') {
4880                 my $refs = git_get_references();
4881                 my $ref = format_ref_marker($refs, $co{'id'});
4883                 git_header_html(undef, $expires);
4884                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4885                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4886                 git_print_authorship(\%co);
4887                 print "<div class=\"page_body\">\n";
4888                 if (@{$co{'comment'}} > 1) {
4889                         print "<div class=\"log\">\n";
4890                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4891                         print "</div>\n"; # class="log"
4892                 }
4894         } elsif ($format eq 'plain') {
4895                 my $refs = git_get_references("tags");
4896                 my $tagname = git_get_rev_name_tags($hash);
4897                 my $filename = basename($project) . "-$hash.patch";
4899                 print $cgi->header(
4900                         -type => 'text/plain',
4901                         -charset => 'utf-8',
4902                         -expires => $expires,
4903                         -content_disposition => 'inline; filename="' . "$filename" . '"');
4904                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4905                 print <<TEXT;
4906 From: $co{'author'}
4907 Date: $ad{'rfc2822'} ($ad{'tz_local'})
4908 Subject: $co{'title'}
4909 TEXT
4910                 print "X-Git-Tag: $tagname\n" if $tagname;
4911                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4913                 foreach my $line (@{$co{'comment'}}) {
4914                         print "$line\n";
4915                 }
4916                 print "---\n\n";
4917         }
4919         # write patch
4920         if ($format eq 'html') {
4921                 my $use_parents = !defined $hash_parent ||
4922                         $hash_parent eq '-c' || $hash_parent eq '--cc';
4923                 git_difftree_body(\@difftree, $hash,
4924                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
4925                 print "<br/>\n";
4927                 git_patchset_body($fd, \@difftree, $hash,
4928                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
4929                 close $fd;
4930                 print "</div>\n"; # class="page_body"
4931                 git_footer_html();
4933         } elsif ($format eq 'plain') {
4934                 local $/ = undef;
4935                 print <$fd>;
4936                 close $fd
4937                         or print "Reading git-diff-tree failed\n";
4938         }
4941 sub git_commitdiff_plain {
4942         git_commitdiff('plain');
4945 sub git_history {
4946         if (!defined $hash_base) {
4947                 $hash_base = git_get_head_hash($project);
4948         }
4949         if (!defined $page) {
4950                 $page = 0;
4951         }
4952         my $ftype;
4953         my %co = parse_commit($hash_base);
4954         if (!%co) {
4955                 die_error(undef, "Unknown commit object");
4956         }
4958         my $refs = git_get_references();
4959         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4961         if (!defined $hash && defined $file_name) {
4962                 $hash = git_get_hash_by_path($hash_base, $file_name);
4963         }
4964         if (defined $hash) {
4965                 $ftype = git_get_type($hash);
4966         }
4968         my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
4970         my $paging_nav = '';
4971         if ($page > 0) {
4972                 $paging_nav .=
4973                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4974                                                file_name=>$file_name)},
4975                                 "first");
4976                 $paging_nav .= " &sdot; " .
4977                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4978                                                file_name=>$file_name, page=>$page-1),
4979                                  -accesskey => "p", -title => "Alt-p"}, "prev");
4980         } else {
4981                 $paging_nav .= "first";
4982                 $paging_nav .= " &sdot; prev";
4983         }
4984         if ($#commitlist >= 100) {
4985                 $paging_nav .= " &sdot; " .
4986                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4987                                                file_name=>$file_name, page=>$page+1),
4988                                  -accesskey => "n", -title => "Alt-n"}, "next");
4989         } else {
4990                 $paging_nav .= " &sdot; next";
4991         }
4992         my $next_link = '';
4993         if ($#commitlist >= 100) {
4994                 $next_link =
4995                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4996                                                file_name=>$file_name, page=>$page+1),
4997                                  -accesskey => "n", -title => "Alt-n"}, "next");
4998         }
5000         git_header_html();
5001         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5002         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5003         git_print_page_path($file_name, $ftype, $hash_base);
5005         git_history_body(\@commitlist, 0, 99,
5006                          $refs, $hash_base, $ftype, $next_link);
5008         git_footer_html();
5011 sub git_search {
5012         my ($have_search) = gitweb_check_feature('search');
5013         if (!$have_search) {
5014                 die_error('403 Permission denied', "Permission denied");
5015         }
5016         if (!defined $searchtext) {
5017                 die_error(undef, "Text field empty");
5018         }
5019         if (!defined $hash) {
5020                 $hash = git_get_head_hash($project);
5021         }
5022         my %co = parse_commit($hash);
5023         if (!%co) {
5024                 die_error(undef, "Unknown commit object");
5025         }
5026         if (!defined $page) {
5027                 $page = 0;
5028         }
5030         $searchtype ||= 'commit';
5031         if ($searchtype eq 'pickaxe') {
5032                 # pickaxe may take all resources of your box and run for several minutes
5033                 # with every query - so decide by yourself how public you make this feature
5034                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5035                 if (!$have_pickaxe) {
5036                         die_error('403 Permission denied', "Permission denied");
5037                 }
5038         }
5039         if ($searchtype eq 'grep') {
5040                 my ($have_grep) = gitweb_check_feature('grep');
5041                 if (!$have_grep) {
5042                         die_error('403 Permission denied', "Permission denied");
5043                 }
5044         }
5046         git_header_html();
5048         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5049                 my $greptype;
5050                 if ($searchtype eq 'commit') {
5051                         $greptype = "--grep=";
5052                 } elsif ($searchtype eq 'author') {
5053                         $greptype = "--author=";
5054                 } elsif ($searchtype eq 'committer') {
5055                         $greptype = "--committer=";
5056                 }
5057                 $greptype .= $search_regexp;
5058                 my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
5060                 my $paging_nav = '';
5061                 if ($page > 0) {
5062                         $paging_nav .=
5063                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5064                                                        searchtext=>$searchtext, searchtype=>$searchtype)},
5065                                         "first");
5066                         $paging_nav .= " &sdot; " .
5067                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5068                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5069                                                        page=>$page-1),
5070                                          -accesskey => "p", -title => "Alt-p"}, "prev");
5071                 } else {
5072                         $paging_nav .= "first";
5073                         $paging_nav .= " &sdot; prev";
5074                 }
5075                 if ($#commitlist >= 100) {
5076                         $paging_nav .= " &sdot; " .
5077                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5078                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5079                                                        page=>$page+1),
5080                                          -accesskey => "n", -title => "Alt-n"}, "next");
5081                 } else {
5082                         $paging_nav .= " &sdot; next";
5083                 }
5084                 my $next_link = '';
5085                 if ($#commitlist >= 100) {
5086                         $next_link =
5087                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5088                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5089                                                        page=>$page+1),
5090                                          -accesskey => "n", -title => "Alt-n"}, "next");
5091                 }
5093                 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5094                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5095                 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5096         }
5098         if ($searchtype eq 'pickaxe') {
5099                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5100                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5102                 print "<table cellspacing=\"0\">\n";
5103                 my $alternate = 1;
5104                 $/ = "\n";
5105                 my $git_command = git_cmd_str();
5106                 my $searchqtext = $searchtext;
5107                 $searchqtext =~ s/'/'\\''/;
5108                 open my $fd, "-|", "$git_command rev-list $hash | " .
5109                         "$git_command diff-tree -r --stdin -S\'$searchqtext\'";
5110                 undef %co;
5111                 my @files;
5112                 while (my $line = <$fd>) {
5113                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
5114                                 my %set;
5115                                 $set{'file'} = $6;
5116                                 $set{'from_id'} = $3;
5117                                 $set{'to_id'} = $4;
5118                                 $set{'id'} = $set{'to_id'};
5119                                 if ($set{'id'} =~ m/0{40}/) {
5120                                         $set{'id'} = $set{'from_id'};
5121                                 }
5122                                 if ($set{'id'} =~ m/0{40}/) {
5123                                         next;
5124                                 }
5125                                 push @files, \%set;
5126                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
5127                                 if (%co) {
5128                                         if ($alternate) {
5129                                                 print "<tr class=\"dark\">\n";
5130                                         } else {
5131                                                 print "<tr class=\"light\">\n";
5132                                         }
5133                                         $alternate ^= 1;
5134                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5135                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
5136                                               "<td>" .
5137                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5138                                                       -class => "list subject"},
5139                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
5140                                         while (my $setref = shift @files) {
5141                                                 my %set = %$setref;
5142                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5143                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
5144                                                               -class => "list"},
5145                                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5146                                                       "<br/>\n";
5147                                         }
5148                                         print "</td>\n" .
5149                                               "<td class=\"link\">" .
5150                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5151                                               " | " .
5152                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5153                                         print "</td>\n" .
5154                                               "</tr>\n";
5155                                 }
5156                                 %co = parse_commit($1);
5157                         }
5158                 }
5159                 close $fd;
5161                 print "</table>\n";
5162         }
5164         if ($searchtype eq 'grep') {
5165                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5166                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5168                 print "<table cellspacing=\"0\">\n";
5169                 my $alternate = 1;
5170                 my $matches = 0;
5171                 $/ = "\n";
5172                 open my $fd, "-|", git_cmd(), 'grep', '-n', '-i', '-E', $searchtext, $co{'tree'};
5173                 my $lastfile = '';
5174                 while (my $line = <$fd>) {
5175                         chomp $line;
5176                         my ($file, $lno, $ltext, $binary);
5177                         last if ($matches++ > 1000);
5178                         if ($line =~ /^Binary file (.+) matches$/) {
5179                                 $file = $1;
5180                                 $binary = 1;
5181                         } else {
5182                                 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5183                         }
5184                         if ($file ne $lastfile) {
5185                                 $lastfile and print "</td></tr>\n";
5186                                 if ($alternate++) {
5187                                         print "<tr class=\"dark\">\n";
5188                                 } else {
5189                                         print "<tr class=\"light\">\n";
5190                                 }
5191                                 print "<td class=\"list\">".
5192                                         $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5193                                                                file_name=>"$file"),
5194                                                 -class => "list"}, esc_path($file));
5195                                 print "</td><td>\n";
5196                                 $lastfile = $file;
5197                         }
5198                         if ($binary) {
5199                                 print "<div class=\"binary\">Binary file</div>\n";
5200                         } else {
5201                                 $ltext = untabify($ltext);
5202                                 if ($ltext =~ m/^(.*)($searchtext)(.*)$/i) {
5203                                         $ltext = esc_html($1, -nbsp=>1);
5204                                         $ltext .= '<span class="match">';
5205                                         $ltext .= esc_html($2, -nbsp=>1);
5206                                         $ltext .= '</span>';
5207                                         $ltext .= esc_html($3, -nbsp=>1);
5208                                 } else {
5209                                         $ltext = esc_html($ltext, -nbsp=>1);
5210                                 }
5211                                 print "<div class=\"pre\">" .
5212                                         $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5213                                                                file_name=>"$file").'#l'.$lno,
5214                                                 -class => "linenr"}, sprintf('%4i', $lno))
5215                                         . ' ' .  $ltext . "</div>\n";
5216                         }
5217                 }
5218                 if ($lastfile) {
5219                         print "</td></tr>\n";
5220                         if ($matches > 1000) {
5221                                 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5222                         }
5223                 } else {
5224                         print "<div class=\"diff nodifferences\">No matches found</div>\n";
5225                 }
5226                 close $fd;
5228                 print "</table>\n";
5229         }
5230         git_footer_html();
5233 sub git_search_help {
5234         git_header_html();
5235         git_print_page_nav('','', $hash,$hash,$hash);
5236         print <<EOT;
5237 <dl>
5238 <dt><b>commit</b></dt>
5239 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
5240 EOT
5241         my ($have_grep) = gitweb_check_feature('grep');
5242         if ($have_grep) {
5243                 print <<EOT;
5244 <dt><b>grep</b></dt>
5245 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5246     a different one) are searched for the given
5247 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a>
5248 (POSIX extended) and the matches are listed. On large
5249 trees, this search can take a while and put some strain on the server, so please use it with
5250 some consideration.</dd>
5251 EOT
5252         }
5253         print <<EOT;
5254 <dt><b>author</b></dt>
5255 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
5256 <dt><b>committer</b></dt>
5257 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
5258 EOT
5259         my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5260         if ($have_pickaxe) {
5261                 print <<EOT;
5262 <dt><b>pickaxe</b></dt>
5263 <dd>All commits that caused the string to appear or disappear from any file (changes that
5264 added, removed or "modified" the string) will be listed. This search can take a while and
5265 takes a lot of strain on the server, so please use it wisely.</dd>
5266 EOT
5267         }
5268         print "</dl>\n";
5269         git_footer_html();
5272 sub git_shortlog {
5273         my $head = git_get_head_hash($project);
5274         if (!defined $hash) {
5275                 $hash = $head;
5276         }
5277         if (!defined $page) {
5278                 $page = 0;
5279         }
5280         my $refs = git_get_references();
5282         my @commitlist = parse_commits($hash, 101, (100 * $page));
5284         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
5285         my $next_link = '';
5286         if ($#commitlist >= 100) {
5287                 $next_link =
5288                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
5289                                  -accesskey => "n", -title => "Alt-n"}, "next");
5290         }
5292         git_header_html();
5293         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5294         git_print_header_div('summary', $project);
5296         git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5298         git_footer_html();
5301 ## ......................................................................
5302 ## feeds (RSS, Atom; OPML)
5304 sub git_feed {
5305         my $format = shift || 'atom';
5306         my ($have_blame) = gitweb_check_feature('blame');
5308         # Atom: http://www.atomenabled.org/developers/syndication/
5309         # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5310         if ($format ne 'rss' && $format ne 'atom') {
5311                 die_error(undef, "Unknown web feed format");
5312         }
5314         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5315         my $head = $hash || 'HEAD';
5316         my @commitlist = parse_commits($head, 150);
5318         my %latest_commit;
5319         my %latest_date;
5320         my $content_type = "application/$format+xml";
5321         if (defined $cgi->http('HTTP_ACCEPT') &&
5322                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5323                 # browser (feed reader) prefers text/xml
5324                 $content_type = 'text/xml';
5325         }
5326         if (defined($commitlist[0])) {
5327                 %latest_commit = %{$commitlist[0]};
5328                 %latest_date   = parse_date($latest_commit{'author_epoch'});
5329                 print $cgi->header(
5330                         -type => $content_type,
5331                         -charset => 'utf-8',
5332                         -last_modified => $latest_date{'rfc2822'});
5333         } else {
5334                 print $cgi->header(
5335                         -type => $content_type,
5336                         -charset => 'utf-8');
5337         }
5339         # Optimization: skip generating the body if client asks only
5340         # for Last-Modified date.
5341         return if ($cgi->request_method() eq 'HEAD');
5343         # header variables
5344         my $title = "$site_name - $project/$action";
5345         my $feed_type = 'log';
5346         if (defined $hash) {
5347                 $title .= " - '$hash'";
5348                 $feed_type = 'branch log';
5349                 if (defined $file_name) {
5350                         $title .= " :: $file_name";
5351                         $feed_type = 'history';
5352                 }
5353         } elsif (defined $file_name) {
5354                 $title .= " - $file_name";
5355                 $feed_type = 'history';
5356         }
5357         $title .= " $feed_type";
5358         my $descr = git_get_project_description($project);
5359         if (defined $descr) {
5360                 $descr = esc_html($descr);
5361         } else {
5362                 $descr = "$project " .
5363                          ($format eq 'rss' ? 'RSS' : 'Atom') .
5364                          " feed";
5365         }
5366         my $owner = git_get_project_owner($project);
5367         $owner = esc_html($owner);
5369         #header
5370         my $alt_url;
5371         if (defined $file_name) {
5372                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5373         } elsif (defined $hash) {
5374                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5375         } else {
5376                 $alt_url = href(-full=>1, action=>"summary");
5377         }
5378         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5379         if ($format eq 'rss') {
5380                 print <<XML;
5381 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5382 <channel>
5383 XML
5384                 print "<title>$title</title>\n" .
5385                       "<link>$alt_url</link>\n" .
5386                       "<description>$descr</description>\n" .
5387                       "<language>en</language>\n";
5388         } elsif ($format eq 'atom') {
5389                 print <<XML;
5390 <feed xmlns="http://www.w3.org/2005/Atom">
5391 XML
5392                 print "<title>$title</title>\n" .
5393                       "<subtitle>$descr</subtitle>\n" .
5394                       '<link rel="alternate" type="text/html" href="' .
5395                       $alt_url . '" />' . "\n" .
5396                       '<link rel="self" type="' . $content_type . '" href="' .
5397                       $cgi->self_url() . '" />' . "\n" .
5398                       "<id>" . href(-full=>1) . "</id>\n" .
5399                       # use project owner for feed author
5400                       "<author><name>$owner</name></author>\n";
5401                 if (defined $favicon) {
5402                         print "<icon>" . esc_url($favicon) . "</icon>\n";
5403                 }
5404                 if (defined $logo_url) {
5405                         # not twice as wide as tall: 72 x 27 pixels
5406                         print "<logo>" . esc_url($logo) . "</logo>\n";
5407                 }
5408                 if (! %latest_date) {
5409                         # dummy date to keep the feed valid until commits trickle in:
5410                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
5411                 } else {
5412                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
5413                 }
5414         }
5416         # contents
5417         for (my $i = 0; $i <= $#commitlist; $i++) {
5418                 my %co = %{$commitlist[$i]};
5419                 my $commit = $co{'id'};
5420                 # we read 150, we always show 30 and the ones more recent than 48 hours
5421                 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5422                         last;
5423                 }
5424                 my %cd = parse_date($co{'author_epoch'});
5426                 # get list of changed files
5427                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5428                         $co{'parent'} || "--root",
5429                         $co{'id'}, "--", (defined $file_name ? $file_name : ())
5430                         or next;
5431                 my @difftree = map { chomp; $_ } <$fd>;
5432                 close $fd
5433                         or next;
5435                 # print element (entry, item)
5436                 my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
5437                 if ($format eq 'rss') {
5438                         print "<item>\n" .
5439                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
5440                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
5441                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5442                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5443                               "<link>$co_url</link>\n" .
5444                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
5445                               "<content:encoded>" .
5446                               "<![CDATA[\n";
5447                 } elsif ($format eq 'atom') {
5448                         print "<entry>\n" .
5449                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5450                               "<updated>$cd{'iso-8601'}</updated>\n" .
5451                               "<author>\n" .
5452                               "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
5453                         if ($co{'author_email'}) {
5454                                 print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
5455                         }
5456                         print "</author>\n" .
5457                               # use committer for contributor
5458                               "<contributor>\n" .
5459                               "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5460                         if ($co{'committer_email'}) {
5461                                 print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5462                         }
5463                         print "</contributor>\n" .
5464                               "<published>$cd{'iso-8601'}</published>\n" .
5465                               "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5466                               "<id>$co_url</id>\n" .
5467                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5468                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5469                 }
5470                 my $comment = $co{'comment'};
5471                 print "<pre>\n";
5472                 foreach my $line (@$comment) {
5473                         $line = esc_html($line);
5474                         print "$line\n";
5475                 }
5476                 print "</pre><ul>\n";
5477                 foreach my $difftree_line (@difftree) {
5478                         my %difftree = parse_difftree_raw_line($difftree_line);
5479                         next if !$difftree{'from_id'};
5481                         my $file = $difftree{'file'} || $difftree{'to_file'};
5483                         print "<li>" .
5484                               "[" .
5485                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5486                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5487                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5488                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
5489                                       -title => "diff"}, 'D');
5490                         if ($have_blame) {
5491                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
5492                                                              file_name=>$file, hash_base=>$commit),
5493                                               -title => "blame"}, 'B');
5494                         }
5495                         # if this is not a feed of a file history
5496                         if (!defined $file_name || $file_name ne $file) {
5497                                 print $cgi->a({-href => href(-full=>1, action=>"history",
5498                                                              file_name=>$file, hash=>$commit),
5499                                               -title => "history"}, 'H');
5500                         }
5501                         $file = esc_path($file);
5502                         print "] ".
5503                               "$file</li>\n";
5504                 }
5505                 if ($format eq 'rss') {
5506                         print "</ul>]]>\n" .
5507                               "</content:encoded>\n" .
5508                               "</item>\n";
5509                 } elsif ($format eq 'atom') {
5510                         print "</ul>\n</div>\n" .
5511                               "</content>\n" .
5512                               "</entry>\n";
5513                 }
5514         }
5516         # end of feed
5517         if ($format eq 'rss') {
5518                 print "</channel>\n</rss>\n";
5519         }       elsif ($format eq 'atom') {
5520                 print "</feed>\n";
5521         }
5524 sub git_rss {
5525         git_feed('rss');
5528 sub git_atom {
5529         git_feed('atom');
5532 sub git_opml {
5533         my @list = git_get_projects_list();
5535         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5536         print <<XML;
5537 <?xml version="1.0" encoding="utf-8"?>
5538 <opml version="1.0">
5539 <head>
5540   <title>$site_name OPML Export</title>
5541 </head>
5542 <body>
5543 <outline text="git RSS feeds">
5544 XML
5546         foreach my $pr (@list) {
5547                 my %proj = %$pr;
5548                 my $head = git_get_head_hash($proj{'path'});
5549                 if (!defined $head) {
5550                         next;
5551                 }
5552                 $git_dir = "$projectroot/$proj{'path'}";
5553                 my %co = parse_commit($head);
5554                 if (!%co) {
5555                         next;
5556                 }
5558                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5559                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
5560                 my $html = "$my_url?p=$proj{'path'};a=summary";
5561                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5562         }
5563         print <<XML;
5564 </outline>
5565 </body>
5566 </opml>
5567 XML