Code

gitweb: Show submodule entries in the 'tree' view
[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 use constant {
894         S_IFINVALID => 0030000,
895         S_IFGITLINK => 0160000,
896 };
898 # submodule/subproject, a commit object reference
899 sub S_ISGITLINK($) {
900         my $mode = shift;
902         return (($mode & S_IFMT) == S_IFGITLINK)
905 # convert file mode in octal to symbolic file mode string
906 sub mode_str {
907         my $mode = oct shift;
909         if (S_ISGITLINK($mode)) {
910                 return 'm---------';
911         } elsif (S_ISDIR($mode & S_IFMT)) {
912                 return 'drwxr-xr-x';
913         } elsif (S_ISLNK($mode)) {
914                 return 'lrwxrwxrwx';
915         } elsif (S_ISREG($mode)) {
916                 # git cares only about the executable bit
917                 if ($mode & S_IXUSR) {
918                         return '-rwxr-xr-x';
919                 } else {
920                         return '-rw-r--r--';
921                 };
922         } else {
923                 return '----------';
924         }
927 # convert file mode in octal to file type string
928 sub file_type {
929         my $mode = shift;
931         if ($mode !~ m/^[0-7]+$/) {
932                 return $mode;
933         } else {
934                 $mode = oct $mode;
935         }
937         if (S_ISGITLINK($mode)) {
938                 return "submodule";
939         } elsif (S_ISDIR($mode & S_IFMT)) {
940                 return "directory";
941         } elsif (S_ISLNK($mode)) {
942                 return "symlink";
943         } elsif (S_ISREG($mode)) {
944                 return "file";
945         } else {
946                 return "unknown";
947         }
950 # convert file mode in octal to file type description string
951 sub file_type_long {
952         my $mode = shift;
954         if ($mode !~ m/^[0-7]+$/) {
955                 return $mode;
956         } else {
957                 $mode = oct $mode;
958         }
960         if (S_ISGITLINK($mode)) {
961                 return "submodule";
962         } elsif (S_ISDIR($mode & S_IFMT)) {
963                 return "directory";
964         } elsif (S_ISLNK($mode)) {
965                 return "symlink";
966         } elsif (S_ISREG($mode)) {
967                 if ($mode & S_IXUSR) {
968                         return "executable";
969                 } else {
970                         return "file";
971                 };
972         } else {
973                 return "unknown";
974         }
978 ## ----------------------------------------------------------------------
979 ## functions returning short HTML fragments, or transforming HTML fragments
980 ## which don't belong to other sections
982 # format line of commit message.
983 sub format_log_line_html {
984         my $line = shift;
986         $line = esc_html($line, -nbsp=>1);
987         if ($line =~ m/([0-9a-fA-F]{8,40})/) {
988                 my $hash_text = $1;
989                 my $link =
990                         $cgi->a({-href => href(action=>"object", hash=>$hash_text),
991                                 -class => "text"}, $hash_text);
992                 $line =~ s/$hash_text/$link/;
993         }
994         return $line;
997 # format marker of refs pointing to given object
998 sub format_ref_marker {
999         my ($refs, $id) = @_;
1000         my $markers = '';
1002         if (defined $refs->{$id}) {
1003                 foreach my $ref (@{$refs->{$id}}) {
1004                         my ($type, $name) = qw();
1005                         # e.g. tags/v2.6.11 or heads/next
1006                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
1007                                 $type = $1;
1008                                 $name = $2;
1009                         } else {
1010                                 $type = "ref";
1011                                 $name = $ref;
1012                         }
1014                         $markers .= " <span class=\"$type\" title=\"$ref\">" .
1015                                     esc_html($name) . "</span>";
1016                 }
1017         }
1019         if ($markers) {
1020                 return ' <span class="refs">'. $markers . '</span>';
1021         } else {
1022                 return "";
1023         }
1026 # format, perhaps shortened and with markers, title line
1027 sub format_subject_html {
1028         my ($long, $short, $href, $extra) = @_;
1029         $extra = '' unless defined($extra);
1031         if (length($short) < length($long)) {
1032                 return $cgi->a({-href => $href, -class => "list subject",
1033                                 -title => to_utf8($long)},
1034                        esc_html($short) . $extra);
1035         } else {
1036                 return $cgi->a({-href => $href, -class => "list subject"},
1037                        esc_html($long)  . $extra);
1038         }
1041 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1042 sub format_git_diff_header_line {
1043         my $line = shift;
1044         my $diffinfo = shift;
1045         my ($from, $to) = @_;
1047         if ($diffinfo->{'nparents'}) {
1048                 # combined diff
1049                 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1050                 if ($to->{'href'}) {
1051                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1052                                          esc_path($to->{'file'}));
1053                 } else { # file was deleted (no href)
1054                         $line .= esc_path($to->{'file'});
1055                 }
1056         } else {
1057                 # "ordinary" diff
1058                 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1059                 if ($from->{'href'}) {
1060                         $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1061                                          'a/' . esc_path($from->{'file'}));
1062                 } else { # file was added (no href)
1063                         $line .= 'a/' . esc_path($from->{'file'});
1064                 }
1065                 $line .= ' ';
1066                 if ($to->{'href'}) {
1067                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1068                                          'b/' . esc_path($to->{'file'}));
1069                 } else { # file was deleted
1070                         $line .= 'b/' . esc_path($to->{'file'});
1071                 }
1072         }
1074         return "<div class=\"diff header\">$line</div>\n";
1077 # format extended diff header line, before patch itself
1078 sub format_extended_diff_header_line {
1079         my $line = shift;
1080         my $diffinfo = shift;
1081         my ($from, $to) = @_;
1083         # match <path>
1084         if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1085                 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1086                                        esc_path($from->{'file'}));
1087         }
1088         if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1089                 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1090                                  esc_path($to->{'file'}));
1091         }
1092         # match single <mode>
1093         if ($line =~ m/\s(\d{6})$/) {
1094                 $line .= '<span class="info"> (' .
1095                          file_type_long($1) .
1096                          ')</span>';
1097         }
1098         # match <hash>
1099         if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1100                 # can match only for combined diff
1101                 $line = 'index ';
1102                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1103                         if ($from->{'href'}[$i]) {
1104                                 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1105                                                   -class=>"hash"},
1106                                                  substr($diffinfo->{'from_id'}[$i],0,7));
1107                         } else {
1108                                 $line .= '0' x 7;
1109                         }
1110                         # separator
1111                         $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1112                 }
1113                 $line .= '..';
1114                 if ($to->{'href'}) {
1115                         $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1116                                          substr($diffinfo->{'to_id'},0,7));
1117                 } else {
1118                         $line .= '0' x 7;
1119                 }
1121         } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1122                 # can match only for ordinary diff
1123                 my ($from_link, $to_link);
1124                 if ($from->{'href'}) {
1125                         $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1126                                              substr($diffinfo->{'from_id'},0,7));
1127                 } else {
1128                         $from_link = '0' x 7;
1129                 }
1130                 if ($to->{'href'}) {
1131                         $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1132                                            substr($diffinfo->{'to_id'},0,7));
1133                 } else {
1134                         $to_link = '0' x 7;
1135                 }
1136                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1137                 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1138         }
1140         return $line . "<br/>\n";
1143 # format from-file/to-file diff header
1144 sub format_diff_from_to_header {
1145         my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1146         my $line;
1147         my $result = '';
1149         $line = $from_line;
1150         #assert($line =~ m/^---/) if DEBUG;
1151         # no extra formatting for "^--- /dev/null"
1152         if (! $diffinfo->{'nparents'}) {
1153                 # ordinary (single parent) diff
1154                 if ($line =~ m!^--- "?a/!) {
1155                         if ($from->{'href'}) {
1156                                 $line = '--- a/' .
1157                                         $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1158                                                 esc_path($from->{'file'}));
1159                         } else {
1160                                 $line = '--- a/' .
1161                                         esc_path($from->{'file'});
1162                         }
1163                 }
1164                 $result .= qq!<div class="diff from_file">$line</div>\n!;
1166         } else {
1167                 # combined diff (merge commit)
1168                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1169                         if ($from->{'href'}[$i]) {
1170                                 $line = '--- ' .
1171                                         $cgi->a({-href=>href(action=>"blobdiff",
1172                                                              hash_parent=>$diffinfo->{'from_id'}[$i],
1173                                                              hash_parent_base=>$parents[$i],
1174                                                              file_parent=>$from->{'file'}[$i],
1175                                                              hash=>$diffinfo->{'to_id'},
1176                                                              hash_base=>$hash,
1177                                                              file_name=>$to->{'file'}),
1178                                                  -class=>"path",
1179                                                  -title=>"diff" . ($i+1)},
1180                                                 $i+1) .
1181                                         '/' .
1182                                         $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1183                                                 esc_path($from->{'file'}[$i]));
1184                         } else {
1185                                 $line = '--- /dev/null';
1186                         }
1187                         $result .= qq!<div class="diff from_file">$line</div>\n!;
1188                 }
1189         }
1191         $line = $to_line;
1192         #assert($line =~ m/^\+\+\+/) if DEBUG;
1193         # no extra formatting for "^+++ /dev/null"
1194         if ($line =~ m!^\+\+\+ "?b/!) {
1195                 if ($to->{'href'}) {
1196                         $line = '+++ b/' .
1197                                 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1198                                         esc_path($to->{'file'}));
1199                 } else {
1200                         $line = '+++ b/' .
1201                                 esc_path($to->{'file'});
1202                 }
1203         }
1204         $result .= qq!<div class="diff to_file">$line</div>\n!;
1206         return $result;
1209 # create note for patch simplified by combined diff
1210 sub format_diff_cc_simplified {
1211         my ($diffinfo, @parents) = @_;
1212         my $result = '';
1214         $result .= "<div class=\"diff header\">" .
1215                    "diff --cc ";
1216         if (!is_deleted($diffinfo)) {
1217                 $result .= $cgi->a({-href => href(action=>"blob",
1218                                                   hash_base=>$hash,
1219                                                   hash=>$diffinfo->{'to_id'},
1220                                                   file_name=>$diffinfo->{'to_file'}),
1221                                     -class => "path"},
1222                                    esc_path($diffinfo->{'to_file'}));
1223         } else {
1224                 $result .= esc_path($diffinfo->{'to_file'});
1225         }
1226         $result .= "</div>\n" . # class="diff header"
1227                    "<div class=\"diff nodifferences\">" .
1228                    "Simple merge" .
1229                    "</div>\n"; # class="diff nodifferences"
1231         return $result;
1234 # format patch (diff) line (not to be used for diff headers)
1235 sub format_diff_line {
1236         my $line = shift;
1237         my ($from, $to) = @_;
1238         my $diff_class = "";
1240         chomp $line;
1242         if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1243                 # combined diff
1244                 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1245                 if ($line =~ m/^\@{3}/) {
1246                         $diff_class = " chunk_header";
1247                 } elsif ($line =~ m/^\\/) {
1248                         $diff_class = " incomplete";
1249                 } elsif ($prefix =~ tr/+/+/) {
1250                         $diff_class = " add";
1251                 } elsif ($prefix =~ tr/-/-/) {
1252                         $diff_class = " rem";
1253                 }
1254         } else {
1255                 # assume ordinary diff
1256                 my $char = substr($line, 0, 1);
1257                 if ($char eq '+') {
1258                         $diff_class = " add";
1259                 } elsif ($char eq '-') {
1260                         $diff_class = " rem";
1261                 } elsif ($char eq '@') {
1262                         $diff_class = " chunk_header";
1263                 } elsif ($char eq "\\") {
1264                         $diff_class = " incomplete";
1265                 }
1266         }
1267         $line = untabify($line);
1268         if ($from && $to && $line =~ m/^\@{2} /) {
1269                 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1270                         $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1272                 $from_lines = 0 unless defined $from_lines;
1273                 $to_lines   = 0 unless defined $to_lines;
1275                 if ($from->{'href'}) {
1276                         $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1277                                              -class=>"list"}, $from_text);
1278                 }
1279                 if ($to->{'href'}) {
1280                         $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1281                                              -class=>"list"}, $to_text);
1282                 }
1283                 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1284                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1285                 return "<div class=\"diff$diff_class\">$line</div>\n";
1286         } elsif ($from && $to && $line =~ m/^\@{3}/) {
1287                 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1288                 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1290                 @from_text = split(' ', $ranges);
1291                 for (my $i = 0; $i < @from_text; ++$i) {
1292                         ($from_start[$i], $from_nlines[$i]) =
1293                                 (split(',', substr($from_text[$i], 1)), 0);
1294                 }
1296                 $to_text   = pop @from_text;
1297                 $to_start  = pop @from_start;
1298                 $to_nlines = pop @from_nlines;
1300                 $line = "<span class=\"chunk_info\">$prefix ";
1301                 for (my $i = 0; $i < @from_text; ++$i) {
1302                         if ($from->{'href'}[$i]) {
1303                                 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1304                                                   -class=>"list"}, $from_text[$i]);
1305                         } else {
1306                                 $line .= $from_text[$i];
1307                         }
1308                         $line .= " ";
1309                 }
1310                 if ($to->{'href'}) {
1311                         $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1312                                           -class=>"list"}, $to_text);
1313                 } else {
1314                         $line .= $to_text;
1315                 }
1316                 $line .= " $prefix</span>" .
1317                          "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1318                 return "<div class=\"diff$diff_class\">$line</div>\n";
1319         }
1320         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1323 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1324 # linked.  Pass the hash of the tree/commit to snapshot.
1325 sub format_snapshot_links {
1326         my ($hash) = @_;
1327         my @snapshot_fmts = gitweb_check_feature('snapshot');
1328         @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1329         my $num_fmts = @snapshot_fmts;
1330         if ($num_fmts > 1) {
1331                 # A parenthesized list of links bearing format names.
1332                 # e.g. "snapshot (_tar.gz_ _zip_)"
1333                 return "snapshot (" . join(' ', map
1334                         $cgi->a({
1335                                 -href => href(
1336                                         action=>"snapshot",
1337                                         hash=>$hash,
1338                                         snapshot_format=>$_
1339                                 )
1340                         }, $known_snapshot_formats{$_}{'display'})
1341                 , @snapshot_fmts) . ")";
1342         } elsif ($num_fmts == 1) {
1343                 # A single "snapshot" link whose tooltip bears the format name.
1344                 # i.e. "_snapshot_"
1345                 my ($fmt) = @snapshot_fmts;
1346                 return
1347                         $cgi->a({
1348                                 -href => href(
1349                                         action=>"snapshot",
1350                                         hash=>$hash,
1351                                         snapshot_format=>$fmt
1352                                 ),
1353                                 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1354                         }, "snapshot");
1355         } else { # $num_fmts == 0
1356                 return undef;
1357         }
1360 ## ----------------------------------------------------------------------
1361 ## git utility subroutines, invoking git commands
1363 # returns path to the core git executable and the --git-dir parameter as list
1364 sub git_cmd {
1365         return $GIT, '--git-dir='.$git_dir;
1368 # returns path to the core git executable and the --git-dir parameter as string
1369 sub git_cmd_str {
1370         return join(' ', git_cmd());
1373 # get HEAD ref of given project as hash
1374 sub git_get_head_hash {
1375         my $project = shift;
1376         my $o_git_dir = $git_dir;
1377         my $retval = undef;
1378         $git_dir = "$projectroot/$project";
1379         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1380                 my $head = <$fd>;
1381                 close $fd;
1382                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1383                         $retval = $1;
1384                 }
1385         }
1386         if (defined $o_git_dir) {
1387                 $git_dir = $o_git_dir;
1388         }
1389         return $retval;
1392 # get type of given object
1393 sub git_get_type {
1394         my $hash = shift;
1396         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1397         my $type = <$fd>;
1398         close $fd or return;
1399         chomp $type;
1400         return $type;
1403 sub git_get_project_config {
1404         my ($key, $type) = @_;
1406         return unless ($key);
1407         $key =~ s/^gitweb\.//;
1408         return if ($key =~ m/\W/);
1410         my @x = (git_cmd(), 'config');
1411         if (defined $type) { push @x, $type; }
1412         push @x, "--get";
1413         push @x, "gitweb.$key";
1414         my $val = qx(@x);
1415         chomp $val;
1416         return ($val);
1419 # get hash of given path at given ref
1420 sub git_get_hash_by_path {
1421         my $base = shift;
1422         my $path = shift || return undef;
1423         my $type = shift;
1425         $path =~ s,/+$,,;
1427         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1428                 or die_error(undef, "Open git-ls-tree failed");
1429         my $line = <$fd>;
1430         close $fd or return undef;
1432         if (!defined $line) {
1433                 # there is no tree or hash given by $path at $base
1434                 return undef;
1435         }
1437         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1438         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1439         if (defined $type && $type ne $2) {
1440                 # type doesn't match
1441                 return undef;
1442         }
1443         return $3;
1446 # get path of entry with given hash at given tree-ish (ref)
1447 # used to get 'from' filename for combined diff (merge commit) for renames
1448 sub git_get_path_by_hash {
1449         my $base = shift || return;
1450         my $hash = shift || return;
1452         local $/ = "\0";
1454         open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1455                 or return undef;
1456         while (my $line = <$fd>) {
1457                 chomp $line;
1459                 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
1460                 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
1461                 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1462                         close $fd;
1463                         return $1;
1464                 }
1465         }
1466         close $fd;
1467         return undef;
1470 ## ......................................................................
1471 ## git utility functions, directly accessing git repository
1473 sub git_get_project_description {
1474         my $path = shift;
1476         open my $fd, "$projectroot/$path/description" or return undef;
1477         my $descr = <$fd>;
1478         close $fd;
1479         if (defined $descr) {
1480                 chomp $descr;
1481         }
1482         return $descr;
1485 sub git_get_project_url_list {
1486         my $path = shift;
1488         open my $fd, "$projectroot/$path/cloneurl" or return;
1489         my @git_project_url_list = map { chomp; $_ } <$fd>;
1490         close $fd;
1492         return wantarray ? @git_project_url_list : \@git_project_url_list;
1495 sub git_get_projects_list {
1496         my ($filter) = @_;
1497         my @list;
1499         $filter ||= '';
1500         $filter =~ s/\.git$//;
1502         my ($check_forks) = gitweb_check_feature('forks');
1504         if (-d $projects_list) {
1505                 # search in directory
1506                 my $dir = $projects_list . ($filter ? "/$filter" : '');
1507                 # remove the trailing "/"
1508                 $dir =~ s!/+$!!;
1509                 my $pfxlen = length("$dir");
1511                 File::Find::find({
1512                         follow_fast => 1, # follow symbolic links
1513                         dangling_symlinks => 0, # ignore dangling symlinks, silently
1514                         wanted => sub {
1515                                 # skip project-list toplevel, if we get it.
1516                                 return if (m!^[/.]$!);
1517                                 # only directories can be git repositories
1518                                 return unless (-d $_);
1520                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
1521                                 # we check related file in $projectroot
1522                                 if ($check_forks and $subdir =~ m#/.#) {
1523                                         $File::Find::prune = 1;
1524                                 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1525                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1526                                         $File::Find::prune = 1;
1527                                 }
1528                         },
1529                 }, "$dir");
1531         } elsif (-f $projects_list) {
1532                 # read from file(url-encoded):
1533                 # 'git%2Fgit.git Linus+Torvalds'
1534                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1535                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1536                 my %paths;
1537                 open my ($fd), $projects_list or return;
1538         PROJECT:
1539                 while (my $line = <$fd>) {
1540                         chomp $line;
1541                         my ($path, $owner) = split ' ', $line;
1542                         $path = unescape($path);
1543                         $owner = unescape($owner);
1544                         if (!defined $path) {
1545                                 next;
1546                         }
1547                         if ($filter ne '') {
1548                                 # looking for forks;
1549                                 my $pfx = substr($path, 0, length($filter));
1550                                 if ($pfx ne $filter) {
1551                                         next PROJECT;
1552                                 }
1553                                 my $sfx = substr($path, length($filter));
1554                                 if ($sfx !~ /^\/.*\.git$/) {
1555                                         next PROJECT;
1556                                 }
1557                         } elsif ($check_forks) {
1558                         PATH:
1559                                 foreach my $filter (keys %paths) {
1560                                         # looking for forks;
1561                                         my $pfx = substr($path, 0, length($filter));
1562                                         if ($pfx ne $filter) {
1563                                                 next PATH;
1564                                         }
1565                                         my $sfx = substr($path, length($filter));
1566                                         if ($sfx !~ /^\/.*\.git$/) {
1567                                                 next PATH;
1568                                         }
1569                                         # is a fork, don't include it in
1570                                         # the list
1571                                         next PROJECT;
1572                                 }
1573                         }
1574                         if (check_export_ok("$projectroot/$path")) {
1575                                 my $pr = {
1576                                         path => $path,
1577                                         owner => to_utf8($owner),
1578                                 };
1579                                 push @list, $pr;
1580                                 (my $forks_path = $path) =~ s/\.git$//;
1581                                 $paths{$forks_path}++;
1582                         }
1583                 }
1584                 close $fd;
1585         }
1586         return @list;
1589 our $gitweb_project_owner = undef;
1590 sub git_get_project_list_from_file {
1592         return if (defined $gitweb_project_owner);
1594         $gitweb_project_owner = {};
1595         # read from file (url-encoded):
1596         # 'git%2Fgit.git Linus+Torvalds'
1597         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1598         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1599         if (-f $projects_list) {
1600                 open (my $fd , $projects_list);
1601                 while (my $line = <$fd>) {
1602                         chomp $line;
1603                         my ($pr, $ow) = split ' ', $line;
1604                         $pr = unescape($pr);
1605                         $ow = unescape($ow);
1606                         $gitweb_project_owner->{$pr} = to_utf8($ow);
1607                 }
1608                 close $fd;
1609         }
1612 sub git_get_project_owner {
1613         my $project = shift;
1614         my $owner;
1616         return undef unless $project;
1618         if (!defined $gitweb_project_owner) {
1619                 git_get_project_list_from_file();
1620         }
1622         if (exists $gitweb_project_owner->{$project}) {
1623                 $owner = $gitweb_project_owner->{$project};
1624         }
1625         if (!defined $owner) {
1626                 $owner = get_file_owner("$projectroot/$project");
1627         }
1629         return $owner;
1632 sub git_get_last_activity {
1633         my ($path) = @_;
1634         my $fd;
1636         $git_dir = "$projectroot/$path";
1637         open($fd, "-|", git_cmd(), 'for-each-ref',
1638              '--format=%(committer)',
1639              '--sort=-committerdate',
1640              '--count=1',
1641              'refs/heads') or return;
1642         my $most_recent = <$fd>;
1643         close $fd or return;
1644         if (defined $most_recent &&
1645             $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1646                 my $timestamp = $1;
1647                 my $age = time - $timestamp;
1648                 return ($age, age_string($age));
1649         }
1650         return (undef, undef);
1653 sub git_get_references {
1654         my $type = shift || "";
1655         my %refs;
1656         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1657         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1658         open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1659                 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1660                 or return;
1662         while (my $line = <$fd>) {
1663                 chomp $line;
1664                 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1665                         if (defined $refs{$1}) {
1666                                 push @{$refs{$1}}, $2;
1667                         } else {
1668                                 $refs{$1} = [ $2 ];
1669                         }
1670                 }
1671         }
1672         close $fd or return;
1673         return \%refs;
1676 sub git_get_rev_name_tags {
1677         my $hash = shift || return undef;
1679         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1680                 or return;
1681         my $name_rev = <$fd>;
1682         close $fd;
1684         if ($name_rev =~ m|^$hash tags/(.*)$|) {
1685                 return $1;
1686         } else {
1687                 # catches also '$hash undefined' output
1688                 return undef;
1689         }
1692 ## ----------------------------------------------------------------------
1693 ## parse to hash functions
1695 sub parse_date {
1696         my $epoch = shift;
1697         my $tz = shift || "-0000";
1699         my %date;
1700         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1701         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1702         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1703         $date{'hour'} = $hour;
1704         $date{'minute'} = $min;
1705         $date{'mday'} = $mday;
1706         $date{'day'} = $days[$wday];
1707         $date{'month'} = $months[$mon];
1708         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1709                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1710         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1711                              $mday, $months[$mon], $hour ,$min;
1712         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1713                              1900+$year, $mon, $mday, $hour ,$min, $sec;
1715         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1716         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1717         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1718         $date{'hour_local'} = $hour;
1719         $date{'minute_local'} = $min;
1720         $date{'tz_local'} = $tz;
1721         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1722                                   1900+$year, $mon+1, $mday,
1723                                   $hour, $min, $sec, $tz);
1724         return %date;
1727 sub parse_tag {
1728         my $tag_id = shift;
1729         my %tag;
1730         my @comment;
1732         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1733         $tag{'id'} = $tag_id;
1734         while (my $line = <$fd>) {
1735                 chomp $line;
1736                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1737                         $tag{'object'} = $1;
1738                 } elsif ($line =~ m/^type (.+)$/) {
1739                         $tag{'type'} = $1;
1740                 } elsif ($line =~ m/^tag (.+)$/) {
1741                         $tag{'name'} = $1;
1742                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1743                         $tag{'author'} = $1;
1744                         $tag{'epoch'} = $2;
1745                         $tag{'tz'} = $3;
1746                 } elsif ($line =~ m/--BEGIN/) {
1747                         push @comment, $line;
1748                         last;
1749                 } elsif ($line eq "") {
1750                         last;
1751                 }
1752         }
1753         push @comment, <$fd>;
1754         $tag{'comment'} = \@comment;
1755         close $fd or return;
1756         if (!defined $tag{'name'}) {
1757                 return
1758         };
1759         return %tag
1762 sub parse_commit_text {
1763         my ($commit_text, $withparents) = @_;
1764         my @commit_lines = split '\n', $commit_text;
1765         my %co;
1767         pop @commit_lines; # Remove '\0'
1769         if (! @commit_lines) {
1770                 return;
1771         }
1773         my $header = shift @commit_lines;
1774         if ($header !~ m/^[0-9a-fA-F]{40}/) {
1775                 return;
1776         }
1777         ($co{'id'}, my @parents) = split ' ', $header;
1778         while (my $line = shift @commit_lines) {
1779                 last if $line eq "\n";
1780                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1781                         $co{'tree'} = $1;
1782                 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1783                         push @parents, $1;
1784                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1785                         $co{'author'} = $1;
1786                         $co{'author_epoch'} = $2;
1787                         $co{'author_tz'} = $3;
1788                         if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1789                                 $co{'author_name'}  = $1;
1790                                 $co{'author_email'} = $2;
1791                         } else {
1792                                 $co{'author_name'} = $co{'author'};
1793                         }
1794                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1795                         $co{'committer'} = $1;
1796                         $co{'committer_epoch'} = $2;
1797                         $co{'committer_tz'} = $3;
1798                         $co{'committer_name'} = $co{'committer'};
1799                         if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1800                                 $co{'committer_name'}  = $1;
1801                                 $co{'committer_email'} = $2;
1802                         } else {
1803                                 $co{'committer_name'} = $co{'committer'};
1804                         }
1805                 }
1806         }
1807         if (!defined $co{'tree'}) {
1808                 return;
1809         };
1810         $co{'parents'} = \@parents;
1811         $co{'parent'} = $parents[0];
1813         foreach my $title (@commit_lines) {
1814                 $title =~ s/^    //;
1815                 if ($title ne "") {
1816                         $co{'title'} = chop_str($title, 80, 5);
1817                         # remove leading stuff of merges to make the interesting part visible
1818                         if (length($title) > 50) {
1819                                 $title =~ s/^Automatic //;
1820                                 $title =~ s/^merge (of|with) /Merge ... /i;
1821                                 if (length($title) > 50) {
1822                                         $title =~ s/(http|rsync):\/\///;
1823                                 }
1824                                 if (length($title) > 50) {
1825                                         $title =~ s/(master|www|rsync)\.//;
1826                                 }
1827                                 if (length($title) > 50) {
1828                                         $title =~ s/kernel.org:?//;
1829                                 }
1830                                 if (length($title) > 50) {
1831                                         $title =~ s/\/pub\/scm//;
1832                                 }
1833                         }
1834                         $co{'title_short'} = chop_str($title, 50, 5);
1835                         last;
1836                 }
1837         }
1838         if ($co{'title'} eq "") {
1839                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1840         }
1841         # remove added spaces
1842         foreach my $line (@commit_lines) {
1843                 $line =~ s/^    //;
1844         }
1845         $co{'comment'} = \@commit_lines;
1847         my $age = time - $co{'committer_epoch'};
1848         $co{'age'} = $age;
1849         $co{'age_string'} = age_string($age);
1850         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1851         if ($age > 60*60*24*7*2) {
1852                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1853                 $co{'age_string_age'} = $co{'age_string'};
1854         } else {
1855                 $co{'age_string_date'} = $co{'age_string'};
1856                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1857         }
1858         return %co;
1861 sub parse_commit {
1862         my ($commit_id) = @_;
1863         my %co;
1865         local $/ = "\0";
1867         open my $fd, "-|", git_cmd(), "rev-list",
1868                 "--parents",
1869                 "--header",
1870                 "--max-count=1",
1871                 $commit_id,
1872                 "--",
1873                 or die_error(undef, "Open git-rev-list failed");
1874         %co = parse_commit_text(<$fd>, 1);
1875         close $fd;
1877         return %co;
1880 sub parse_commits {
1881         my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1882         my @cos;
1884         $maxcount ||= 1;
1885         $skip ||= 0;
1887         local $/ = "\0";
1889         open my $fd, "-|", git_cmd(), "rev-list",
1890                 "--header",
1891                 ($arg ? ($arg) : ()),
1892                 ("--max-count=" . $maxcount),
1893                 ("--skip=" . $skip),
1894                 @extra_options,
1895                 $commit_id,
1896                 "--",
1897                 ($filename ? ($filename) : ())
1898                 or die_error(undef, "Open git-rev-list failed");
1899         while (my $line = <$fd>) {
1900                 my %co = parse_commit_text($line);
1901                 push @cos, \%co;
1902         }
1903         close $fd;
1905         return wantarray ? @cos : \@cos;
1908 # parse ref from ref_file, given by ref_id, with given type
1909 sub parse_ref {
1910         my $ref_file = shift;
1911         my $ref_id = shift;
1912         my $type = shift || git_get_type($ref_id);
1913         my %ref_item;
1915         $ref_item{'type'} = $type;
1916         $ref_item{'id'} = $ref_id;
1917         $ref_item{'epoch'} = 0;
1918         $ref_item{'age'} = "unknown";
1919         if ($type eq "tag") {
1920                 my %tag = parse_tag($ref_id);
1921                 $ref_item{'comment'} = $tag{'comment'};
1922                 if ($tag{'type'} eq "commit") {
1923                         my %co = parse_commit($tag{'object'});
1924                         $ref_item{'epoch'} = $co{'committer_epoch'};
1925                         $ref_item{'age'} = $co{'age_string'};
1926                 } elsif (defined($tag{'epoch'})) {
1927                         my $age = time - $tag{'epoch'};
1928                         $ref_item{'epoch'} = $tag{'epoch'};
1929                         $ref_item{'age'} = age_string($age);
1930                 }
1931                 $ref_item{'reftype'} = $tag{'type'};
1932                 $ref_item{'name'} = $tag{'name'};
1933                 $ref_item{'refid'} = $tag{'object'};
1934         } elsif ($type eq "commit"){
1935                 my %co = parse_commit($ref_id);
1936                 $ref_item{'reftype'} = "commit";
1937                 $ref_item{'name'} = $ref_file;
1938                 $ref_item{'title'} = $co{'title'};
1939                 $ref_item{'refid'} = $ref_id;
1940                 $ref_item{'epoch'} = $co{'committer_epoch'};
1941                 $ref_item{'age'} = $co{'age_string'};
1942         } else {
1943                 $ref_item{'reftype'} = $type;
1944                 $ref_item{'name'} = $ref_file;
1945                 $ref_item{'refid'} = $ref_id;
1946         }
1948         return %ref_item;
1951 # parse line of git-diff-tree "raw" output
1952 sub parse_difftree_raw_line {
1953         my $line = shift;
1954         my %res;
1956         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1957         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1958         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1959                 $res{'from_mode'} = $1;
1960                 $res{'to_mode'} = $2;
1961                 $res{'from_id'} = $3;
1962                 $res{'to_id'} = $4;
1963                 $res{'status'} = $5;
1964                 $res{'similarity'} = $6;
1965                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1966                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1967                 } else {
1968                         $res{'file'} = unquote($7);
1969                 }
1970         }
1971         # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
1972         # combined diff (for merge commit)
1973         elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
1974                 $res{'nparents'}  = length($1);
1975                 $res{'from_mode'} = [ split(' ', $2) ];
1976                 $res{'to_mode'} = pop @{$res{'from_mode'}};
1977                 $res{'from_id'} = [ split(' ', $3) ];
1978                 $res{'to_id'} = pop @{$res{'from_id'}};
1979                 $res{'status'} = [ split('', $4) ];
1980                 $res{'to_file'} = unquote($5);
1981         }
1982         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1983         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1984                 $res{'commit'} = $1;
1985         }
1987         return wantarray ? %res : \%res;
1990 # parse line of git-ls-tree output
1991 sub parse_ls_tree_line ($;%) {
1992         my $line = shift;
1993         my %opts = @_;
1994         my %res;
1996         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1997         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1999         $res{'mode'} = $1;
2000         $res{'type'} = $2;
2001         $res{'hash'} = $3;
2002         if ($opts{'-z'}) {
2003                 $res{'name'} = $4;
2004         } else {
2005                 $res{'name'} = unquote($4);
2006         }
2008         return wantarray ? %res : \%res;
2011 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2012 sub parse_from_to_diffinfo {
2013         my ($diffinfo, $from, $to, @parents) = @_;
2015         if ($diffinfo->{'nparents'}) {
2016                 # combined diff
2017                 $from->{'file'} = [];
2018                 $from->{'href'} = [];
2019                 fill_from_file_info($diffinfo, @parents)
2020                         unless exists $diffinfo->{'from_file'};
2021                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2022                         $from->{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
2023                         if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2024                                 $from->{'href'}[$i] = href(action=>"blob",
2025                                                            hash_base=>$parents[$i],
2026                                                            hash=>$diffinfo->{'from_id'}[$i],
2027                                                            file_name=>$from->{'file'}[$i]);
2028                         } else {
2029                                 $from->{'href'}[$i] = undef;
2030                         }
2031                 }
2032         } else {
2033                 $from->{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
2034                 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2035                         $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2036                                                hash=>$diffinfo->{'from_id'},
2037                                                file_name=>$from->{'file'});
2038                 } else {
2039                         delete $from->{'href'};
2040                 }
2041         }
2043         $to->{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
2044         if (!is_deleted($diffinfo)) { # file exists in result
2045                 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2046                                      hash=>$diffinfo->{'to_id'},
2047                                      file_name=>$to->{'file'});
2048         } else {
2049                 delete $to->{'href'};
2050         }
2053 ## ......................................................................
2054 ## parse to array of hashes functions
2056 sub git_get_heads_list {
2057         my $limit = shift;
2058         my @headslist;
2060         open my $fd, '-|', git_cmd(), 'for-each-ref',
2061                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2062                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2063                 'refs/heads'
2064                 or return;
2065         while (my $line = <$fd>) {
2066                 my %ref_item;
2068                 chomp $line;
2069                 my ($refinfo, $committerinfo) = split(/\0/, $line);
2070                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2071                 my ($committer, $epoch, $tz) =
2072                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2073                 $name =~ s!^refs/heads/!!;
2075                 $ref_item{'name'}  = $name;
2076                 $ref_item{'id'}    = $hash;
2077                 $ref_item{'title'} = $title || '(no commit message)';
2078                 $ref_item{'epoch'} = $epoch;
2079                 if ($epoch) {
2080                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2081                 } else {
2082                         $ref_item{'age'} = "unknown";
2083                 }
2085                 push @headslist, \%ref_item;
2086         }
2087         close $fd;
2089         return wantarray ? @headslist : \@headslist;
2092 sub git_get_tags_list {
2093         my $limit = shift;
2094         my @tagslist;
2096         open my $fd, '-|', git_cmd(), 'for-each-ref',
2097                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2098                 '--format=%(objectname) %(objecttype) %(refname) '.
2099                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2100                 'refs/tags'
2101                 or return;
2102         while (my $line = <$fd>) {
2103                 my %ref_item;
2105                 chomp $line;
2106                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2107                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2108                 my ($creator, $epoch, $tz) =
2109                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2110                 $name =~ s!^refs/tags/!!;
2112                 $ref_item{'type'} = $type;
2113                 $ref_item{'id'} = $id;
2114                 $ref_item{'name'} = $name;
2115                 if ($type eq "tag") {
2116                         $ref_item{'subject'} = $title;
2117                         $ref_item{'reftype'} = $reftype;
2118                         $ref_item{'refid'}   = $refid;
2119                 } else {
2120                         $ref_item{'reftype'} = $type;
2121                         $ref_item{'refid'}   = $id;
2122                 }
2124                 if ($type eq "tag" || $type eq "commit") {
2125                         $ref_item{'epoch'} = $epoch;
2126                         if ($epoch) {
2127                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2128                         } else {
2129                                 $ref_item{'age'} = "unknown";
2130                         }
2131                 }
2133                 push @tagslist, \%ref_item;
2134         }
2135         close $fd;
2137         return wantarray ? @tagslist : \@tagslist;
2140 ## ----------------------------------------------------------------------
2141 ## filesystem-related functions
2143 sub get_file_owner {
2144         my $path = shift;
2146         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2147         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2148         if (!defined $gcos) {
2149                 return undef;
2150         }
2151         my $owner = $gcos;
2152         $owner =~ s/[,;].*$//;
2153         return to_utf8($owner);
2156 ## ......................................................................
2157 ## mimetype related functions
2159 sub mimetype_guess_file {
2160         my $filename = shift;
2161         my $mimemap = shift;
2162         -r $mimemap or return undef;
2164         my %mimemap;
2165         open(MIME, $mimemap) or return undef;
2166         while (<MIME>) {
2167                 next if m/^#/; # skip comments
2168                 my ($mime, $exts) = split(/\t+/);
2169                 if (defined $exts) {
2170                         my @exts = split(/\s+/, $exts);
2171                         foreach my $ext (@exts) {
2172                                 $mimemap{$ext} = $mime;
2173                         }
2174                 }
2175         }
2176         close(MIME);
2178         $filename =~ /\.([^.]*)$/;
2179         return $mimemap{$1};
2182 sub mimetype_guess {
2183         my $filename = shift;
2184         my $mime;
2185         $filename =~ /\./ or return undef;
2187         if ($mimetypes_file) {
2188                 my $file = $mimetypes_file;
2189                 if ($file !~ m!^/!) { # if it is relative path
2190                         # it is relative to project
2191                         $file = "$projectroot/$project/$file";
2192                 }
2193                 $mime = mimetype_guess_file($filename, $file);
2194         }
2195         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2196         return $mime;
2199 sub blob_mimetype {
2200         my $fd = shift;
2201         my $filename = shift;
2203         if ($filename) {
2204                 my $mime = mimetype_guess($filename);
2205                 $mime and return $mime;
2206         }
2208         # just in case
2209         return $default_blob_plain_mimetype unless $fd;
2211         if (-T $fd) {
2212                 return 'text/plain' .
2213                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
2214         } elsif (! $filename) {
2215                 return 'application/octet-stream';
2216         } elsif ($filename =~ m/\.png$/i) {
2217                 return 'image/png';
2218         } elsif ($filename =~ m/\.gif$/i) {
2219                 return 'image/gif';
2220         } elsif ($filename =~ m/\.jpe?g$/i) {
2221                 return 'image/jpeg';
2222         } else {
2223                 return 'application/octet-stream';
2224         }
2227 ## ======================================================================
2228 ## functions printing HTML: header, footer, error page
2230 sub git_header_html {
2231         my $status = shift || "200 OK";
2232         my $expires = shift;
2234         my $title = "$site_name";
2235         if (defined $project) {
2236                 $title .= " - " . to_utf8($project);
2237                 if (defined $action) {
2238                         $title .= "/$action";
2239                         if (defined $file_name) {
2240                                 $title .= " - " . esc_path($file_name);
2241                                 if ($action eq "tree" && $file_name !~ m|/$|) {
2242                                         $title .= "/";
2243                                 }
2244                         }
2245                 }
2246         }
2247         my $content_type;
2248         # require explicit support from the UA if we are to send the page as
2249         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2250         # we have to do this because MSIE sometimes globs '*/*', pretending to
2251         # support xhtml+xml but choking when it gets what it asked for.
2252         if (defined $cgi->http('HTTP_ACCEPT') &&
2253             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2254             $cgi->Accept('application/xhtml+xml') != 0) {
2255                 $content_type = 'application/xhtml+xml';
2256         } else {
2257                 $content_type = 'text/html';
2258         }
2259         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2260                            -status=> $status, -expires => $expires);
2261         my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2262         print <<EOF;
2263 <?xml version="1.0" encoding="utf-8"?>
2264 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2265 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2266 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2267 <!-- git core binaries version $git_version -->
2268 <head>
2269 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2270 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2271 <meta name="robots" content="index, nofollow"/>
2272 <title>$title</title>
2273 EOF
2274 # print out each stylesheet that exist
2275         if (defined $stylesheet) {
2276 #provides backwards capability for those people who define style sheet in a config file
2277                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2278         } else {
2279                 foreach my $stylesheet (@stylesheets) {
2280                         next unless $stylesheet;
2281                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2282                 }
2283         }
2284         if (defined $project) {
2285                 printf('<link rel="alternate" title="%s log RSS feed" '.
2286                        'href="%s" type="application/rss+xml" />'."\n",
2287                        esc_param($project), href(action=>"rss"));
2288                 printf('<link rel="alternate" title="%s log Atom feed" '.
2289                        'href="%s" type="application/atom+xml" />'."\n",
2290                        esc_param($project), href(action=>"atom"));
2291         } else {
2292                 printf('<link rel="alternate" title="%s projects list" '.
2293                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
2294                        $site_name, href(project=>undef, action=>"project_index"));
2295                 printf('<link rel="alternate" title="%s projects feeds" '.
2296                        'href="%s" type="text/x-opml"/>'."\n",
2297                        $site_name, href(project=>undef, action=>"opml"));
2298         }
2299         if (defined $favicon) {
2300                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
2301         }
2303         print "</head>\n" .
2304               "<body>\n";
2306         if (-f $site_header) {
2307                 open (my $fd, $site_header);
2308                 print <$fd>;
2309                 close $fd;
2310         }
2312         print "<div class=\"page_header\">\n" .
2313               $cgi->a({-href => esc_url($logo_url),
2314                        -title => $logo_label},
2315                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2316         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2317         if (defined $project) {
2318                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2319                 if (defined $action) {
2320                         print " / $action";
2321                 }
2322                 print "\n";
2323         }
2324         print "</div>\n";
2326         my ($have_search) = gitweb_check_feature('search');
2327         if ((defined $project) && ($have_search)) {
2328                 if (!defined $searchtext) {
2329                         $searchtext = "";
2330                 }
2331                 my $search_hash;
2332                 if (defined $hash_base) {
2333                         $search_hash = $hash_base;
2334                 } elsif (defined $hash) {
2335                         $search_hash = $hash;
2336                 } else {
2337                         $search_hash = "HEAD";
2338                 }
2339                 my $action = $my_uri;
2340                 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2341                 if ($use_pathinfo) {
2342                         $action .= "/$project";
2343                 } else {
2344                         $cgi->param("p", $project);
2345                 }
2346                 $cgi->param("a", "search");
2347                 $cgi->param("h", $search_hash);
2348                 print $cgi->startform(-method => "get", -action => $action) .
2349                       "<div class=\"search\">\n" .
2350                       (!$use_pathinfo && $cgi->hidden(-name => "p") . "\n") .
2351                       $cgi->hidden(-name => "a") . "\n" .
2352                       $cgi->hidden(-name => "h") . "\n" .
2353                       $cgi->popup_menu(-name => 'st', -default => 'commit',
2354                                        -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2355                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2356                       " search:\n",
2357                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2358                       "</div>" .
2359                       $cgi->end_form() . "\n";
2360         }
2363 sub git_footer_html {
2364         print "<div class=\"page_footer\">\n";
2365         if (defined $project) {
2366                 my $descr = git_get_project_description($project);
2367                 if (defined $descr) {
2368                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2369                 }
2370                 print $cgi->a({-href => href(action=>"rss"),
2371                               -class => "rss_logo"}, "RSS") . " ";
2372                 print $cgi->a({-href => href(action=>"atom"),
2373                               -class => "rss_logo"}, "Atom") . "\n";
2374         } else {
2375                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
2376                               -class => "rss_logo"}, "OPML") . " ";
2377                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2378                               -class => "rss_logo"}, "TXT") . "\n";
2379         }
2380         print "</div>\n" ;
2382         if (-f $site_footer) {
2383                 open (my $fd, $site_footer);
2384                 print <$fd>;
2385                 close $fd;
2386         }
2388         print "</body>\n" .
2389               "</html>";
2392 sub die_error {
2393         my $status = shift || "403 Forbidden";
2394         my $error = shift || "Malformed query, file missing or permission denied";
2396         git_header_html($status);
2397         print <<EOF;
2398 <div class="page_body">
2399 <br /><br />
2400 $status - $error
2401 <br />
2402 </div>
2403 EOF
2404         git_footer_html();
2405         exit;
2408 ## ----------------------------------------------------------------------
2409 ## functions printing or outputting HTML: navigation
2411 sub git_print_page_nav {
2412         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2413         $extra = '' if !defined $extra; # pager or formats
2415         my @navs = qw(summary shortlog log commit commitdiff tree);
2416         if ($suppress) {
2417                 @navs = grep { $_ ne $suppress } @navs;
2418         }
2420         my %arg = map { $_ => {action=>$_} } @navs;
2421         if (defined $head) {
2422                 for (qw(commit commitdiff)) {
2423                         $arg{$_}{'hash'} = $head;
2424                 }
2425                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2426                         for (qw(shortlog log)) {
2427                                 $arg{$_}{'hash'} = $head;
2428                         }
2429                 }
2430         }
2431         $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2432         $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2434         print "<div class=\"page_nav\">\n" .
2435                 (join " | ",
2436                  map { $_ eq $current ?
2437                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2438                  } @navs);
2439         print "<br/>\n$extra<br/>\n" .
2440               "</div>\n";
2443 sub format_paging_nav {
2444         my ($action, $hash, $head, $page, $nrevs) = @_;
2445         my $paging_nav;
2448         if ($hash ne $head || $page) {
2449                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2450         } else {
2451                 $paging_nav .= "HEAD";
2452         }
2454         if ($page > 0) {
2455                 $paging_nav .= " &sdot; " .
2456                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
2457                                  -accesskey => "p", -title => "Alt-p"}, "prev");
2458         } else {
2459                 $paging_nav .= " &sdot; prev";
2460         }
2462         if ($nrevs >= (100 * ($page+1)-1)) {
2463                 $paging_nav .= " &sdot; " .
2464                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
2465                                  -accesskey => "n", -title => "Alt-n"}, "next");
2466         } else {
2467                 $paging_nav .= " &sdot; next";
2468         }
2470         return $paging_nav;
2473 ## ......................................................................
2474 ## functions printing or outputting HTML: div
2476 sub git_print_header_div {
2477         my ($action, $title, $hash, $hash_base) = @_;
2478         my %args = ();
2480         $args{'action'} = $action;
2481         $args{'hash'} = $hash if $hash;
2482         $args{'hash_base'} = $hash_base if $hash_base;
2484         print "<div class=\"header\">\n" .
2485               $cgi->a({-href => href(%args), -class => "title"},
2486               $title ? $title : $action) .
2487               "\n</div>\n";
2490 #sub git_print_authorship (\%) {
2491 sub git_print_authorship {
2492         my $co = shift;
2494         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2495         print "<div class=\"author_date\">" .
2496               esc_html($co->{'author_name'}) .
2497               " [$ad{'rfc2822'}";
2498         if ($ad{'hour_local'} < 6) {
2499                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2500                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2501         } else {
2502                 printf(" (%02d:%02d %s)",
2503                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2504         }
2505         print "]</div>\n";
2508 sub git_print_page_path {
2509         my $name = shift;
2510         my $type = shift;
2511         my $hb = shift;
2514         print "<div class=\"page_path\">";
2515         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2516                       -title => 'tree root'}, to_utf8("[$project]"));
2517         print " / ";
2518         if (defined $name) {
2519                 my @dirname = split '/', $name;
2520                 my $basename = pop @dirname;
2521                 my $fullname = '';
2523                 foreach my $dir (@dirname) {
2524                         $fullname .= ($fullname ? '/' : '') . $dir;
2525                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2526                                                      hash_base=>$hb),
2527                                       -title => $fullname}, esc_path($dir));
2528                         print " / ";
2529                 }
2530                 if (defined $type && $type eq 'blob') {
2531                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2532                                                      hash_base=>$hb),
2533                                       -title => $name}, esc_path($basename));
2534                 } elsif (defined $type && $type eq 'tree') {
2535                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2536                                                      hash_base=>$hb),
2537                                       -title => $name}, esc_path($basename));
2538                         print " / ";
2539                 } else {
2540                         print esc_path($basename);
2541                 }
2542         }
2543         print "<br/></div>\n";
2546 # sub git_print_log (\@;%) {
2547 sub git_print_log ($;%) {
2548         my $log = shift;
2549         my %opts = @_;
2551         if ($opts{'-remove_title'}) {
2552                 # remove title, i.e. first line of log
2553                 shift @$log;
2554         }
2555         # remove leading empty lines
2556         while (defined $log->[0] && $log->[0] eq "") {
2557                 shift @$log;
2558         }
2560         # print log
2561         my $signoff = 0;
2562         my $empty = 0;
2563         foreach my $line (@$log) {
2564                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2565                         $signoff = 1;
2566                         $empty = 0;
2567                         if (! $opts{'-remove_signoff'}) {
2568                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2569                                 next;
2570                         } else {
2571                                 # remove signoff lines
2572                                 next;
2573                         }
2574                 } else {
2575                         $signoff = 0;
2576                 }
2578                 # print only one empty line
2579                 # do not print empty line after signoff
2580                 if ($line eq "") {
2581                         next if ($empty || $signoff);
2582                         $empty = 1;
2583                 } else {
2584                         $empty = 0;
2585                 }
2587                 print format_log_line_html($line) . "<br/>\n";
2588         }
2590         if ($opts{'-final_empty_line'}) {
2591                 # end with single empty line
2592                 print "<br/>\n" unless $empty;
2593         }
2596 # return link target (what link points to)
2597 sub git_get_link_target {
2598         my $hash = shift;
2599         my $link_target;
2601         # read link
2602         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2603                 or return;
2604         {
2605                 local $/;
2606                 $link_target = <$fd>;
2607         }
2608         close $fd
2609                 or return;
2611         return $link_target;
2614 # given link target, and the directory (basedir) the link is in,
2615 # return target of link relative to top directory (top tree);
2616 # return undef if it is not possible (including absolute links).
2617 sub normalize_link_target {
2618         my ($link_target, $basedir, $hash_base) = @_;
2620         # we can normalize symlink target only if $hash_base is provided
2621         return unless $hash_base;
2623         # absolute symlinks (beginning with '/') cannot be normalized
2624         return if (substr($link_target, 0, 1) eq '/');
2626         # normalize link target to path from top (root) tree (dir)
2627         my $path;
2628         if ($basedir) {
2629                 $path = $basedir . '/' . $link_target;
2630         } else {
2631                 # we are in top (root) tree (dir)
2632                 $path = $link_target;
2633         }
2635         # remove //, /./, and /../
2636         my @path_parts;
2637         foreach my $part (split('/', $path)) {
2638                 # discard '.' and ''
2639                 next if (!$part || $part eq '.');
2640                 # handle '..'
2641                 if ($part eq '..') {
2642                         if (@path_parts) {
2643                                 pop @path_parts;
2644                         } else {
2645                                 # link leads outside repository (outside top dir)
2646                                 return;
2647                         }
2648                 } else {
2649                         push @path_parts, $part;
2650                 }
2651         }
2652         $path = join('/', @path_parts);
2654         return $path;
2657 # print tree entry (row of git_tree), but without encompassing <tr> element
2658 sub git_print_tree_entry {
2659         my ($t, $basedir, $hash_base, $have_blame) = @_;
2661         my %base_key = ();
2662         $base_key{'hash_base'} = $hash_base if defined $hash_base;
2664         # The format of a table row is: mode list link.  Where mode is
2665         # the mode of the entry, list is the name of the entry, an href,
2666         # and link is the action links of the entry.
2668         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2669         if ($t->{'type'} eq "blob") {
2670                 print "<td class=\"list\">" .
2671                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2672                                                file_name=>"$basedir$t->{'name'}", %base_key),
2673                                 -class => "list"}, esc_path($t->{'name'}));
2674                 if (S_ISLNK(oct $t->{'mode'})) {
2675                         my $link_target = git_get_link_target($t->{'hash'});
2676                         if ($link_target) {
2677                                 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2678                                 if (defined $norm_target) {
2679                                         print " -> " .
2680                                               $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2681                                                                      file_name=>$norm_target),
2682                                                        -title => $norm_target}, esc_path($link_target));
2683                                 } else {
2684                                         print " -> " . esc_path($link_target);
2685                                 }
2686                         }
2687                 }
2688                 print "</td>\n";
2689                 print "<td class=\"link\">";
2690                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2691                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2692                               "blob");
2693                 if ($have_blame) {
2694                         print " | " .
2695                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2696                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
2697                                       "blame");
2698                 }
2699                 if (defined $hash_base) {
2700                         print " | " .
2701                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2702                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2703                                       "history");
2704                 }
2705                 print " | " .
2706                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2707                                                file_name=>"$basedir$t->{'name'}")},
2708                                 "raw");
2709                 print "</td>\n";
2711         } elsif ($t->{'type'} eq "tree") {
2712                 print "<td class=\"list\">";
2713                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2714                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2715                               esc_path($t->{'name'}));
2716                 print "</td>\n";
2717                 print "<td class=\"link\">";
2718                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2719                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2720                               "tree");
2721                 if (defined $hash_base) {
2722                         print " | " .
2723                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2724                                                      file_name=>"$basedir$t->{'name'}")},
2725                                       "history");
2726                 }
2727                 print "</td>\n";
2728         } else {
2729                 # unknown object: we can only present history for it
2730                 # (this includes 'commit' object, i.e. submodule support)
2731                 print "<td class=\"list\">" .
2732                       esc_path($t->{'name'}) .
2733                       "</td>\n";
2734                 print "<td class=\"link\">";
2735                 if (defined $hash_base) {
2736                         print $cgi->a({-href => href(action=>"history",
2737                                                      hash_base=>$hash_base,
2738                                                      file_name=>"$basedir$t->{'name'}")},
2739                                       "history");
2740                 }
2741                 print "</td>\n";
2742         }
2745 ## ......................................................................
2746 ## functions printing large fragments of HTML
2748 sub fill_from_file_info {
2749         my ($diff, @parents) = @_;
2751         $diff->{'from_file'} = [ ];
2752         $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
2753         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2754                 if ($diff->{'status'}[$i] eq 'R' ||
2755                     $diff->{'status'}[$i] eq 'C') {
2756                         $diff->{'from_file'}[$i] =
2757                                 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
2758                 }
2759         }
2761         return $diff;
2764 # parameters can be strings, or references to arrays of strings
2765 sub from_ids_eq {
2766         my ($a, $b) = @_;
2768         if (ref($a) eq "ARRAY" && ref($b) eq "ARRAY" && @$a == @$b) {
2769                 for (my $i = 0; $i < @$a; ++$i) {
2770                         return 0 unless ($a->[$i] eq $b->[$i]);
2771                 }
2772                 return 1;
2773         } elsif (!ref($a) && !ref($b)) {
2774                 return $a eq $b;
2775         } else {
2776                 return 0;
2777         }
2780 sub is_deleted {
2781         my $diffinfo = shift;
2783         return $diffinfo->{'to_id'} eq ('0' x 40);
2786 sub git_difftree_body {
2787         my ($difftree, $hash, @parents) = @_;
2788         my ($parent) = $parents[0];
2789         my ($have_blame) = gitweb_check_feature('blame');
2790         print "<div class=\"list_head\">\n";
2791         if ($#{$difftree} > 10) {
2792                 print(($#{$difftree} + 1) . " files changed:\n");
2793         }
2794         print "</div>\n";
2796         print "<table class=\"" .
2797               (@parents > 1 ? "combined " : "") .
2798               "diff_tree\">\n";
2800         # header only for combined diff in 'commitdiff' view
2801         my $has_header = @parents > 1 && $action eq 'commitdiff';
2802         if ($has_header) {
2803                 # table header
2804                 print "<thead><tr>\n" .
2805                        "<th></th><th></th>\n"; # filename, patchN link
2806                 for (my $i = 0; $i < @parents; $i++) {
2807                         my $par = $parents[$i];
2808                         print "<th>" .
2809                               $cgi->a({-href => href(action=>"commitdiff",
2810                                                      hash=>$hash, hash_parent=>$par),
2811                                        -title => 'commitdiff to parent number ' .
2812                                                   ($i+1) . ': ' . substr($par,0,7)},
2813                                       $i+1) .
2814                               "&nbsp;</th>\n";
2815                 }
2816                 print "</tr></thead>\n<tbody>\n";
2817         }
2819         my $alternate = 1;
2820         my $patchno = 0;
2821         foreach my $line (@{$difftree}) {
2822                 my $diff;
2823                 if (ref($line) eq "HASH") {
2824                         # pre-parsed (or generated by hand)
2825                         $diff = $line;
2826                 } else {
2827                         $diff = parse_difftree_raw_line($line);
2828                 }
2830                 if ($alternate) {
2831                         print "<tr class=\"dark\">\n";
2832                 } else {
2833                         print "<tr class=\"light\">\n";
2834                 }
2835                 $alternate ^= 1;
2837                 if (exists $diff->{'nparents'}) { # combined diff
2839                         fill_from_file_info($diff, @parents)
2840                                 unless exists $diff->{'from_file'};
2842                         if (!is_deleted($diff)) {
2843                                 # file exists in the result (child) commit
2844                                 print "<td>" .
2845                                       $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2846                                                              file_name=>$diff->{'to_file'},
2847                                                              hash_base=>$hash),
2848                                               -class => "list"}, esc_path($diff->{'to_file'})) .
2849                                       "</td>\n";
2850                         } else {
2851                                 print "<td>" .
2852                                       esc_path($diff->{'to_file'}) .
2853                                       "</td>\n";
2854                         }
2856                         if ($action eq 'commitdiff') {
2857                                 # link to patch
2858                                 $patchno++;
2859                                 print "<td class=\"link\">" .
2860                                       $cgi->a({-href => "#patch$patchno"}, "patch") .
2861                                       " | " .
2862                                       "</td>\n";
2863                         }
2865                         my $has_history = 0;
2866                         my $not_deleted = 0;
2867                         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2868                                 my $hash_parent = $parents[$i];
2869                                 my $from_hash = $diff->{'from_id'}[$i];
2870                                 my $from_path = $diff->{'from_file'}[$i];
2871                                 my $status = $diff->{'status'}[$i];
2873                                 $has_history ||= ($status ne 'A');
2874                                 $not_deleted ||= ($status ne 'D');
2876                                 if ($status eq 'A') {
2877                                         print "<td  class=\"link\" align=\"right\"> | </td>\n";
2878                                 } elsif ($status eq 'D') {
2879                                         print "<td class=\"link\">" .
2880                                               $cgi->a({-href => href(action=>"blob",
2881                                                                      hash_base=>$hash,
2882                                                                      hash=>$from_hash,
2883                                                                      file_name=>$from_path)},
2884                                                       "blob" . ($i+1)) .
2885                                               " | </td>\n";
2886                                 } else {
2887                                         if ($diff->{'to_id'} eq $from_hash) {
2888                                                 print "<td class=\"link nochange\">";
2889                                         } else {
2890                                                 print "<td class=\"link\">";
2891                                         }
2892                                         print $cgi->a({-href => href(action=>"blobdiff",
2893                                                                      hash=>$diff->{'to_id'},
2894                                                                      hash_parent=>$from_hash,
2895                                                                      hash_base=>$hash,
2896                                                                      hash_parent_base=>$hash_parent,
2897                                                                      file_name=>$diff->{'to_file'},
2898                                                                      file_parent=>$from_path)},
2899                                                       "diff" . ($i+1)) .
2900                                               " | </td>\n";
2901                                 }
2902                         }
2904                         print "<td class=\"link\">";
2905                         if ($not_deleted) {
2906                                 print $cgi->a({-href => href(action=>"blob",
2907                                                              hash=>$diff->{'to_id'},
2908                                                              file_name=>$diff->{'to_file'},
2909                                                              hash_base=>$hash)},
2910                                               "blob");
2911                                 print " | " if ($has_history);
2912                         }
2913                         if ($has_history) {
2914                                 print $cgi->a({-href => href(action=>"history",
2915                                                              file_name=>$diff->{'to_file'},
2916                                                              hash_base=>$hash)},
2917                                               "history");
2918                         }
2919                         print "</td>\n";
2921                         print "</tr>\n";
2922                         next; # instead of 'else' clause, to avoid extra indent
2923                 }
2924                 # else ordinary diff
2926                 my ($to_mode_oct, $to_mode_str, $to_file_type);
2927                 my ($from_mode_oct, $from_mode_str, $from_file_type);
2928                 if ($diff->{'to_mode'} ne ('0' x 6)) {
2929                         $to_mode_oct = oct $diff->{'to_mode'};
2930                         if (S_ISREG($to_mode_oct)) { # only for regular file
2931                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2932                         }
2933                         $to_file_type = file_type($diff->{'to_mode'});
2934                 }
2935                 if ($diff->{'from_mode'} ne ('0' x 6)) {
2936                         $from_mode_oct = oct $diff->{'from_mode'};
2937                         if (S_ISREG($to_mode_oct)) { # only for regular file
2938                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2939                         }
2940                         $from_file_type = file_type($diff->{'from_mode'});
2941                 }
2943                 if ($diff->{'status'} eq "A") { # created
2944                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2945                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2946                         $mode_chng   .= "]</span>";
2947                         print "<td>";
2948                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2949                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
2950                                       -class => "list"}, esc_path($diff->{'file'}));
2951                         print "</td>\n";
2952                         print "<td>$mode_chng</td>\n";
2953                         print "<td class=\"link\">";
2954                         if ($action eq 'commitdiff') {
2955                                 # link to patch
2956                                 $patchno++;
2957                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2958                                 print " | ";
2959                         }
2960                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2961                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
2962                                       "blob");
2963                         print "</td>\n";
2965                 } elsif ($diff->{'status'} eq "D") { # deleted
2966                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2967                         print "<td>";
2968                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2969                                                      hash_base=>$parent, file_name=>$diff->{'file'}),
2970                                        -class => "list"}, esc_path($diff->{'file'}));
2971                         print "</td>\n";
2972                         print "<td>$mode_chng</td>\n";
2973                         print "<td class=\"link\">";
2974                         if ($action eq 'commitdiff') {
2975                                 # link to patch
2976                                 $patchno++;
2977                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2978                                 print " | ";
2979                         }
2980                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
2981                                                      hash_base=>$parent, file_name=>$diff->{'file'})},
2982                                       "blob") . " | ";
2983                         if ($have_blame) {
2984                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2985                                                              file_name=>$diff->{'file'})},
2986                                               "blame") . " | ";
2987                         }
2988                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2989                                                      file_name=>$diff->{'file'})},
2990                                       "history");
2991                         print "</td>\n";
2993                 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
2994                         my $mode_chnge = "";
2995                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
2996                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2997                                 if ($from_file_type ne $to_file_type) {
2998                                         $mode_chnge .= " from $from_file_type to $to_file_type";
2999                                 }
3000                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3001                                         if ($from_mode_str && $to_mode_str) {
3002                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3003                                         } elsif ($to_mode_str) {
3004                                                 $mode_chnge .= " mode: $to_mode_str";
3005                                         }
3006                                 }
3007                                 $mode_chnge .= "]</span>\n";
3008                         }
3009                         print "<td>";
3010                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3011                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
3012                                       -class => "list"}, esc_path($diff->{'file'}));
3013                         print "</td>\n";
3014                         print "<td>$mode_chnge</td>\n";
3015                         print "<td class=\"link\">";
3016                         if ($action eq 'commitdiff') {
3017                                 # link to patch
3018                                 $patchno++;
3019                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3020                                       " | ";
3021                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3022                                 # "commit" view and modified file (not onlu mode changed)
3023                                 print $cgi->a({-href => href(action=>"blobdiff",
3024                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3025                                                              hash_base=>$hash, hash_parent_base=>$parent,
3026                                                              file_name=>$diff->{'file'})},
3027                                               "diff") .
3028                                       " | ";
3029                         }
3030                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3031                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
3032                                        "blob") . " | ";
3033                         if ($have_blame) {
3034                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3035                                                              file_name=>$diff->{'file'})},
3036                                               "blame") . " | ";
3037                         }
3038                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3039                                                      file_name=>$diff->{'file'})},
3040                                       "history");
3041                         print "</td>\n";
3043                 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3044                         my %status_name = ('R' => 'moved', 'C' => 'copied');
3045                         my $nstatus = $status_name{$diff->{'status'}};
3046                         my $mode_chng = "";
3047                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3048                                 # mode also for directories, so we cannot use $to_mode_str
3049                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3050                         }
3051                         print "<td>" .
3052                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3053                                                      hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3054                                       -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3055                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3056                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3057                                                      hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3058                                       -class => "list"}, esc_path($diff->{'from_file'})) .
3059                               " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3060                               "<td class=\"link\">";
3061                         if ($action eq 'commitdiff') {
3062                                 # link to patch
3063                                 $patchno++;
3064                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3065                                       " | ";
3066                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3067                                 # "commit" view and modified file (not only pure rename or copy)
3068                                 print $cgi->a({-href => href(action=>"blobdiff",
3069                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3070                                                              hash_base=>$hash, hash_parent_base=>$parent,
3071                                                              file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3072                                               "diff") .
3073                                       " | ";
3074                         }
3075                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3076                                                      hash_base=>$parent, file_name=>$diff->{'to_file'})},
3077                                       "blob") . " | ";
3078                         if ($have_blame) {
3079                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3080                                                              file_name=>$diff->{'to_file'})},
3081                                               "blame") . " | ";
3082                         }
3083                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3084                                                     file_name=>$diff->{'to_file'})},
3085                                       "history");
3086                         print "</td>\n";
3088                 } # we should not encounter Unmerged (U) or Unknown (X) status
3089                 print "</tr>\n";
3090         }
3091         print "</tbody>" if $has_header;
3092         print "</table>\n";
3095 sub git_patchset_body {
3096         my ($fd, $difftree, $hash, @hash_parents) = @_;
3097         my ($hash_parent) = $hash_parents[0];
3099         my $patch_idx = 0;
3100         my $patch_number = 0;
3101         my $patch_line;
3102         my $diffinfo;
3103         my (%from, %to);
3105         print "<div class=\"patchset\">\n";
3107         # skip to first patch
3108         while ($patch_line = <$fd>) {
3109                 chomp $patch_line;
3111                 last if ($patch_line =~ m/^diff /);
3112         }
3114  PATCH:
3115         while ($patch_line) {
3116                 my @diff_header;
3117                 my ($from_id, $to_id);
3119                 # git diff header
3120                 #assert($patch_line =~ m/^diff /) if DEBUG;
3121                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3122                 $patch_number++;
3123                 push @diff_header, $patch_line;
3125                 # extended diff header
3126         EXTENDED_HEADER:
3127                 while ($patch_line = <$fd>) {
3128                         chomp $patch_line;
3130                         last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3132                         if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
3133                                 $from_id = $1;
3134                                 $to_id   = $2;
3135                         } elsif ($patch_line =~ m/^index ((?:[0-9a-fA-F]{40},)+[0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
3136                                 $from_id = [ split(',', $1) ];
3137                                 $to_id   = $2;
3138                         }
3140                         push @diff_header, $patch_line;
3141                 }
3142                 my $last_patch_line = $patch_line;
3144                 # check if current patch belong to current raw line
3145                 # and parse raw git-diff line if needed
3146                 if (defined $diffinfo &&
3147                     defined $from_id && defined $to_id &&
3148                     from_ids_eq($diffinfo->{'from_id'}, $from_id) &&
3149                     $diffinfo->{'to_id'} eq $to_id) {
3150                         # this is continuation of a split patch
3151                         print "<div class=\"patch cont\">\n";
3152                 } else {
3153                         # advance raw git-diff output if needed
3154                         $patch_idx++ if defined $diffinfo;
3156                         # compact combined diff output can have some patches skipped
3157                         # find which patch (using pathname of result) we are at now
3158                         my $to_name;
3159                         if ($diff_header[0] =~ m!^diff --cc "?(.*)"?$!) {
3160                                 $to_name = $1;
3161                         }
3163                         do {
3164                                 # read and prepare patch information
3165                                 if (ref($difftree->[$patch_idx]) eq "HASH") {
3166                                         # pre-parsed (or generated by hand)
3167                                         $diffinfo = $difftree->[$patch_idx];
3168                                 } else {
3169                                         $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
3170                                 }
3172                                 # check if current raw line has no patch (it got simplified)
3173                                 if (defined $to_name && $to_name ne $diffinfo->{'to_file'}) {
3174                                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3175                                               format_diff_cc_simplified($diffinfo, @hash_parents) .
3176                                               "</div>\n";  # class="patch"
3178                                         $patch_idx++;
3179                                         $patch_number++;
3180                                 }
3181                         } until (!defined $to_name || $to_name eq $diffinfo->{'to_file'} ||
3182                                  $patch_idx > $#$difftree);
3183                         # modifies %from, %to hashes
3184                         parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3185                         if ($diffinfo->{'nparents'}) {
3186                                 # combined diff
3187                                 $from{'file'} = [];
3188                                 $from{'href'} = [];
3189                                 fill_from_file_info($diffinfo, @hash_parents)
3190                                         unless exists $diffinfo->{'from_file'};
3191                                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3192                                         $from{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
3193                                         if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3194                                                 $from{'href'}[$i] = href(action=>"blob",
3195                                                                          hash_base=>$hash_parents[$i],
3196                                                                          hash=>$diffinfo->{'from_id'}[$i],
3197                                                                          file_name=>$from{'file'}[$i]);
3198                                         } else {
3199                                                 $from{'href'}[$i] = undef;
3200                                         }
3201                                 }
3202                         } else {
3203                                 $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
3204                                 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3205                                         $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3206                                                              hash=>$diffinfo->{'from_id'},
3207                                                              file_name=>$from{'file'});
3208                                 } else {
3209                                         delete $from{'href'};
3210                                 }
3211                         }
3213                         $to{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
3214                         if (!is_deleted($diffinfo)) { # file exists in result
3215                                 $to{'href'} = href(action=>"blob", hash_base=>$hash,
3216                                                    hash=>$diffinfo->{'to_id'},
3217                                                    file_name=>$to{'file'});
3218                         } else {
3219                                 delete $to{'href'};
3220                         }
3221                         # this is first patch for raw difftree line with $patch_idx index
3222                         # we index @$difftree array from 0, but number patches from 1
3223                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3224                 }
3226                 # print "git diff" header
3227                 $patch_line = shift @diff_header;
3228                 print format_git_diff_header_line($patch_line, $diffinfo,
3229                                                   \%from, \%to);
3231                 # print extended diff header
3232                 print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
3233         EXTENDED_HEADER:
3234                 foreach $patch_line (@diff_header) {
3235                         print format_extended_diff_header_line($patch_line, $diffinfo,
3236                                                                \%from, \%to);
3237                 }
3238                 print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
3240                 # from-file/to-file diff header
3241                 $patch_line = $last_patch_line;
3242                 if (! $patch_line) {
3243                         print "</div>\n"; # class="patch"
3244                         last PATCH;
3245                 }
3246                 next PATCH if ($patch_line =~ m/^diff /);
3247                 #assert($patch_line =~ m/^---/) if DEBUG;
3248                 #assert($patch_line eq $last_patch_line) if DEBUG;
3250                 $patch_line = <$fd>;
3251                 chomp $patch_line;
3252                 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3254                 print format_diff_from_to_header($last_patch_line, $patch_line,
3255                                                  $diffinfo, \%from, \%to,
3256                                                  @hash_parents);
3258                 # the patch itself
3259         LINE:
3260                 while ($patch_line = <$fd>) {
3261                         chomp $patch_line;
3263                         next PATCH if ($patch_line =~ m/^diff /);
3265                         print format_diff_line($patch_line, \%from, \%to);
3266                 }
3268         } continue {
3269                 print "</div>\n"; # class="patch"
3270         }
3272         # for compact combined (--cc) format, with chunk and patch simpliciaction
3273         # patchset might be empty, but there might be unprocessed raw lines
3274         for ($patch_idx++ if $patch_number > 0;
3275              $patch_idx < @$difftree;
3276              $patch_idx++) {
3277                 # read and prepare patch information
3278                 if (ref($difftree->[$patch_idx]) eq "HASH") {
3279                         # pre-parsed (or generated by hand)
3280                         $diffinfo = $difftree->[$patch_idx];
3281                 } else {
3282                         $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
3283                 }
3285                 # generate anchor for "patch" links in difftree / whatchanged part
3286                 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3287                       format_diff_cc_simplified($diffinfo, @hash_parents) .
3288                       "</div>\n";  # class="patch"
3290                 $patch_number++;
3291         }
3293         if ($patch_number == 0) {
3294                 if (@hash_parents > 1) {
3295                         print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3296                 } else {
3297                         print "<div class=\"diff nodifferences\">No differences found</div>\n";
3298                 }
3299         }
3301         print "</div>\n"; # class="patchset"
3304 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3306 sub git_project_list_body {
3307         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3309         my ($check_forks) = gitweb_check_feature('forks');
3311         my @projects;
3312         foreach my $pr (@$projlist) {
3313                 my (@aa) = git_get_last_activity($pr->{'path'});
3314                 unless (@aa) {
3315                         next;
3316                 }
3317                 ($pr->{'age'}, $pr->{'age_string'}) = @aa;
3318                 if (!defined $pr->{'descr'}) {
3319                         my $descr = git_get_project_description($pr->{'path'}) || "";
3320                         $pr->{'descr_long'} = to_utf8($descr);
3321                         $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3322                 }
3323                 if (!defined $pr->{'owner'}) {
3324                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3325                 }
3326                 if ($check_forks) {
3327                         my $pname = $pr->{'path'};
3328                         if (($pname =~ s/\.git$//) &&
3329                             ($pname !~ /\/$/) &&
3330                             (-d "$projectroot/$pname")) {
3331                                 $pr->{'forks'} = "-d $projectroot/$pname";
3332                         }
3333                         else {
3334                                 $pr->{'forks'} = 0;
3335                         }
3336                 }
3337                 push @projects, $pr;
3338         }
3340         $order ||= $default_projects_order;
3341         $from = 0 unless defined $from;
3342         $to = $#projects if (!defined $to || $#projects < $to);
3344         print "<table class=\"project_list\">\n";
3345         unless ($no_header) {
3346                 print "<tr>\n";
3347                 if ($check_forks) {
3348                         print "<th></th>\n";
3349                 }
3350                 if ($order eq "project") {
3351                         @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
3352                         print "<th>Project</th>\n";
3353                 } else {
3354                         print "<th>" .
3355                               $cgi->a({-href => href(project=>undef, order=>'project'),
3356                                        -class => "header"}, "Project") .
3357                               "</th>\n";
3358                 }
3359                 if ($order eq "descr") {
3360                         @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
3361                         print "<th>Description</th>\n";
3362                 } else {
3363                         print "<th>" .
3364                               $cgi->a({-href => href(project=>undef, order=>'descr'),
3365                                        -class => "header"}, "Description") .
3366                               "</th>\n";
3367                 }
3368                 if ($order eq "owner") {
3369                         @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
3370                         print "<th>Owner</th>\n";
3371                 } else {
3372                         print "<th>" .
3373                               $cgi->a({-href => href(project=>undef, order=>'owner'),
3374                                        -class => "header"}, "Owner") .
3375                               "</th>\n";
3376                 }
3377                 if ($order eq "age") {
3378                         @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
3379                         print "<th>Last Change</th>\n";
3380                 } else {
3381                         print "<th>" .
3382                               $cgi->a({-href => href(project=>undef, order=>'age'),
3383                                        -class => "header"}, "Last Change") .
3384                               "</th>\n";
3385                 }
3386                 print "<th></th>\n" .
3387                       "</tr>\n";
3388         }
3389         my $alternate = 1;
3390         for (my $i = $from; $i <= $to; $i++) {
3391                 my $pr = $projects[$i];
3392                 if ($alternate) {
3393                         print "<tr class=\"dark\">\n";
3394                 } else {
3395                         print "<tr class=\"light\">\n";
3396                 }
3397                 $alternate ^= 1;
3398                 if ($check_forks) {
3399                         print "<td>";
3400                         if ($pr->{'forks'}) {
3401                                 print "<!-- $pr->{'forks'} -->\n";
3402                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3403                         }
3404                         print "</td>\n";
3405                 }
3406                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3407                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3408                       "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3409                                         -class => "list", -title => $pr->{'descr_long'}},
3410                                         esc_html($pr->{'descr'})) . "</td>\n" .
3411                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
3412                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3413                       (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3414                       "<td class=\"link\">" .
3415                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
3416                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3417                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3418                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3419                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3420                       "</td>\n" .
3421                       "</tr>\n";
3422         }
3423         if (defined $extra) {
3424                 print "<tr>\n";
3425                 if ($check_forks) {
3426                         print "<td></td>\n";
3427                 }
3428                 print "<td colspan=\"5\">$extra</td>\n" .
3429                       "</tr>\n";
3430         }
3431         print "</table>\n";
3434 sub git_shortlog_body {
3435         # uses global variable $project
3436         my ($commitlist, $from, $to, $refs, $extra) = @_;
3438         $from = 0 unless defined $from;
3439         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3441         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
3442         my $alternate = 1;
3443         for (my $i = $from; $i <= $to; $i++) {
3444                 my %co = %{$commitlist->[$i]};
3445                 my $commit = $co{'id'};
3446                 my $ref = format_ref_marker($refs, $commit);
3447                 if ($alternate) {
3448                         print "<tr class=\"dark\">\n";
3449                 } else {
3450                         print "<tr class=\"light\">\n";
3451                 }
3452                 $alternate ^= 1;
3453                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3454                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3455                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
3456                       "<td>";
3457                 print format_subject_html($co{'title'}, $co{'title_short'},
3458                                           href(action=>"commit", hash=>$commit), $ref);
3459                 print "</td>\n" .
3460                       "<td class=\"link\">" .
3461                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3462                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3463                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3464                 my $snapshot_links = format_snapshot_links($commit);
3465                 if (defined $snapshot_links) {
3466                         print " | " . $snapshot_links;
3467                 }
3468                 print "</td>\n" .
3469                       "</tr>\n";
3470         }
3471         if (defined $extra) {
3472                 print "<tr>\n" .
3473                       "<td colspan=\"4\">$extra</td>\n" .
3474                       "</tr>\n";
3475         }
3476         print "</table>\n";
3479 sub git_history_body {
3480         # Warning: assumes constant type (blob or tree) during history
3481         my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3483         $from = 0 unless defined $from;
3484         $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3486         print "<table class=\"history\" cellspacing=\"0\">\n";
3487         my $alternate = 1;
3488         for (my $i = $from; $i <= $to; $i++) {
3489                 my %co = %{$commitlist->[$i]};
3490                 if (!%co) {
3491                         next;
3492                 }
3493                 my $commit = $co{'id'};
3495                 my $ref = format_ref_marker($refs, $commit);
3497                 if ($alternate) {
3498                         print "<tr class=\"dark\">\n";
3499                 } else {
3500                         print "<tr class=\"light\">\n";
3501                 }
3502                 $alternate ^= 1;
3503                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3504                       # shortlog uses      chop_str($co{'author_name'}, 10)
3505                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
3506                       "<td>";
3507                 # originally git_history used chop_str($co{'title'}, 50)
3508                 print format_subject_html($co{'title'}, $co{'title_short'},
3509                                           href(action=>"commit", hash=>$commit), $ref);
3510                 print "</td>\n" .
3511                       "<td class=\"link\">" .
3512                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3513                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3515                 if ($ftype eq 'blob') {
3516                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3517                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
3518                         if (defined $blob_current && defined $blob_parent &&
3519                                         $blob_current ne $blob_parent) {
3520                                 print " | " .
3521                                         $cgi->a({-href => href(action=>"blobdiff",
3522                                                                hash=>$blob_current, hash_parent=>$blob_parent,
3523                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
3524                                                                file_name=>$file_name)},
3525                                                 "diff to current");
3526                         }
3527                 }
3528                 print "</td>\n" .
3529                       "</tr>\n";
3530         }
3531         if (defined $extra) {
3532                 print "<tr>\n" .
3533                       "<td colspan=\"4\">$extra</td>\n" .
3534                       "</tr>\n";
3535         }
3536         print "</table>\n";
3539 sub git_tags_body {
3540         # uses global variable $project
3541         my ($taglist, $from, $to, $extra) = @_;
3542         $from = 0 unless defined $from;
3543         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3545         print "<table class=\"tags\" cellspacing=\"0\">\n";
3546         my $alternate = 1;
3547         for (my $i = $from; $i <= $to; $i++) {
3548                 my $entry = $taglist->[$i];
3549                 my %tag = %$entry;
3550                 my $comment = $tag{'subject'};
3551                 my $comment_short;
3552                 if (defined $comment) {
3553                         $comment_short = chop_str($comment, 30, 5);
3554                 }
3555                 if ($alternate) {
3556                         print "<tr class=\"dark\">\n";
3557                 } else {
3558                         print "<tr class=\"light\">\n";
3559                 }
3560                 $alternate ^= 1;
3561                 if (defined $tag{'age'}) {
3562                         print "<td><i>$tag{'age'}</i></td>\n";
3563                 } else {
3564                         print "<td></td>\n";
3565                 }
3566                 print "<td>" .
3567                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3568                                -class => "list name"}, esc_html($tag{'name'})) .
3569                       "</td>\n" .
3570                       "<td>";
3571                 if (defined $comment) {
3572                         print format_subject_html($comment, $comment_short,
3573                                                   href(action=>"tag", hash=>$tag{'id'}));
3574                 }
3575                 print "</td>\n" .
3576                       "<td class=\"selflink\">";
3577                 if ($tag{'type'} eq "tag") {
3578                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3579                 } else {
3580                         print "&nbsp;";
3581                 }
3582                 print "</td>\n" .
3583                       "<td class=\"link\">" . " | " .
3584                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3585                 if ($tag{'reftype'} eq "commit") {
3586                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
3587                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
3588                 } elsif ($tag{'reftype'} eq "blob") {
3589                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3590                 }
3591                 print "</td>\n" .
3592                       "</tr>";
3593         }
3594         if (defined $extra) {
3595                 print "<tr>\n" .
3596                       "<td colspan=\"5\">$extra</td>\n" .
3597                       "</tr>\n";
3598         }
3599         print "</table>\n";
3602 sub git_heads_body {
3603         # uses global variable $project
3604         my ($headlist, $head, $from, $to, $extra) = @_;
3605         $from = 0 unless defined $from;
3606         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3608         print "<table class=\"heads\" cellspacing=\"0\">\n";
3609         my $alternate = 1;
3610         for (my $i = $from; $i <= $to; $i++) {
3611                 my $entry = $headlist->[$i];
3612                 my %ref = %$entry;
3613                 my $curr = $ref{'id'} eq $head;
3614                 if ($alternate) {
3615                         print "<tr class=\"dark\">\n";
3616                 } else {
3617                         print "<tr class=\"light\">\n";
3618                 }
3619                 $alternate ^= 1;
3620                 print "<td><i>$ref{'age'}</i></td>\n" .
3621                       ($curr ? "<td class=\"current_head\">" : "<td>") .
3622                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
3623                                -class => "list name"},esc_html($ref{'name'})) .
3624                       "</td>\n" .
3625                       "<td class=\"link\">" .
3626                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
3627                       $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
3628                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
3629                       "</td>\n" .
3630                       "</tr>";
3631         }
3632         if (defined $extra) {
3633                 print "<tr>\n" .
3634                       "<td colspan=\"3\">$extra</td>\n" .
3635                       "</tr>\n";
3636         }
3637         print "</table>\n";
3640 sub git_search_grep_body {
3641         my ($commitlist, $from, $to, $extra) = @_;
3642         $from = 0 unless defined $from;
3643         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3645         print "<table class=\"grep\" cellspacing=\"0\">\n";
3646         my $alternate = 1;
3647         for (my $i = $from; $i <= $to; $i++) {
3648                 my %co = %{$commitlist->[$i]};
3649                 if (!%co) {
3650                         next;
3651                 }
3652                 my $commit = $co{'id'};
3653                 if ($alternate) {
3654                         print "<tr class=\"dark\">\n";
3655                 } else {
3656                         print "<tr class=\"light\">\n";
3657                 }
3658                 $alternate ^= 1;
3659                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3660                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3661                       "<td>" .
3662                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3663                                esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3664                 my $comment = $co{'comment'};
3665                 foreach my $line (@$comment) {
3666                         if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
3667                                 my $lead = esc_html($1) || "";
3668                                 $lead = chop_str($lead, 30, 10);
3669                                 my $match = esc_html($2) || "";
3670                                 my $trail = esc_html($3) || "";
3671                                 $trail = chop_str($trail, 30, 10);
3672                                 my $text = "$lead<span class=\"match\">$match</span>$trail";
3673                                 print chop_str($text, 80, 5) . "<br/>\n";
3674                         }
3675                 }
3676                 print "</td>\n" .
3677                       "<td class=\"link\">" .
3678                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3679                       " | " .
3680                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3681                 print "</td>\n" .
3682                       "</tr>\n";
3683         }
3684         if (defined $extra) {
3685                 print "<tr>\n" .
3686                       "<td colspan=\"3\">$extra</td>\n" .
3687                       "</tr>\n";
3688         }
3689         print "</table>\n";
3692 ## ======================================================================
3693 ## ======================================================================
3694 ## actions
3696 sub git_project_list {
3697         my $order = $cgi->param('o');
3698         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3699                 die_error(undef, "Unknown order parameter");
3700         }
3702         my @list = git_get_projects_list();
3703         if (!@list) {
3704                 die_error(undef, "No projects found");
3705         }
3707         git_header_html();
3708         if (-f $home_text) {
3709                 print "<div class=\"index_include\">\n";
3710                 open (my $fd, $home_text);
3711                 print <$fd>;
3712                 close $fd;
3713                 print "</div>\n";
3714         }
3715         git_project_list_body(\@list, $order);
3716         git_footer_html();
3719 sub git_forks {
3720         my $order = $cgi->param('o');
3721         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3722                 die_error(undef, "Unknown order parameter");
3723         }
3725         my @list = git_get_projects_list($project);
3726         if (!@list) {
3727                 die_error(undef, "No forks found");
3728         }
3730         git_header_html();
3731         git_print_page_nav('','');
3732         git_print_header_div('summary', "$project forks");
3733         git_project_list_body(\@list, $order);
3734         git_footer_html();
3737 sub git_project_index {
3738         my @projects = git_get_projects_list($project);
3740         print $cgi->header(
3741                 -type => 'text/plain',
3742                 -charset => 'utf-8',
3743                 -content_disposition => 'inline; filename="index.aux"');
3745         foreach my $pr (@projects) {
3746                 if (!exists $pr->{'owner'}) {
3747                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
3748                 }
3750                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3751                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3752                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3753                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3754                 $path  =~ s/ /\+/g;
3755                 $owner =~ s/ /\+/g;
3757                 print "$path $owner\n";
3758         }
3761 sub git_summary {
3762         my $descr = git_get_project_description($project) || "none";
3763         my %co = parse_commit("HEAD");
3764         my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
3765         my $head = $co{'id'};
3767         my $owner = git_get_project_owner($project);
3769         my $refs = git_get_references();
3770         # These get_*_list functions return one more to allow us to see if
3771         # there are more ...
3772         my @taglist  = git_get_tags_list(16);
3773         my @headlist = git_get_heads_list(16);
3774         my @forklist;
3775         my ($check_forks) = gitweb_check_feature('forks');
3777         if ($check_forks) {
3778                 @forklist = git_get_projects_list($project);
3779         }
3781         git_header_html();
3782         git_print_page_nav('summary','', $head);
3784         print "<div class=\"title\">&nbsp;</div>\n";
3785         print "<table cellspacing=\"0\">\n" .
3786               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3787               "<tr><td>owner</td><td>$owner</td></tr>\n";
3788         if (defined $cd{'rfc2822'}) {
3789                 print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3790         }
3792         # use per project git URL list in $projectroot/$project/cloneurl
3793         # or make project git URL from git base URL and project name
3794         my $url_tag = "URL";
3795         my @url_list = git_get_project_url_list($project);
3796         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3797         foreach my $git_url (@url_list) {
3798                 next unless $git_url;
3799                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3800                 $url_tag = "";
3801         }
3802         print "</table>\n";
3804         if (-s "$projectroot/$project/README.html") {
3805                 if (open my $fd, "$projectroot/$project/README.html") {
3806                         print "<div class=\"title\">readme</div>\n";
3807                         print $_ while (<$fd>);
3808                         close $fd;
3809                 }
3810         }
3812         # we need to request one more than 16 (0..15) to check if
3813         # those 16 are all
3814         my @commitlist = $head ? parse_commits($head, 17) : ();
3815         if (@commitlist) {
3816                 git_print_header_div('shortlog');
3817                 git_shortlog_body(\@commitlist, 0, 15, $refs,
3818                                   $#commitlist <=  15 ? undef :
3819                                   $cgi->a({-href => href(action=>"shortlog")}, "..."));
3820         }
3822         if (@taglist) {
3823                 git_print_header_div('tags');
3824                 git_tags_body(\@taglist, 0, 15,
3825                               $#taglist <=  15 ? undef :
3826                               $cgi->a({-href => href(action=>"tags")}, "..."));
3827         }
3829         if (@headlist) {
3830                 git_print_header_div('heads');
3831                 git_heads_body(\@headlist, $head, 0, 15,
3832                                $#headlist <= 15 ? undef :
3833                                $cgi->a({-href => href(action=>"heads")}, "..."));
3834         }
3836         if (@forklist) {
3837                 git_print_header_div('forks');
3838                 git_project_list_body(\@forklist, undef, 0, 15,
3839                                       $#forklist <= 15 ? undef :
3840                                       $cgi->a({-href => href(action=>"forks")}, "..."),
3841                                       'noheader');
3842         }
3844         git_footer_html();
3847 sub git_tag {
3848         my $head = git_get_head_hash($project);
3849         git_header_html();
3850         git_print_page_nav('','', $head,undef,$head);
3851         my %tag = parse_tag($hash);
3853         if (! %tag) {
3854                 die_error(undef, "Unknown tag object");
3855         }
3857         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3858         print "<div class=\"title_text\">\n" .
3859               "<table cellspacing=\"0\">\n" .
3860               "<tr>\n" .
3861               "<td>object</td>\n" .
3862               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3863                                $tag{'object'}) . "</td>\n" .
3864               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3865                                               $tag{'type'}) . "</td>\n" .
3866               "</tr>\n";
3867         if (defined($tag{'author'})) {
3868                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3869                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3870                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
3871                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3872                         "</td></tr>\n";
3873         }
3874         print "</table>\n\n" .
3875               "</div>\n";
3876         print "<div class=\"page_body\">";
3877         my $comment = $tag{'comment'};
3878         foreach my $line (@$comment) {
3879                 chomp $line;
3880                 print esc_html($line, -nbsp=>1) . "<br/>\n";
3881         }
3882         print "</div>\n";
3883         git_footer_html();
3886 sub git_blame2 {
3887         my $fd;
3888         my $ftype;
3890         my ($have_blame) = gitweb_check_feature('blame');
3891         if (!$have_blame) {
3892                 die_error('403 Permission denied', "Permission denied");
3893         }
3894         die_error('404 Not Found', "File name not defined") if (!$file_name);
3895         $hash_base ||= git_get_head_hash($project);
3896         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3897         my %co = parse_commit($hash_base)
3898                 or die_error(undef, "Reading commit failed");
3899         if (!defined $hash) {
3900                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3901                         or die_error(undef, "Error looking up file");
3902         }
3903         $ftype = git_get_type($hash);
3904         if ($ftype !~ "blob") {
3905                 die_error('400 Bad Request', "Object is not a blob");
3906         }
3907         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3908               $file_name, $hash_base)
3909                 or die_error(undef, "Open git-blame failed");
3910         git_header_html();
3911         my $formats_nav =
3912                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3913                         "blob") .
3914                 " | " .
3915                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3916                         "history") .
3917                 " | " .
3918                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3919                         "HEAD");
3920         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3921         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3922         git_print_page_path($file_name, $ftype, $hash_base);
3923         my @rev_color = (qw(light2 dark2));
3924         my $num_colors = scalar(@rev_color);
3925         my $current_color = 0;
3926         my $last_rev;
3927         print <<HTML;
3928 <div class="page_body">
3929 <table class="blame">
3930 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3931 HTML
3932         my %metainfo = ();
3933         while (1) {
3934                 $_ = <$fd>;
3935                 last unless defined $_;
3936                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
3937                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3938                 if (!exists $metainfo{$full_rev}) {
3939                         $metainfo{$full_rev} = {};
3940                 }
3941                 my $meta = $metainfo{$full_rev};
3942                 while (<$fd>) {
3943                         last if (s/^\t//);
3944                         if (/^(\S+) (.*)$/) {
3945                                 $meta->{$1} = $2;
3946                         }
3947                 }
3948                 my $data = $_;
3949                 chomp $data;
3950                 my $rev = substr($full_rev, 0, 8);
3951                 my $author = $meta->{'author'};
3952                 my %date = parse_date($meta->{'author-time'},
3953                                       $meta->{'author-tz'});
3954                 my $date = $date{'iso-tz'};
3955                 if ($group_size) {
3956                         $current_color = ++$current_color % $num_colors;
3957                 }
3958                 print "<tr class=\"$rev_color[$current_color]\">\n";
3959                 if ($group_size) {
3960                         print "<td class=\"sha1\"";
3961                         print " title=\"". esc_html($author) . ", $date\"";
3962                         print " rowspan=\"$group_size\"" if ($group_size > 1);
3963                         print ">";
3964                         print $cgi->a({-href => href(action=>"commit",
3965                                                      hash=>$full_rev,
3966                                                      file_name=>$file_name)},
3967                                       esc_html($rev));
3968                         print "</td>\n";
3969                 }
3970                 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
3971                         or die_error(undef, "Open git-rev-parse failed");
3972                 my $parent_commit = <$dd>;
3973                 close $dd;
3974                 chomp($parent_commit);
3975                 my $blamed = href(action => 'blame',
3976                                   file_name => $meta->{'filename'},
3977                                   hash_base => $parent_commit);
3978                 print "<td class=\"linenr\">";
3979                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
3980                                 -id => "l$lineno",
3981                                 -class => "linenr" },
3982                               esc_html($lineno));
3983                 print "</td>";
3984                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3985                 print "</tr>\n";
3986         }
3987         print "</table>\n";
3988         print "</div>";
3989         close $fd
3990                 or print "Reading blob failed\n";
3991         git_footer_html();
3994 sub git_blame {
3995         my $fd;
3997         my ($have_blame) = gitweb_check_feature('blame');
3998         if (!$have_blame) {
3999                 die_error('403 Permission denied', "Permission denied");
4000         }
4001         die_error('404 Not Found', "File name not defined") if (!$file_name);
4002         $hash_base ||= git_get_head_hash($project);
4003         die_error(undef, "Couldn't find base commit") unless ($hash_base);
4004         my %co = parse_commit($hash_base)
4005                 or die_error(undef, "Reading commit failed");
4006         if (!defined $hash) {
4007                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4008                         or die_error(undef, "Error lookup file");
4009         }
4010         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
4011                 or die_error(undef, "Open git-annotate failed");
4012         git_header_html();
4013         my $formats_nav =
4014                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
4015                         "blob") .
4016                 " | " .
4017                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
4018                         "history") .
4019                 " | " .
4020                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4021                         "HEAD");
4022         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4023         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4024         git_print_page_path($file_name, 'blob', $hash_base);
4025         print "<div class=\"page_body\">\n";
4026         print <<HTML;
4027 <table class="blame">
4028   <tr>
4029     <th>Commit</th>
4030     <th>Age</th>
4031     <th>Author</th>
4032     <th>Line</th>
4033     <th>Data</th>
4034   </tr>
4035 HTML
4036         my @line_class = (qw(light dark));
4037         my $line_class_len = scalar (@line_class);
4038         my $line_class_num = $#line_class;
4039         while (my $line = <$fd>) {
4040                 my $long_rev;
4041                 my $short_rev;
4042                 my $author;
4043                 my $time;
4044                 my $lineno;
4045                 my $data;
4046                 my $age;
4047                 my $age_str;
4048                 my $age_class;
4050                 chomp $line;
4051                 $line_class_num = ($line_class_num + 1) % $line_class_len;
4053                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
4054                         $long_rev = $1;
4055                         $author   = $2;
4056                         $time     = $3;
4057                         $lineno   = $4;
4058                         $data     = $5;
4059                 } else {
4060                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
4061                         next;
4062                 }
4063                 $short_rev  = substr ($long_rev, 0, 8);
4064                 $age        = time () - $time;
4065                 $age_str    = age_string ($age);
4066                 $age_str    =~ s/ /&nbsp;/g;
4067                 $age_class  = age_class($age);
4068                 $author     = esc_html ($author);
4069                 $author     =~ s/ /&nbsp;/g;
4071                 $data = untabify($data);
4072                 $data = esc_html ($data);
4074                 print <<HTML;
4075   <tr class="$line_class[$line_class_num]">
4076     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
4077     <td class="$age_class">$age_str</td>
4078     <td>$author</td>
4079     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
4080     <td class="pre">$data</td>
4081   </tr>
4082 HTML
4083         } # while (my $line = <$fd>)
4084         print "</table>\n\n";
4085         close $fd
4086                 or print "Reading blob failed.\n";
4087         print "</div>";
4088         git_footer_html();
4091 sub git_tags {
4092         my $head = git_get_head_hash($project);
4093         git_header_html();
4094         git_print_page_nav('','', $head,undef,$head);
4095         git_print_header_div('summary', $project);
4097         my @tagslist = git_get_tags_list();
4098         if (@tagslist) {
4099                 git_tags_body(\@tagslist);
4100         }
4101         git_footer_html();
4104 sub git_heads {
4105         my $head = git_get_head_hash($project);
4106         git_header_html();
4107         git_print_page_nav('','', $head,undef,$head);
4108         git_print_header_div('summary', $project);
4110         my @headslist = git_get_heads_list();
4111         if (@headslist) {
4112                 git_heads_body(\@headslist, $head);
4113         }
4114         git_footer_html();
4117 sub git_blob_plain {
4118         my $expires;
4120         if (!defined $hash) {
4121                 if (defined $file_name) {
4122                         my $base = $hash_base || git_get_head_hash($project);
4123                         $hash = git_get_hash_by_path($base, $file_name, "blob")
4124                                 or die_error(undef, "Error lookup file");
4125                 } else {
4126                         die_error(undef, "No file name defined");
4127                 }
4128         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4129                 # blobs defined by non-textual hash id's can be cached
4130                 $expires = "+1d";
4131         }
4133         my $type = shift;
4134         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4135                 or die_error(undef, "Couldn't cat $file_name, $hash");
4137         $type ||= blob_mimetype($fd, $file_name);
4139         # save as filename, even when no $file_name is given
4140         my $save_as = "$hash";
4141         if (defined $file_name) {
4142                 $save_as = $file_name;
4143         } elsif ($type =~ m/^text\//) {
4144                 $save_as .= '.txt';
4145         }
4147         print $cgi->header(
4148                 -type => "$type",
4149                 -expires=>$expires,
4150                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
4151         undef $/;
4152         binmode STDOUT, ':raw';
4153         print <$fd>;
4154         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4155         $/ = "\n";
4156         close $fd;
4159 sub git_blob {
4160         my $expires;
4162         if (!defined $hash) {
4163                 if (defined $file_name) {
4164                         my $base = $hash_base || git_get_head_hash($project);
4165                         $hash = git_get_hash_by_path($base, $file_name, "blob")
4166                                 or die_error(undef, "Error lookup file");
4167                 } else {
4168                         die_error(undef, "No file name defined");
4169                 }
4170         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4171                 # blobs defined by non-textual hash id's can be cached
4172                 $expires = "+1d";
4173         }
4175         my ($have_blame) = gitweb_check_feature('blame');
4176         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4177                 or die_error(undef, "Couldn't cat $file_name, $hash");
4178         my $mimetype = blob_mimetype($fd, $file_name);
4179         if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
4180                 close $fd;
4181                 return git_blob_plain($mimetype);
4182         }
4183         # we can have blame only for text/* mimetype
4184         $have_blame &&= ($mimetype =~ m!^text/!);
4186         git_header_html(undef, $expires);
4187         my $formats_nav = '';
4188         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4189                 if (defined $file_name) {
4190                         if ($have_blame) {
4191                                 $formats_nav .=
4192                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
4193                                                                hash=>$hash, file_name=>$file_name)},
4194                                                 "blame") .
4195                                         " | ";
4196                         }
4197                         $formats_nav .=
4198                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4199                                                        hash=>$hash, file_name=>$file_name)},
4200                                         "history") .
4201                                 " | " .
4202                                 $cgi->a({-href => href(action=>"blob_plain",
4203                                                        hash=>$hash, file_name=>$file_name)},
4204                                         "raw") .
4205                                 " | " .
4206                                 $cgi->a({-href => href(action=>"blob",
4207                                                        hash_base=>"HEAD", file_name=>$file_name)},
4208                                         "HEAD");
4209                 } else {
4210                         $formats_nav .=
4211                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
4212                 }
4213                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4214                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4215         } else {
4216                 print "<div class=\"page_nav\">\n" .
4217                       "<br/><br/></div>\n" .
4218                       "<div class=\"title\">$hash</div>\n";
4219         }
4220         git_print_page_path($file_name, "blob", $hash_base);
4221         print "<div class=\"page_body\">\n";
4222         if ($mimetype =~ m!^text/!) {
4223                 my $nr;
4224                 while (my $line = <$fd>) {
4225                         chomp $line;
4226                         $nr++;
4227                         $line = untabify($line);
4228                         printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4229                                $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4230                 }
4231         } elsif ($mimetype =~ m!^image/!) {
4232                 print qq!<img type="$mimetype"!;
4233                 if ($file_name) {
4234                         print qq! alt="$file_name" title="$file_name"!;
4235                 }
4236                 print qq! src="! .
4237                       href(action=>"blob_plain", hash=>$hash,
4238                            hash_base=>$hash_base, file_name=>$file_name) .
4239                       qq!" />\n!;
4240         }
4241         close $fd
4242                 or print "Reading blob failed.\n";
4243         print "</div>";
4244         git_footer_html();
4247 sub git_tree {
4248         if (!defined $hash_base) {
4249                 $hash_base = "HEAD";
4250         }
4251         if (!defined $hash) {
4252                 if (defined $file_name) {
4253                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4254                 } else {
4255                         $hash = $hash_base;
4256                 }
4257         }
4258         $/ = "\0";
4259         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4260                 or die_error(undef, "Open git-ls-tree failed");
4261         my @entries = map { chomp; $_ } <$fd>;
4262         close $fd or die_error(undef, "Reading tree failed");
4263         $/ = "\n";
4265         my $refs = git_get_references();
4266         my $ref = format_ref_marker($refs, $hash_base);
4267         git_header_html();
4268         my $basedir = '';
4269         my ($have_blame) = gitweb_check_feature('blame');
4270         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4271                 my @views_nav = ();
4272                 if (defined $file_name) {
4273                         push @views_nav,
4274                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4275                                                        hash=>$hash, file_name=>$file_name)},
4276                                         "history"),
4277                                 $cgi->a({-href => href(action=>"tree",
4278                                                        hash_base=>"HEAD", file_name=>$file_name)},
4279                                         "HEAD"),
4280                 }
4281                 my $snapshot_links = format_snapshot_links($hash);
4282                 if (defined $snapshot_links) {
4283                         # FIXME: Should be available when we have no hash base as well.
4284                         push @views_nav, $snapshot_links;
4285                 }
4286                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4287                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4288         } else {
4289                 undef $hash_base;
4290                 print "<div class=\"page_nav\">\n";
4291                 print "<br/><br/></div>\n";
4292                 print "<div class=\"title\">$hash</div>\n";
4293         }
4294         if (defined $file_name) {
4295                 $basedir = $file_name;
4296                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4297                         $basedir .= '/';
4298                 }
4299         }
4300         git_print_page_path($file_name, 'tree', $hash_base);
4301         print "<div class=\"page_body\">\n";
4302         print "<table cellspacing=\"0\">\n";
4303         my $alternate = 1;
4304         # '..' (top directory) link if possible
4305         if (defined $hash_base &&
4306             defined $file_name && $file_name =~ m![^/]+$!) {
4307                 if ($alternate) {
4308                         print "<tr class=\"dark\">\n";
4309                 } else {
4310                         print "<tr class=\"light\">\n";
4311                 }
4312                 $alternate ^= 1;
4314                 my $up = $file_name;
4315                 $up =~ s!/?[^/]+$!!;
4316                 undef $up unless $up;
4317                 # based on git_print_tree_entry
4318                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4319                 print '<td class="list">';
4320                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4321                                              file_name=>$up)},
4322                               "..");
4323                 print "</td>\n";
4324                 print "<td class=\"link\"></td>\n";
4326                 print "</tr>\n";
4327         }
4328         foreach my $line (@entries) {
4329                 my %t = parse_ls_tree_line($line, -z => 1);
4331                 if ($alternate) {
4332                         print "<tr class=\"dark\">\n";
4333                 } else {
4334                         print "<tr class=\"light\">\n";
4335                 }
4336                 $alternate ^= 1;
4338                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4340                 print "</tr>\n";
4341         }
4342         print "</table>\n" .
4343               "</div>";
4344         git_footer_html();
4347 sub git_snapshot {
4348         my @supported_fmts = gitweb_check_feature('snapshot');
4349         @supported_fmts = filter_snapshot_fmts(@supported_fmts);
4351         my $format = $cgi->param('sf');
4352         if (!@supported_fmts) {
4353                 die_error('403 Permission denied', "Permission denied");
4354         }
4355         # default to first supported snapshot format
4356         $format ||= $supported_fmts[0];
4357         if ($format !~ m/^[a-z0-9]+$/) {
4358                 die_error(undef, "Invalid snapshot format parameter");
4359         } elsif (!exists($known_snapshot_formats{$format})) {
4360                 die_error(undef, "Unknown snapshot format");
4361         } elsif (!grep($_ eq $format, @supported_fmts)) {
4362                 die_error(undef, "Unsupported snapshot format");
4363         }
4365         if (!defined $hash) {
4366                 $hash = git_get_head_hash($project);
4367         }
4369         my $git_command = git_cmd_str();
4370         my $name = $project;
4371         $name =~ s,([^/])/*\.git$,$1,;
4372         $name = basename($name);
4373         my $filename = to_utf8($name);
4374         $name =~ s/\047/\047\\\047\047/g;
4375         my $cmd;
4376         $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4377         $cmd = "$git_command archive " .
4378                 "--format=$known_snapshot_formats{$format}{'format'} " .
4379                 "--prefix=\'$name\'/ $hash";
4380         if (exists $known_snapshot_formats{$format}{'compressor'}) {
4381                 $cmd .= ' | ' . join ' ', @{$known_snapshot_formats{$format}{'compressor'}};
4382         }
4384         print $cgi->header(
4385                 -type => $known_snapshot_formats{$format}{'type'},
4386                 -content_disposition => 'inline; filename="' . "$filename" . '"',
4387                 -status => '200 OK');
4389         open my $fd, "-|", $cmd
4390                 or die_error(undef, "Execute git-archive failed");
4391         binmode STDOUT, ':raw';
4392         print <$fd>;
4393         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4394         close $fd;
4397 sub git_log {
4398         my $head = git_get_head_hash($project);
4399         if (!defined $hash) {
4400                 $hash = $head;
4401         }
4402         if (!defined $page) {
4403                 $page = 0;
4404         }
4405         my $refs = git_get_references();
4407         my @commitlist = parse_commits($hash, 101, (100 * $page));
4409         my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
4411         git_header_html();
4412         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4414         if (!@commitlist) {
4415                 my %co = parse_commit($hash);
4417                 git_print_header_div('summary', $project);
4418                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4419         }
4420         my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4421         for (my $i = 0; $i <= $to; $i++) {
4422                 my %co = %{$commitlist[$i]};
4423                 next if !%co;
4424                 my $commit = $co{'id'};
4425                 my $ref = format_ref_marker($refs, $commit);
4426                 my %ad = parse_date($co{'author_epoch'});
4427                 git_print_header_div('commit',
4428                                "<span class=\"age\">$co{'age_string'}</span>" .
4429                                esc_html($co{'title'}) . $ref,
4430                                $commit);
4431                 print "<div class=\"title_text\">\n" .
4432                       "<div class=\"log_link\">\n" .
4433                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4434                       " | " .
4435                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4436                       " | " .
4437                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4438                       "<br/>\n" .
4439                       "</div>\n" .
4440                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
4441                       "</div>\n";
4443                 print "<div class=\"log_body\">\n";
4444                 git_print_log($co{'comment'}, -final_empty_line=> 1);
4445                 print "</div>\n";
4446         }
4447         if ($#commitlist >= 100) {
4448                 print "<div class=\"page_nav\">\n";
4449                 print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
4450                                -accesskey => "n", -title => "Alt-n"}, "next");
4451                 print "</div>\n";
4452         }
4453         git_footer_html();
4456 sub git_commit {
4457         $hash ||= $hash_base || "HEAD";
4458         my %co = parse_commit($hash);
4459         if (!%co) {
4460                 die_error(undef, "Unknown commit object");
4461         }
4462         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4463         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4465         my $parent  = $co{'parent'};
4466         my $parents = $co{'parents'}; # listref
4468         # we need to prepare $formats_nav before any parameter munging
4469         my $formats_nav;
4470         if (!defined $parent) {
4471                 # --root commitdiff
4472                 $formats_nav .= '(initial)';
4473         } elsif (@$parents == 1) {
4474                 # single parent commit
4475                 $formats_nav .=
4476                         '(parent: ' .
4477                         $cgi->a({-href => href(action=>"commit",
4478                                                hash=>$parent)},
4479                                 esc_html(substr($parent, 0, 7))) .
4480                         ')';
4481         } else {
4482                 # merge commit
4483                 $formats_nav .=
4484                         '(merge: ' .
4485                         join(' ', map {
4486                                 $cgi->a({-href => href(action=>"commit",
4487                                                        hash=>$_)},
4488                                         esc_html(substr($_, 0, 7)));
4489                         } @$parents ) .
4490                         ')';
4491         }
4493         if (!defined $parent) {
4494                 $parent = "--root";
4495         }
4496         my @difftree;
4497         open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4498                 @diff_opts,
4499                 (@$parents <= 1 ? $parent : '-c'),
4500                 $hash, "--"
4501                 or die_error(undef, "Open git-diff-tree failed");
4502         @difftree = map { chomp; $_ } <$fd>;
4503         close $fd or die_error(undef, "Reading git-diff-tree failed");
4505         # non-textual hash id's can be cached
4506         my $expires;
4507         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4508                 $expires = "+1d";
4509         }
4510         my $refs = git_get_references();
4511         my $ref = format_ref_marker($refs, $co{'id'});
4513         git_header_html(undef, $expires);
4514         git_print_page_nav('commit', '',
4515                            $hash, $co{'tree'}, $hash,
4516                            $formats_nav);
4518         if (defined $co{'parent'}) {
4519                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4520         } else {
4521                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4522         }
4523         print "<div class=\"title_text\">\n" .
4524               "<table cellspacing=\"0\">\n";
4525         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4526               "<tr>" .
4527               "<td></td><td> $ad{'rfc2822'}";
4528         if ($ad{'hour_local'} < 6) {
4529                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4530                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4531         } else {
4532                 printf(" (%02d:%02d %s)",
4533                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4534         }
4535         print "</td>" .
4536               "</tr>\n";
4537         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4538         print "<tr><td></td><td> $cd{'rfc2822'}" .
4539               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4540               "</td></tr>\n";
4541         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4542         print "<tr>" .
4543               "<td>tree</td>" .
4544               "<td class=\"sha1\">" .
4545               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4546                        class => "list"}, $co{'tree'}) .
4547               "</td>" .
4548               "<td class=\"link\">" .
4549               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4550                       "tree");
4551         my $snapshot_links = format_snapshot_links($hash);
4552         if (defined $snapshot_links) {
4553                 print " | " . $snapshot_links;
4554         }
4555         print "</td>" .
4556               "</tr>\n";
4558         foreach my $par (@$parents) {
4559                 print "<tr>" .
4560                       "<td>parent</td>" .
4561                       "<td class=\"sha1\">" .
4562                       $cgi->a({-href => href(action=>"commit", hash=>$par),
4563                                class => "list"}, $par) .
4564                       "</td>" .
4565                       "<td class=\"link\">" .
4566                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4567                       " | " .
4568                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4569                       "</td>" .
4570                       "</tr>\n";
4571         }
4572         print "</table>".
4573               "</div>\n";
4575         print "<div class=\"page_body\">\n";
4576         git_print_log($co{'comment'});
4577         print "</div>\n";
4579         git_difftree_body(\@difftree, $hash, @$parents);
4581         git_footer_html();
4584 sub git_object {
4585         # object is defined by:
4586         # - hash or hash_base alone
4587         # - hash_base and file_name
4588         my $type;
4590         # - hash or hash_base alone
4591         if ($hash || ($hash_base && !defined $file_name)) {
4592                 my $object_id = $hash || $hash_base;
4594                 my $git_command = git_cmd_str();
4595                 open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
4596                         or die_error('404 Not Found', "Object does not exist");
4597                 $type = <$fd>;
4598                 chomp $type;
4599                 close $fd
4600                         or die_error('404 Not Found', "Object does not exist");
4602         # - hash_base and file_name
4603         } elsif ($hash_base && defined $file_name) {
4604                 $file_name =~ s,/+$,,;
4606                 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4607                         or die_error('404 Not Found', "Base object does not exist");
4609                 # here errors should not hapen
4610                 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4611                         or die_error(undef, "Open git-ls-tree failed");
4612                 my $line = <$fd>;
4613                 close $fd;
4615                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
4616                 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4617                         die_error('404 Not Found', "File or directory for given base does not exist");
4618                 }
4619                 $type = $2;
4620                 $hash = $3;
4621         } else {
4622                 die_error('404 Not Found', "Not enough information to find object");
4623         }
4625         print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4626                                           hash=>$hash, hash_base=>$hash_base,
4627                                           file_name=>$file_name),
4628                              -status => '302 Found');
4631 sub git_blobdiff {
4632         my $format = shift || 'html';
4634         my $fd;
4635         my @difftree;
4636         my %diffinfo;
4637         my $expires;
4639         # preparing $fd and %diffinfo for git_patchset_body
4640         # new style URI
4641         if (defined $hash_base && defined $hash_parent_base) {
4642                 if (defined $file_name) {
4643                         # read raw output
4644                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4645                                 $hash_parent_base, $hash_base,
4646                                 "--", (defined $file_parent ? $file_parent : ()), $file_name
4647                                 or die_error(undef, "Open git-diff-tree failed");
4648                         @difftree = map { chomp; $_ } <$fd>;
4649                         close $fd
4650                                 or die_error(undef, "Reading git-diff-tree failed");
4651                         @difftree
4652                                 or die_error('404 Not Found', "Blob diff not found");
4654                 } elsif (defined $hash &&
4655                          $hash =~ /[0-9a-fA-F]{40}/) {
4656                         # try to find filename from $hash
4658                         # read filtered raw output
4659                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4660                                 $hash_parent_base, $hash_base, "--"
4661                                 or die_error(undef, "Open git-diff-tree failed");
4662                         @difftree =
4663                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
4664                                 # $hash == to_id
4665                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4666                                 map { chomp; $_ } <$fd>;
4667                         close $fd
4668                                 or die_error(undef, "Reading git-diff-tree failed");
4669                         @difftree
4670                                 or die_error('404 Not Found', "Blob diff not found");
4672                 } else {
4673                         die_error('404 Not Found', "Missing one of the blob diff parameters");
4674                 }
4676                 if (@difftree > 1) {
4677                         die_error('404 Not Found', "Ambiguous blob diff specification");
4678                 }
4680                 %diffinfo = parse_difftree_raw_line($difftree[0]);
4681                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
4682                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
4684                 $hash_parent ||= $diffinfo{'from_id'};
4685                 $hash        ||= $diffinfo{'to_id'};
4687                 # non-textual hash id's can be cached
4688                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4689                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4690                         $expires = '+1d';
4691                 }
4693                 # open patch output
4694                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4695                         '-p', ($format eq 'html' ? "--full-index" : ()),
4696                         $hash_parent_base, $hash_base,
4697                         "--", (defined $file_parent ? $file_parent : ()), $file_name
4698                         or die_error(undef, "Open git-diff-tree failed");
4699         }
4701         # old/legacy style URI
4702         if (!%diffinfo && # if new style URI failed
4703             defined $hash && defined $hash_parent) {
4704                 # fake git-diff-tree raw output
4705                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4706                 $diffinfo{'from_id'} = $hash_parent;
4707                 $diffinfo{'to_id'}   = $hash;
4708                 if (defined $file_name) {
4709                         if (defined $file_parent) {
4710                                 $diffinfo{'status'} = '2';
4711                                 $diffinfo{'from_file'} = $file_parent;
4712                                 $diffinfo{'to_file'}   = $file_name;
4713                         } else { # assume not renamed
4714                                 $diffinfo{'status'} = '1';
4715                                 $diffinfo{'from_file'} = $file_name;
4716                                 $diffinfo{'to_file'}   = $file_name;
4717                         }
4718                 } else { # no filename given
4719                         $diffinfo{'status'} = '2';
4720                         $diffinfo{'from_file'} = $hash_parent;
4721                         $diffinfo{'to_file'}   = $hash;
4722                 }
4724                 # non-textual hash id's can be cached
4725                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4726                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4727                         $expires = '+1d';
4728                 }
4730                 # open patch output
4731                 open $fd, "-|", git_cmd(), "diff", @diff_opts,
4732                         '-p', ($format eq 'html' ? "--full-index" : ()),
4733                         $hash_parent, $hash, "--"
4734                         or die_error(undef, "Open git-diff failed");
4735         } else  {
4736                 die_error('404 Not Found', "Missing one of the blob diff parameters")
4737                         unless %diffinfo;
4738         }
4740         # header
4741         if ($format eq 'html') {
4742                 my $formats_nav =
4743                         $cgi->a({-href => href(action=>"blobdiff_plain",
4744                                                hash=>$hash, hash_parent=>$hash_parent,
4745                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
4746                                                file_name=>$file_name, file_parent=>$file_parent)},
4747                                 "raw");
4748                 git_header_html(undef, $expires);
4749                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4750                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4751                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4752                 } else {
4753                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4754                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4755                 }
4756                 if (defined $file_name) {
4757                         git_print_page_path($file_name, "blob", $hash_base);
4758                 } else {
4759                         print "<div class=\"page_path\"></div>\n";
4760                 }
4762         } elsif ($format eq 'plain') {
4763                 print $cgi->header(
4764                         -type => 'text/plain',
4765                         -charset => 'utf-8',
4766                         -expires => $expires,
4767                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4769                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4771         } else {
4772                 die_error(undef, "Unknown blobdiff format");
4773         }
4775         # patch
4776         if ($format eq 'html') {
4777                 print "<div class=\"page_body\">\n";
4779                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4780                 close $fd;
4782                 print "</div>\n"; # class="page_body"
4783                 git_footer_html();
4785         } else {
4786                 while (my $line = <$fd>) {
4787                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4788                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4790                         print $line;
4792                         last if $line =~ m!^\+\+\+!;
4793                 }
4794                 local $/ = undef;
4795                 print <$fd>;
4796                 close $fd;
4797         }
4800 sub git_blobdiff_plain {
4801         git_blobdiff('plain');
4804 sub git_commitdiff {
4805         my $format = shift || 'html';
4806         $hash ||= $hash_base || "HEAD";
4807         my %co = parse_commit($hash);
4808         if (!%co) {
4809                 die_error(undef, "Unknown commit object");
4810         }
4812         # choose format for commitdiff for merge
4813         if (! defined $hash_parent && @{$co{'parents'}} > 1) {
4814                 $hash_parent = '--cc';
4815         }
4816         # we need to prepare $formats_nav before almost any parameter munging
4817         my $formats_nav;
4818         if ($format eq 'html') {
4819                 $formats_nav =
4820                         $cgi->a({-href => href(action=>"commitdiff_plain",
4821                                                hash=>$hash, hash_parent=>$hash_parent)},
4822                                 "raw");
4824                 if (defined $hash_parent &&
4825                     $hash_parent ne '-c' && $hash_parent ne '--cc') {
4826                         # commitdiff with two commits given
4827                         my $hash_parent_short = $hash_parent;
4828                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4829                                 $hash_parent_short = substr($hash_parent, 0, 7);
4830                         }
4831                         $formats_nav .=
4832                                 ' (from';
4833                         for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
4834                                 if ($co{'parents'}[$i] eq $hash_parent) {
4835                                         $formats_nav .= ' parent ' . ($i+1);
4836                                         last;
4837                                 }
4838                         }
4839                         $formats_nav .= ': ' .
4840                                 $cgi->a({-href => href(action=>"commitdiff",
4841                                                        hash=>$hash_parent)},
4842                                         esc_html($hash_parent_short)) .
4843                                 ')';
4844                 } elsif (!$co{'parent'}) {
4845                         # --root commitdiff
4846                         $formats_nav .= ' (initial)';
4847                 } elsif (scalar @{$co{'parents'}} == 1) {
4848                         # single parent commit
4849                         $formats_nav .=
4850                                 ' (parent: ' .
4851                                 $cgi->a({-href => href(action=>"commitdiff",
4852                                                        hash=>$co{'parent'})},
4853                                         esc_html(substr($co{'parent'}, 0, 7))) .
4854                                 ')';
4855                 } else {
4856                         # merge commit
4857                         if ($hash_parent eq '--cc') {
4858                                 $formats_nav .= ' | ' .
4859                                         $cgi->a({-href => href(action=>"commitdiff",
4860                                                                hash=>$hash, hash_parent=>'-c')},
4861                                                 'combined');
4862                         } else { # $hash_parent eq '-c'
4863                                 $formats_nav .= ' | ' .
4864                                         $cgi->a({-href => href(action=>"commitdiff",
4865                                                                hash=>$hash, hash_parent=>'--cc')},
4866                                                 'compact');
4867                         }
4868                         $formats_nav .=
4869                                 ' (merge: ' .
4870                                 join(' ', map {
4871                                         $cgi->a({-href => href(action=>"commitdiff",
4872                                                                hash=>$_)},
4873                                                 esc_html(substr($_, 0, 7)));
4874                                 } @{$co{'parents'}} ) .
4875                                 ')';
4876                 }
4877         }
4879         my $hash_parent_param = $hash_parent;
4880         if (!defined $hash_parent_param) {
4881                 # --cc for multiple parents, --root for parentless
4882                 $hash_parent_param =
4883                         @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
4884         }
4886         # read commitdiff
4887         my $fd;
4888         my @difftree;
4889         if ($format eq 'html') {
4890                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4891                         "--no-commit-id", "--patch-with-raw", "--full-index",
4892                         $hash_parent_param, $hash, "--"
4893                         or die_error(undef, "Open git-diff-tree failed");
4895                 while (my $line = <$fd>) {
4896                         chomp $line;
4897                         # empty line ends raw part of diff-tree output
4898                         last unless $line;
4899                         push @difftree, scalar parse_difftree_raw_line($line);
4900                 }
4902         } elsif ($format eq 'plain') {
4903                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4904                         '-p', $hash_parent_param, $hash, "--"
4905                         or die_error(undef, "Open git-diff-tree failed");
4907         } else {
4908                 die_error(undef, "Unknown commitdiff format");
4909         }
4911         # non-textual hash id's can be cached
4912         my $expires;
4913         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4914                 $expires = "+1d";
4915         }
4917         # write commit message
4918         if ($format eq 'html') {
4919                 my $refs = git_get_references();
4920                 my $ref = format_ref_marker($refs, $co{'id'});
4922                 git_header_html(undef, $expires);
4923                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4924                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4925                 git_print_authorship(\%co);
4926                 print "<div class=\"page_body\">\n";
4927                 if (@{$co{'comment'}} > 1) {
4928                         print "<div class=\"log\">\n";
4929                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4930                         print "</div>\n"; # class="log"
4931                 }
4933         } elsif ($format eq 'plain') {
4934                 my $refs = git_get_references("tags");
4935                 my $tagname = git_get_rev_name_tags($hash);
4936                 my $filename = basename($project) . "-$hash.patch";
4938                 print $cgi->header(
4939                         -type => 'text/plain',
4940                         -charset => 'utf-8',
4941                         -expires => $expires,
4942                         -content_disposition => 'inline; filename="' . "$filename" . '"');
4943                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4944                 print <<TEXT;
4945 From: $co{'author'}
4946 Date: $ad{'rfc2822'} ($ad{'tz_local'})
4947 Subject: $co{'title'}
4948 TEXT
4949                 print "X-Git-Tag: $tagname\n" if $tagname;
4950                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4952                 foreach my $line (@{$co{'comment'}}) {
4953                         print "$line\n";
4954                 }
4955                 print "---\n\n";
4956         }
4958         # write patch
4959         if ($format eq 'html') {
4960                 my $use_parents = !defined $hash_parent ||
4961                         $hash_parent eq '-c' || $hash_parent eq '--cc';
4962                 git_difftree_body(\@difftree, $hash,
4963                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
4964                 print "<br/>\n";
4966                 git_patchset_body($fd, \@difftree, $hash,
4967                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
4968                 close $fd;
4969                 print "</div>\n"; # class="page_body"
4970                 git_footer_html();
4972         } elsif ($format eq 'plain') {
4973                 local $/ = undef;
4974                 print <$fd>;
4975                 close $fd
4976                         or print "Reading git-diff-tree failed\n";
4977         }
4980 sub git_commitdiff_plain {
4981         git_commitdiff('plain');
4984 sub git_history {
4985         if (!defined $hash_base) {
4986                 $hash_base = git_get_head_hash($project);
4987         }
4988         if (!defined $page) {
4989                 $page = 0;
4990         }
4991         my $ftype;
4992         my %co = parse_commit($hash_base);
4993         if (!%co) {
4994                 die_error(undef, "Unknown commit object");
4995         }
4997         my $refs = git_get_references();
4998         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5000         if (!defined $hash && defined $file_name) {
5001                 $hash = git_get_hash_by_path($hash_base, $file_name);
5002         }
5003         if (defined $hash) {
5004                 $ftype = git_get_type($hash);
5005         }
5007         my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
5009         my $paging_nav = '';
5010         if ($page > 0) {
5011                 $paging_nav .=
5012                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5013                                                file_name=>$file_name)},
5014                                 "first");
5015                 $paging_nav .= " &sdot; " .
5016                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5017                                                file_name=>$file_name, page=>$page-1),
5018                                  -accesskey => "p", -title => "Alt-p"}, "prev");
5019         } else {
5020                 $paging_nav .= "first";
5021                 $paging_nav .= " &sdot; prev";
5022         }
5023         if ($#commitlist >= 100) {
5024                 $paging_nav .= " &sdot; " .
5025                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5026                                                file_name=>$file_name, page=>$page+1),
5027                                  -accesskey => "n", -title => "Alt-n"}, "next");
5028         } else {
5029                 $paging_nav .= " &sdot; next";
5030         }
5031         my $next_link = '';
5032         if ($#commitlist >= 100) {
5033                 $next_link =
5034                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5035                                                file_name=>$file_name, page=>$page+1),
5036                                  -accesskey => "n", -title => "Alt-n"}, "next");
5037         }
5039         git_header_html();
5040         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5041         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5042         git_print_page_path($file_name, $ftype, $hash_base);
5044         git_history_body(\@commitlist, 0, 99,
5045                          $refs, $hash_base, $ftype, $next_link);
5047         git_footer_html();
5050 sub git_search {
5051         my ($have_search) = gitweb_check_feature('search');
5052         if (!$have_search) {
5053                 die_error('403 Permission denied', "Permission denied");
5054         }
5055         if (!defined $searchtext) {
5056                 die_error(undef, "Text field empty");
5057         }
5058         if (!defined $hash) {
5059                 $hash = git_get_head_hash($project);
5060         }
5061         my %co = parse_commit($hash);
5062         if (!%co) {
5063                 die_error(undef, "Unknown commit object");
5064         }
5065         if (!defined $page) {
5066                 $page = 0;
5067         }
5069         $searchtype ||= 'commit';
5070         if ($searchtype eq 'pickaxe') {
5071                 # pickaxe may take all resources of your box and run for several minutes
5072                 # with every query - so decide by yourself how public you make this feature
5073                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5074                 if (!$have_pickaxe) {
5075                         die_error('403 Permission denied', "Permission denied");
5076                 }
5077         }
5078         if ($searchtype eq 'grep') {
5079                 my ($have_grep) = gitweb_check_feature('grep');
5080                 if (!$have_grep) {
5081                         die_error('403 Permission denied', "Permission denied");
5082                 }
5083         }
5085         git_header_html();
5087         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5088                 my $greptype;
5089                 if ($searchtype eq 'commit') {
5090                         $greptype = "--grep=";
5091                 } elsif ($searchtype eq 'author') {
5092                         $greptype = "--author=";
5093                 } elsif ($searchtype eq 'committer') {
5094                         $greptype = "--committer=";
5095                 }
5096                 $greptype .= $search_regexp;
5097                 my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
5099                 my $paging_nav = '';
5100                 if ($page > 0) {
5101                         $paging_nav .=
5102                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5103                                                        searchtext=>$searchtext, searchtype=>$searchtype)},
5104                                         "first");
5105                         $paging_nav .= " &sdot; " .
5106                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5107                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5108                                                        page=>$page-1),
5109                                          -accesskey => "p", -title => "Alt-p"}, "prev");
5110                 } else {
5111                         $paging_nav .= "first";
5112                         $paging_nav .= " &sdot; prev";
5113                 }
5114                 if ($#commitlist >= 100) {
5115                         $paging_nav .= " &sdot; " .
5116                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5117                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5118                                                        page=>$page+1),
5119                                          -accesskey => "n", -title => "Alt-n"}, "next");
5120                 } else {
5121                         $paging_nav .= " &sdot; next";
5122                 }
5123                 my $next_link = '';
5124                 if ($#commitlist >= 100) {
5125                         $next_link =
5126                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5127                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5128                                                        page=>$page+1),
5129                                          -accesskey => "n", -title => "Alt-n"}, "next");
5130                 }
5132                 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5133                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5134                 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5135         }
5137         if ($searchtype eq 'pickaxe') {
5138                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5139                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5141                 print "<table cellspacing=\"0\">\n";
5142                 my $alternate = 1;
5143                 $/ = "\n";
5144                 my $git_command = git_cmd_str();
5145                 my $searchqtext = $searchtext;
5146                 $searchqtext =~ s/'/'\\''/;
5147                 open my $fd, "-|", "$git_command rev-list $hash | " .
5148                         "$git_command diff-tree -r --stdin -S\'$searchqtext\'";
5149                 undef %co;
5150                 my @files;
5151                 while (my $line = <$fd>) {
5152                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
5153                                 my %set;
5154                                 $set{'file'} = $6;
5155                                 $set{'from_id'} = $3;
5156                                 $set{'to_id'} = $4;
5157                                 $set{'id'} = $set{'to_id'};
5158                                 if ($set{'id'} =~ m/0{40}/) {
5159                                         $set{'id'} = $set{'from_id'};
5160                                 }
5161                                 if ($set{'id'} =~ m/0{40}/) {
5162                                         next;
5163                                 }
5164                                 push @files, \%set;
5165                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
5166                                 if (%co) {
5167                                         if ($alternate) {
5168                                                 print "<tr class=\"dark\">\n";
5169                                         } else {
5170                                                 print "<tr class=\"light\">\n";
5171                                         }
5172                                         $alternate ^= 1;
5173                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5174                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
5175                                               "<td>" .
5176                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5177                                                       -class => "list subject"},
5178                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
5179                                         while (my $setref = shift @files) {
5180                                                 my %set = %$setref;
5181                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5182                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
5183                                                               -class => "list"},
5184                                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5185                                                       "<br/>\n";
5186                                         }
5187                                         print "</td>\n" .
5188                                               "<td class=\"link\">" .
5189                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5190                                               " | " .
5191                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5192                                         print "</td>\n" .
5193                                               "</tr>\n";
5194                                 }
5195                                 %co = parse_commit($1);
5196                         }
5197                 }
5198                 close $fd;
5200                 print "</table>\n";
5201         }
5203         if ($searchtype eq 'grep') {
5204                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5205                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5207                 print "<table cellspacing=\"0\">\n";
5208                 my $alternate = 1;
5209                 my $matches = 0;
5210                 $/ = "\n";
5211                 open my $fd, "-|", git_cmd(), 'grep', '-n', '-i', '-E', $searchtext, $co{'tree'};
5212                 my $lastfile = '';
5213                 while (my $line = <$fd>) {
5214                         chomp $line;
5215                         my ($file, $lno, $ltext, $binary);
5216                         last if ($matches++ > 1000);
5217                         if ($line =~ /^Binary file (.+) matches$/) {
5218                                 $file = $1;
5219                                 $binary = 1;
5220                         } else {
5221                                 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5222                         }
5223                         if ($file ne $lastfile) {
5224                                 $lastfile and print "</td></tr>\n";
5225                                 if ($alternate++) {
5226                                         print "<tr class=\"dark\">\n";
5227                                 } else {
5228                                         print "<tr class=\"light\">\n";
5229                                 }
5230                                 print "<td class=\"list\">".
5231                                         $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5232                                                                file_name=>"$file"),
5233                                                 -class => "list"}, esc_path($file));
5234                                 print "</td><td>\n";
5235                                 $lastfile = $file;
5236                         }
5237                         if ($binary) {
5238                                 print "<div class=\"binary\">Binary file</div>\n";
5239                         } else {
5240                                 $ltext = untabify($ltext);
5241                                 if ($ltext =~ m/^(.*)($searchtext)(.*)$/i) {
5242                                         $ltext = esc_html($1, -nbsp=>1);
5243                                         $ltext .= '<span class="match">';
5244                                         $ltext .= esc_html($2, -nbsp=>1);
5245                                         $ltext .= '</span>';
5246                                         $ltext .= esc_html($3, -nbsp=>1);
5247                                 } else {
5248                                         $ltext = esc_html($ltext, -nbsp=>1);
5249                                 }
5250                                 print "<div class=\"pre\">" .
5251                                         $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5252                                                                file_name=>"$file").'#l'.$lno,
5253                                                 -class => "linenr"}, sprintf('%4i', $lno))
5254                                         . ' ' .  $ltext . "</div>\n";
5255                         }
5256                 }
5257                 if ($lastfile) {
5258                         print "</td></tr>\n";
5259                         if ($matches > 1000) {
5260                                 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5261                         }
5262                 } else {
5263                         print "<div class=\"diff nodifferences\">No matches found</div>\n";
5264                 }
5265                 close $fd;
5267                 print "</table>\n";
5268         }
5269         git_footer_html();
5272 sub git_search_help {
5273         git_header_html();
5274         git_print_page_nav('','', $hash,$hash,$hash);
5275         print <<EOT;
5276 <dl>
5277 <dt><b>commit</b></dt>
5278 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
5279 EOT
5280         my ($have_grep) = gitweb_check_feature('grep');
5281         if ($have_grep) {
5282                 print <<EOT;
5283 <dt><b>grep</b></dt>
5284 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5285     a different one) are searched for the given
5286 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a>
5287 (POSIX extended) and the matches are listed. On large
5288 trees, this search can take a while and put some strain on the server, so please use it with
5289 some consideration.</dd>
5290 EOT
5291         }
5292         print <<EOT;
5293 <dt><b>author</b></dt>
5294 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
5295 <dt><b>committer</b></dt>
5296 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
5297 EOT
5298         my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5299         if ($have_pickaxe) {
5300                 print <<EOT;
5301 <dt><b>pickaxe</b></dt>
5302 <dd>All commits that caused the string to appear or disappear from any file (changes that
5303 added, removed or "modified" the string) will be listed. This search can take a while and
5304 takes a lot of strain on the server, so please use it wisely.</dd>
5305 EOT
5306         }
5307         print "</dl>\n";
5308         git_footer_html();
5311 sub git_shortlog {
5312         my $head = git_get_head_hash($project);
5313         if (!defined $hash) {
5314                 $hash = $head;
5315         }
5316         if (!defined $page) {
5317                 $page = 0;
5318         }
5319         my $refs = git_get_references();
5321         my @commitlist = parse_commits($hash, 101, (100 * $page));
5323         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
5324         my $next_link = '';
5325         if ($#commitlist >= 100) {
5326                 $next_link =
5327                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
5328                                  -accesskey => "n", -title => "Alt-n"}, "next");
5329         }
5331         git_header_html();
5332         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5333         git_print_header_div('summary', $project);
5335         git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5337         git_footer_html();
5340 ## ......................................................................
5341 ## feeds (RSS, Atom; OPML)
5343 sub git_feed {
5344         my $format = shift || 'atom';
5345         my ($have_blame) = gitweb_check_feature('blame');
5347         # Atom: http://www.atomenabled.org/developers/syndication/
5348         # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5349         if ($format ne 'rss' && $format ne 'atom') {
5350                 die_error(undef, "Unknown web feed format");
5351         }
5353         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5354         my $head = $hash || 'HEAD';
5355         my @commitlist = parse_commits($head, 150);
5357         my %latest_commit;
5358         my %latest_date;
5359         my $content_type = "application/$format+xml";
5360         if (defined $cgi->http('HTTP_ACCEPT') &&
5361                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5362                 # browser (feed reader) prefers text/xml
5363                 $content_type = 'text/xml';
5364         }
5365         if (defined($commitlist[0])) {
5366                 %latest_commit = %{$commitlist[0]};
5367                 %latest_date   = parse_date($latest_commit{'author_epoch'});
5368                 print $cgi->header(
5369                         -type => $content_type,
5370                         -charset => 'utf-8',
5371                         -last_modified => $latest_date{'rfc2822'});
5372         } else {
5373                 print $cgi->header(
5374                         -type => $content_type,
5375                         -charset => 'utf-8');
5376         }
5378         # Optimization: skip generating the body if client asks only
5379         # for Last-Modified date.
5380         return if ($cgi->request_method() eq 'HEAD');
5382         # header variables
5383         my $title = "$site_name - $project/$action";
5384         my $feed_type = 'log';
5385         if (defined $hash) {
5386                 $title .= " - '$hash'";
5387                 $feed_type = 'branch log';
5388                 if (defined $file_name) {
5389                         $title .= " :: $file_name";
5390                         $feed_type = 'history';
5391                 }
5392         } elsif (defined $file_name) {
5393                 $title .= " - $file_name";
5394                 $feed_type = 'history';
5395         }
5396         $title .= " $feed_type";
5397         my $descr = git_get_project_description($project);
5398         if (defined $descr) {
5399                 $descr = esc_html($descr);
5400         } else {
5401                 $descr = "$project " .
5402                          ($format eq 'rss' ? 'RSS' : 'Atom') .
5403                          " feed";
5404         }
5405         my $owner = git_get_project_owner($project);
5406         $owner = esc_html($owner);
5408         #header
5409         my $alt_url;
5410         if (defined $file_name) {
5411                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5412         } elsif (defined $hash) {
5413                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5414         } else {
5415                 $alt_url = href(-full=>1, action=>"summary");
5416         }
5417         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5418         if ($format eq 'rss') {
5419                 print <<XML;
5420 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5421 <channel>
5422 XML
5423                 print "<title>$title</title>\n" .
5424                       "<link>$alt_url</link>\n" .
5425                       "<description>$descr</description>\n" .
5426                       "<language>en</language>\n";
5427         } elsif ($format eq 'atom') {
5428                 print <<XML;
5429 <feed xmlns="http://www.w3.org/2005/Atom">
5430 XML
5431                 print "<title>$title</title>\n" .
5432                       "<subtitle>$descr</subtitle>\n" .
5433                       '<link rel="alternate" type="text/html" href="' .
5434                       $alt_url . '" />' . "\n" .
5435                       '<link rel="self" type="' . $content_type . '" href="' .
5436                       $cgi->self_url() . '" />' . "\n" .
5437                       "<id>" . href(-full=>1) . "</id>\n" .
5438                       # use project owner for feed author
5439                       "<author><name>$owner</name></author>\n";
5440                 if (defined $favicon) {
5441                         print "<icon>" . esc_url($favicon) . "</icon>\n";
5442                 }
5443                 if (defined $logo_url) {
5444                         # not twice as wide as tall: 72 x 27 pixels
5445                         print "<logo>" . esc_url($logo) . "</logo>\n";
5446                 }
5447                 if (! %latest_date) {
5448                         # dummy date to keep the feed valid until commits trickle in:
5449                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
5450                 } else {
5451                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
5452                 }
5453         }
5455         # contents
5456         for (my $i = 0; $i <= $#commitlist; $i++) {
5457                 my %co = %{$commitlist[$i]};
5458                 my $commit = $co{'id'};
5459                 # we read 150, we always show 30 and the ones more recent than 48 hours
5460                 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5461                         last;
5462                 }
5463                 my %cd = parse_date($co{'author_epoch'});
5465                 # get list of changed files
5466                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5467                         $co{'parent'} || "--root",
5468                         $co{'id'}, "--", (defined $file_name ? $file_name : ())
5469                         or next;
5470                 my @difftree = map { chomp; $_ } <$fd>;
5471                 close $fd
5472                         or next;
5474                 # print element (entry, item)
5475                 my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
5476                 if ($format eq 'rss') {
5477                         print "<item>\n" .
5478                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
5479                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
5480                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5481                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5482                               "<link>$co_url</link>\n" .
5483                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
5484                               "<content:encoded>" .
5485                               "<![CDATA[\n";
5486                 } elsif ($format eq 'atom') {
5487                         print "<entry>\n" .
5488                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5489                               "<updated>$cd{'iso-8601'}</updated>\n" .
5490                               "<author>\n" .
5491                               "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
5492                         if ($co{'author_email'}) {
5493                                 print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
5494                         }
5495                         print "</author>\n" .
5496                               # use committer for contributor
5497                               "<contributor>\n" .
5498                               "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5499                         if ($co{'committer_email'}) {
5500                                 print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5501                         }
5502                         print "</contributor>\n" .
5503                               "<published>$cd{'iso-8601'}</published>\n" .
5504                               "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5505                               "<id>$co_url</id>\n" .
5506                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5507                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5508                 }
5509                 my $comment = $co{'comment'};
5510                 print "<pre>\n";
5511                 foreach my $line (@$comment) {
5512                         $line = esc_html($line);
5513                         print "$line\n";
5514                 }
5515                 print "</pre><ul>\n";
5516                 foreach my $difftree_line (@difftree) {
5517                         my %difftree = parse_difftree_raw_line($difftree_line);
5518                         next if !$difftree{'from_id'};
5520                         my $file = $difftree{'file'} || $difftree{'to_file'};
5522                         print "<li>" .
5523                               "[" .
5524                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5525                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5526                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5527                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
5528                                       -title => "diff"}, 'D');
5529                         if ($have_blame) {
5530                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
5531                                                              file_name=>$file, hash_base=>$commit),
5532                                               -title => "blame"}, 'B');
5533                         }
5534                         # if this is not a feed of a file history
5535                         if (!defined $file_name || $file_name ne $file) {
5536                                 print $cgi->a({-href => href(-full=>1, action=>"history",
5537                                                              file_name=>$file, hash=>$commit),
5538                                               -title => "history"}, 'H');
5539                         }
5540                         $file = esc_path($file);
5541                         print "] ".
5542                               "$file</li>\n";
5543                 }
5544                 if ($format eq 'rss') {
5545                         print "</ul>]]>\n" .
5546                               "</content:encoded>\n" .
5547                               "</item>\n";
5548                 } elsif ($format eq 'atom') {
5549                         print "</ul>\n</div>\n" .
5550                               "</content>\n" .
5551                               "</entry>\n";
5552                 }
5553         }
5555         # end of feed
5556         if ($format eq 'rss') {
5557                 print "</channel>\n</rss>\n";
5558         }       elsif ($format eq 'atom') {
5559                 print "</feed>\n";
5560         }
5563 sub git_rss {
5564         git_feed('rss');
5567 sub git_atom {
5568         git_feed('atom');
5571 sub git_opml {
5572         my @list = git_get_projects_list();
5574         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5575         print <<XML;
5576 <?xml version="1.0" encoding="utf-8"?>
5577 <opml version="1.0">
5578 <head>
5579   <title>$site_name OPML Export</title>
5580 </head>
5581 <body>
5582 <outline text="git RSS feeds">
5583 XML
5585         foreach my $pr (@list) {
5586                 my %proj = %$pr;
5587                 my $head = git_get_head_hash($proj{'path'});
5588                 if (!defined $head) {
5589                         next;
5590                 }
5591                 $git_dir = "$projectroot/$proj{'path'}";
5592                 my %co = parse_commit($head);
5593                 if (!%co) {
5594                         next;
5595                 }
5597                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5598                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
5599                 my $html = "$my_url?p=$proj{'path'};a=summary";
5600                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5601         }
5602         print <<XML;
5603 </outline>
5604 </body>
5605 </opml>
5606 XML