Code

gitweb: Always set 'from_file' and 'to_file' in parse_difftree_raw_line
[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 # fs traversing limit for getting project list
39 # the number is relative to the projectroot
40 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
42 # target of the home link on top of all pages
43 our $home_link = $my_uri || "/";
45 # string of the home link on top of all pages
46 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
48 # name of your site or organization to appear in page titles
49 # replace this with something more descriptive for clearer bookmarks
50 our $site_name = "++GITWEB_SITENAME++"
51                  || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
53 # filename of html text to include at top of each page
54 our $site_header = "++GITWEB_SITE_HEADER++";
55 # html text to include at home page
56 our $home_text = "++GITWEB_HOMETEXT++";
57 # filename of html text to include at bottom of each page
58 our $site_footer = "++GITWEB_SITE_FOOTER++";
60 # URI of stylesheets
61 our @stylesheets = ("++GITWEB_CSS++");
62 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
63 our $stylesheet = undef;
64 # URI of GIT logo (72x27 size)
65 our $logo = "++GITWEB_LOGO++";
66 # URI of GIT favicon, assumed to be image/png type
67 our $favicon = "++GITWEB_FAVICON++";
69 # URI and label (title) of GIT logo link
70 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
71 #our $logo_label = "git documentation";
72 our $logo_url = "http://git.or.cz/";
73 our $logo_label = "git homepage";
75 # source of projects list
76 our $projects_list = "++GITWEB_LIST++";
78 # the width (in characters) of the projects list "Description" column
79 our $projects_list_description_width = 25;
81 # default order of projects list
82 # valid values are none, project, descr, owner, and age
83 our $default_projects_order = "project";
85 # show repository only if this file exists
86 # (only effective if this variable evaluates to true)
87 our $export_ok = "++GITWEB_EXPORT_OK++";
89 # only allow viewing of repositories also shown on the overview page
90 our $strict_export = "++GITWEB_STRICT_EXPORT++";
92 # list of git base URLs used for URL to where fetch project from,
93 # i.e. full URL is "$git_base_url/$project"
94 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
96 # default blob_plain mimetype and default charset for text/plain blob
97 our $default_blob_plain_mimetype = 'text/plain';
98 our $default_text_plain_charset  = undef;
100 # file to use for guessing MIME types before trying /etc/mime.types
101 # (relative to the current git repository)
102 our $mimetypes_file = undef;
104 # assume this charset if line contains non-UTF-8 characters;
105 # it should be valid encoding (see Encoding::Supported(3pm) for list),
106 # for which encoding all byte sequences are valid, for example
107 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
108 # could be even 'utf-8' for the old behavior)
109 our $fallback_encoding = 'latin1';
111 # rename detection options for git-diff and git-diff-tree
112 # - default is '-M', with the cost proportional to
113 #   (number of removed files) * (number of new files).
114 # - more costly is '-C' (which implies '-M'), with the cost proportional to
115 #   (number of changed files + number of removed files) * (number of new files)
116 # - even more costly is '-C', '--find-copies-harder' with cost
117 #   (number of files in the original tree) * (number of new files)
118 # - one might want to include '-B' option, e.g. '-B', '-M'
119 our @diff_opts = ('-M'); # taken from git_commit
121 # information about snapshot formats that gitweb is capable of serving
122 our %known_snapshot_formats = (
123         # name => {
124         #       'display' => display name,
125         #       'type' => mime type,
126         #       'suffix' => filename suffix,
127         #       'format' => --format for git-archive,
128         #       'compressor' => [compressor command and arguments]
129         #                       (array reference, optional)}
130         #
131         'tgz' => {
132                 'display' => 'tar.gz',
133                 'type' => 'application/x-gzip',
134                 'suffix' => '.tar.gz',
135                 'format' => 'tar',
136                 'compressor' => ['gzip']},
138         'tbz2' => {
139                 'display' => 'tar.bz2',
140                 'type' => 'application/x-bzip2',
141                 'suffix' => '.tar.bz2',
142                 'format' => 'tar',
143                 'compressor' => ['bzip2']},
145         'zip' => {
146                 'display' => 'zip',
147                 'type' => 'application/x-zip',
148                 'suffix' => '.zip',
149                 'format' => 'zip'},
150 );
152 # Aliases so we understand old gitweb.snapshot values in repository
153 # configuration.
154 our %known_snapshot_format_aliases = (
155         'gzip'  => 'tgz',
156         'bzip2' => 'tbz2',
158         # backward compatibility: legacy gitweb config support
159         'x-gzip' => undef, 'gz' => undef,
160         'x-bzip2' => undef, 'bz2' => undef,
161         'x-zip' => undef, '' => undef,
162 );
164 # You define site-wide feature defaults here; override them with
165 # $GITWEB_CONFIG as necessary.
166 our %feature = (
167         # feature => {
168         #       'sub' => feature-sub (subroutine),
169         #       'override' => allow-override (boolean),
170         #       'default' => [ default options...] (array reference)}
171         #
172         # if feature is overridable (it means that allow-override has true value),
173         # then feature-sub will be called with default options as parameters;
174         # return value of feature-sub indicates if to enable specified feature
175         #
176         # if there is no 'sub' key (no feature-sub), then feature cannot be
177         # overriden
178         #
179         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
181         # Enable the 'blame' blob view, showing the last commit that modified
182         # each line in the file. This can be very CPU-intensive.
184         # To enable system wide have in $GITWEB_CONFIG
185         # $feature{'blame'}{'default'} = [1];
186         # To have project specific config enable override in $GITWEB_CONFIG
187         # $feature{'blame'}{'override'} = 1;
188         # and in project config gitweb.blame = 0|1;
189         'blame' => {
190                 'sub' => \&feature_blame,
191                 'override' => 0,
192                 'default' => [0]},
194         # Enable the 'snapshot' link, providing a compressed archive of any
195         # tree. This can potentially generate high traffic if you have large
196         # project.
198         # Value is a list of formats defined in %known_snapshot_formats that
199         # you wish to offer.
200         # To disable system wide have in $GITWEB_CONFIG
201         # $feature{'snapshot'}{'default'} = [];
202         # To have project specific config enable override in $GITWEB_CONFIG
203         # $feature{'snapshot'}{'override'} = 1;
204         # and in project config, a comma-separated list of formats or "none"
205         # to disable.  Example: gitweb.snapshot = tbz2,zip;
206         'snapshot' => {
207                 'sub' => \&feature_snapshot,
208                 'override' => 0,
209                 'default' => ['tgz']},
211         # Enable text search, which will list the commits which match author,
212         # committer or commit text to a given string.  Enabled by default.
213         # Project specific override is not supported.
214         'search' => {
215                 'override' => 0,
216                 'default' => [1]},
218         # Enable grep search, which will list the files in currently selected
219         # tree containing the given string. Enabled by default. This can be
220         # potentially CPU-intensive, of course.
222         # To enable system wide have in $GITWEB_CONFIG
223         # $feature{'grep'}{'default'} = [1];
224         # To have project specific config enable override in $GITWEB_CONFIG
225         # $feature{'grep'}{'override'} = 1;
226         # and in project config gitweb.grep = 0|1;
227         'grep' => {
228                 'override' => 0,
229                 'default' => [1]},
231         # Enable the pickaxe search, which will list the commits that modified
232         # a given string in a file. This can be practical and quite faster
233         # alternative to 'blame', but still potentially CPU-intensive.
235         # To enable system wide have in $GITWEB_CONFIG
236         # $feature{'pickaxe'}{'default'} = [1];
237         # To have project specific config enable override in $GITWEB_CONFIG
238         # $feature{'pickaxe'}{'override'} = 1;
239         # and in project config gitweb.pickaxe = 0|1;
240         'pickaxe' => {
241                 'sub' => \&feature_pickaxe,
242                 'override' => 0,
243                 'default' => [1]},
245         # Make gitweb use an alternative format of the URLs which can be
246         # more readable and natural-looking: project name is embedded
247         # directly in the path and the query string contains other
248         # auxiliary information. All gitweb installations recognize
249         # URL in either format; this configures in which formats gitweb
250         # generates links.
252         # To enable system wide have in $GITWEB_CONFIG
253         # $feature{'pathinfo'}{'default'} = [1];
254         # Project specific override is not supported.
256         # Note that you will need to change the default location of CSS,
257         # favicon, logo and possibly other files to an absolute URL. Also,
258         # if gitweb.cgi serves as your indexfile, you will need to force
259         # $my_uri to contain the script name in your $GITWEB_CONFIG.
260         'pathinfo' => {
261                 'override' => 0,
262                 'default' => [0]},
264         # Make gitweb consider projects in project root subdirectories
265         # to be forks of existing projects. Given project $projname.git,
266         # projects matching $projname/*.git will not be shown in the main
267         # projects list, instead a '+' mark will be added to $projname
268         # there and a 'forks' view will be enabled for the project, listing
269         # all the forks. If project list is taken from a file, forks have
270         # to be listed after the main project.
272         # To enable system wide have in $GITWEB_CONFIG
273         # $feature{'forks'}{'default'} = [1];
274         # Project specific override is not supported.
275         'forks' => {
276                 'override' => 0,
277                 'default' => [0]},
278 );
280 sub gitweb_check_feature {
281         my ($name) = @_;
282         return unless exists $feature{$name};
283         my ($sub, $override, @defaults) = (
284                 $feature{$name}{'sub'},
285                 $feature{$name}{'override'},
286                 @{$feature{$name}{'default'}});
287         if (!$override) { return @defaults; }
288         if (!defined $sub) {
289                 warn "feature $name is not overrideable";
290                 return @defaults;
291         }
292         return $sub->(@defaults);
295 sub feature_blame {
296         my ($val) = git_get_project_config('blame', '--bool');
298         if ($val eq 'true') {
299                 return 1;
300         } elsif ($val eq 'false') {
301                 return 0;
302         }
304         return $_[0];
307 sub feature_snapshot {
308         my (@fmts) = @_;
310         my ($val) = git_get_project_config('snapshot');
312         if ($val) {
313                 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
314         }
316         return @fmts;
319 sub feature_grep {
320         my ($val) = git_get_project_config('grep', '--bool');
322         if ($val eq 'true') {
323                 return (1);
324         } elsif ($val eq 'false') {
325                 return (0);
326         }
328         return ($_[0]);
331 sub feature_pickaxe {
332         my ($val) = git_get_project_config('pickaxe', '--bool');
334         if ($val eq 'true') {
335                 return (1);
336         } elsif ($val eq 'false') {
337                 return (0);
338         }
340         return ($_[0]);
343 # checking HEAD file with -e is fragile if the repository was
344 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
345 # and then pruned.
346 sub check_head_link {
347         my ($dir) = @_;
348         my $headfile = "$dir/HEAD";
349         return ((-e $headfile) ||
350                 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
353 sub check_export_ok {
354         my ($dir) = @_;
355         return (check_head_link($dir) &&
356                 (!$export_ok || -e "$dir/$export_ok"));
359 # process alternate names for backward compatibility
360 # filter out unsupported (unknown) snapshot formats
361 sub filter_snapshot_fmts {
362         my @fmts = @_;
364         @fmts = map {
365                 exists $known_snapshot_format_aliases{$_} ?
366                        $known_snapshot_format_aliases{$_} : $_} @fmts;
367         @fmts = grep(exists $known_snapshot_formats{$_}, @fmts);
371 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
372 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
374 # version of the core git binary
375 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
377 $projects_list ||= $projectroot;
379 # ======================================================================
380 # input validation and dispatch
381 our $action = $cgi->param('a');
382 if (defined $action) {
383         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
384                 die_error(undef, "Invalid action parameter");
385         }
388 # parameters which are pathnames
389 our $project = $cgi->param('p');
390 if (defined $project) {
391         if (!validate_pathname($project) ||
392             !(-d "$projectroot/$project") ||
393             !check_head_link("$projectroot/$project") ||
394             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
395             ($strict_export && !project_in_list($project))) {
396                 undef $project;
397                 die_error(undef, "No such project");
398         }
401 our $file_name = $cgi->param('f');
402 if (defined $file_name) {
403         if (!validate_pathname($file_name)) {
404                 die_error(undef, "Invalid file parameter");
405         }
408 our $file_parent = $cgi->param('fp');
409 if (defined $file_parent) {
410         if (!validate_pathname($file_parent)) {
411                 die_error(undef, "Invalid file parent parameter");
412         }
415 # parameters which are refnames
416 our $hash = $cgi->param('h');
417 if (defined $hash) {
418         if (!validate_refname($hash)) {
419                 die_error(undef, "Invalid hash parameter");
420         }
423 our $hash_parent = $cgi->param('hp');
424 if (defined $hash_parent) {
425         if (!validate_refname($hash_parent)) {
426                 die_error(undef, "Invalid hash parent parameter");
427         }
430 our $hash_base = $cgi->param('hb');
431 if (defined $hash_base) {
432         if (!validate_refname($hash_base)) {
433                 die_error(undef, "Invalid hash base parameter");
434         }
437 my %allowed_options = (
438         "--no-merges" => [ qw(rss atom log shortlog history) ],
439 );
441 our @extra_options = $cgi->param('opt');
442 if (defined @extra_options) {
443         foreach my $opt (@extra_options) {
444                 if (not exists $allowed_options{$opt}) {
445                         die_error(undef, "Invalid option parameter");
446                 }
447                 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
448                         die_error(undef, "Invalid option parameter for this action");
449                 }
450         }
453 our $hash_parent_base = $cgi->param('hpb');
454 if (defined $hash_parent_base) {
455         if (!validate_refname($hash_parent_base)) {
456                 die_error(undef, "Invalid hash parent base parameter");
457         }
460 # other parameters
461 our $page = $cgi->param('pg');
462 if (defined $page) {
463         if ($page =~ m/[^0-9]/) {
464                 die_error(undef, "Invalid page parameter");
465         }
468 our $searchtype = $cgi->param('st');
469 if (defined $searchtype) {
470         if ($searchtype =~ m/[^a-z]/) {
471                 die_error(undef, "Invalid searchtype parameter");
472         }
475 our $searchtext = $cgi->param('s');
476 our $search_regexp;
477 if (defined $searchtext) {
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                 hash => "h",
602                 hash_parent => "hp",
603                 hash_base => "hb",
604                 hash_parent_base => "hpb",
605                 page => "pg",
606                 order => "o",
607                 searchtext => "s",
608                 searchtype => "st",
609                 snapshot_format => "sf",
610                 extra_options => "opt",
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                         if (ref($params{$name}) eq "ARRAY") {
634                                 foreach my $par (@{$params{$name}}) {
635                                         push @result, $symbol . "=" . esc_param($par);
636                                 }
637                         } else {
638                                 push @result, $symbol . "=" . esc_param($params{$name});
639                         }
640                 }
641         }
642         $href .= "?" . join(';', @result) if scalar @result;
644         return $href;
648 ## ======================================================================
649 ## validation, quoting/unquoting and escaping
651 sub validate_pathname {
652         my $input = shift || return undef;
654         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
655         # at the beginning, at the end, and between slashes.
656         # also this catches doubled slashes
657         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
658                 return undef;
659         }
660         # no null characters
661         if ($input =~ m!\0!) {
662                 return undef;
663         }
664         return $input;
667 sub validate_refname {
668         my $input = shift || return undef;
670         # textual hashes are O.K.
671         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
672                 return $input;
673         }
674         # it must be correct pathname
675         $input = validate_pathname($input)
676                 or return undef;
677         # restrictions on ref name according to git-check-ref-format
678         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
679                 return undef;
680         }
681         return $input;
684 # decode sequences of octets in utf8 into Perl's internal form,
685 # which is utf-8 with utf8 flag set if needed.  gitweb writes out
686 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
687 sub to_utf8 {
688         my $str = shift;
689         my $res;
690         eval { $res = decode_utf8($str, Encode::FB_CROAK); };
691         if (defined $res) {
692                 return $res;
693         } else {
694                 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
695         }
698 # quote unsafe chars, but keep the slash, even when it's not
699 # correct, but quoted slashes look too horrible in bookmarks
700 sub esc_param {
701         my $str = shift;
702         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
703         $str =~ s/\+/%2B/g;
704         $str =~ s/ /\+/g;
705         return $str;
708 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
709 sub esc_url {
710         my $str = shift;
711         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
712         $str =~ s/\+/%2B/g;
713         $str =~ s/ /\+/g;
714         return $str;
717 # replace invalid utf8 character with SUBSTITUTION sequence
718 sub esc_html ($;%) {
719         my $str = shift;
720         my %opts = @_;
722         $str = to_utf8($str);
723         $str = $cgi->escapeHTML($str);
724         if ($opts{'-nbsp'}) {
725                 $str =~ s/ /&nbsp;/g;
726         }
727         $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
728         return $str;
731 # quote control characters and escape filename to HTML
732 sub esc_path {
733         my $str = shift;
734         my %opts = @_;
736         $str = to_utf8($str);
737         $str = $cgi->escapeHTML($str);
738         if ($opts{'-nbsp'}) {
739                 $str =~ s/ /&nbsp;/g;
740         }
741         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
742         return $str;
745 # Make control characters "printable", using character escape codes (CEC)
746 sub quot_cec {
747         my $cntrl = shift;
748         my %es = ( # character escape codes, aka escape sequences
749                    "\t" => '\t',   # tab            (HT)
750                    "\n" => '\n',   # line feed      (LF)
751                    "\r" => '\r',   # carrige return (CR)
752                    "\f" => '\f',   # form feed      (FF)
753                    "\b" => '\b',   # backspace      (BS)
754                    "\a" => '\a',   # alarm (bell)   (BEL)
755                    "\e" => '\e',   # escape         (ESC)
756                    "\013" => '\v', # vertical tab   (VT)
757                    "\000" => '\0', # nul character  (NUL)
758                    );
759         my $chr = ( (exists $es{$cntrl})
760                     ? $es{$cntrl}
761                     : sprintf('\%03o', ord($cntrl)) );
762         return "<span class=\"cntrl\">$chr</span>";
765 # Alternatively use unicode control pictures codepoints,
766 # Unicode "printable representation" (PR)
767 sub quot_upr {
768         my $cntrl = shift;
769         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
770         return "<span class=\"cntrl\">$chr</span>";
773 # git may return quoted and escaped filenames
774 sub unquote {
775         my $str = shift;
777         sub unq {
778                 my $seq = shift;
779                 my %es = ( # character escape codes, aka escape sequences
780                         't' => "\t",   # tab            (HT, TAB)
781                         'n' => "\n",   # newline        (NL)
782                         'r' => "\r",   # return         (CR)
783                         'f' => "\f",   # form feed      (FF)
784                         'b' => "\b",   # backspace      (BS)
785                         'a' => "\a",   # alarm (bell)   (BEL)
786                         'e' => "\e",   # escape         (ESC)
787                         'v' => "\013", # vertical tab   (VT)
788                 );
790                 if ($seq =~ m/^[0-7]{1,3}$/) {
791                         # octal char sequence
792                         return chr(oct($seq));
793                 } elsif (exists $es{$seq}) {
794                         # C escape sequence, aka character escape code
795                         return $es{$seq}
796                 }
797                 # quoted ordinary character
798                 return $seq;
799         }
801         if ($str =~ m/^"(.*)"$/) {
802                 # needs unquoting
803                 $str = $1;
804                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
805         }
806         return $str;
809 # escape tabs (convert tabs to spaces)
810 sub untabify {
811         my $line = shift;
813         while ((my $pos = index($line, "\t")) != -1) {
814                 if (my $count = (8 - ($pos % 8))) {
815                         my $spaces = ' ' x $count;
816                         $line =~ s/\t/$spaces/;
817                 }
818         }
820         return $line;
823 sub project_in_list {
824         my $project = shift;
825         my @list = git_get_projects_list();
826         return @list && scalar(grep { $_->{'path'} eq $project } @list);
829 ## ----------------------------------------------------------------------
830 ## HTML aware string manipulation
832 sub chop_str {
833         my $str = shift;
834         my $len = shift;
835         my $add_len = shift || 10;
837         # allow only $len chars, but don't cut a word if it would fit in $add_len
838         # if it doesn't fit, cut it if it's still longer than the dots we would add
839         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
840         my $body = $1;
841         my $tail = $2;
842         if (length($tail) > 4) {
843                 $tail = " ...";
844                 $body =~ s/&[^;]*$//; # remove chopped character entities
845         }
846         return "$body$tail";
849 # takes the same arguments as chop_str, but also wraps a <span> around the
850 # result with a title attribute if it does get chopped. Additionally, the
851 # string is HTML-escaped.
852 sub chop_and_escape_str {
853         my $str = shift;
854         my $len = shift;
855         my $add_len = shift || 10;
857         my $chopped = chop_str($str, $len, $add_len);
858         if ($chopped eq $str) {
859                 return esc_html($chopped);
860         } else {
861                 return qq{<span title="} . esc_html($str) . qq{">} .
862                         esc_html($chopped) . qq{</span>};
863         }
866 ## ----------------------------------------------------------------------
867 ## functions returning short strings
869 # CSS class for given age value (in seconds)
870 sub age_class {
871         my $age = shift;
873         if (!defined $age) {
874                 return "noage";
875         } elsif ($age < 60*60*2) {
876                 return "age0";
877         } elsif ($age < 60*60*24*2) {
878                 return "age1";
879         } else {
880                 return "age2";
881         }
884 # convert age in seconds to "nn units ago" string
885 sub age_string {
886         my $age = shift;
887         my $age_str;
889         if ($age > 60*60*24*365*2) {
890                 $age_str = (int $age/60/60/24/365);
891                 $age_str .= " years ago";
892         } elsif ($age > 60*60*24*(365/12)*2) {
893                 $age_str = int $age/60/60/24/(365/12);
894                 $age_str .= " months ago";
895         } elsif ($age > 60*60*24*7*2) {
896                 $age_str = int $age/60/60/24/7;
897                 $age_str .= " weeks ago";
898         } elsif ($age > 60*60*24*2) {
899                 $age_str = int $age/60/60/24;
900                 $age_str .= " days ago";
901         } elsif ($age > 60*60*2) {
902                 $age_str = int $age/60/60;
903                 $age_str .= " hours ago";
904         } elsif ($age > 60*2) {
905                 $age_str = int $age/60;
906                 $age_str .= " min ago";
907         } elsif ($age > 2) {
908                 $age_str = int $age;
909                 $age_str .= " sec ago";
910         } else {
911                 $age_str .= " right now";
912         }
913         return $age_str;
916 use constant {
917         S_IFINVALID => 0030000,
918         S_IFGITLINK => 0160000,
919 };
921 # submodule/subproject, a commit object reference
922 sub S_ISGITLINK($) {
923         my $mode = shift;
925         return (($mode & S_IFMT) == S_IFGITLINK)
928 # convert file mode in octal to symbolic file mode string
929 sub mode_str {
930         my $mode = oct shift;
932         if (S_ISGITLINK($mode)) {
933                 return 'm---------';
934         } elsif (S_ISDIR($mode & S_IFMT)) {
935                 return 'drwxr-xr-x';
936         } elsif (S_ISLNK($mode)) {
937                 return 'lrwxrwxrwx';
938         } elsif (S_ISREG($mode)) {
939                 # git cares only about the executable bit
940                 if ($mode & S_IXUSR) {
941                         return '-rwxr-xr-x';
942                 } else {
943                         return '-rw-r--r--';
944                 };
945         } else {
946                 return '----------';
947         }
950 # convert file mode in octal to file type string
951 sub file_type {
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                 return "file";
968         } else {
969                 return "unknown";
970         }
973 # convert file mode in octal to file type description string
974 sub file_type_long {
975         my $mode = shift;
977         if ($mode !~ m/^[0-7]+$/) {
978                 return $mode;
979         } else {
980                 $mode = oct $mode;
981         }
983         if (S_ISGITLINK($mode)) {
984                 return "submodule";
985         } elsif (S_ISDIR($mode & S_IFMT)) {
986                 return "directory";
987         } elsif (S_ISLNK($mode)) {
988                 return "symlink";
989         } elsif (S_ISREG($mode)) {
990                 if ($mode & S_IXUSR) {
991                         return "executable";
992                 } else {
993                         return "file";
994                 };
995         } else {
996                 return "unknown";
997         }
1001 ## ----------------------------------------------------------------------
1002 ## functions returning short HTML fragments, or transforming HTML fragments
1003 ## which don't belong to other sections
1005 # format line of commit message.
1006 sub format_log_line_html {
1007         my $line = shift;
1009         $line = esc_html($line, -nbsp=>1);
1010         if ($line =~ m/([0-9a-fA-F]{8,40})/) {
1011                 my $hash_text = $1;
1012                 my $link =
1013                         $cgi->a({-href => href(action=>"object", hash=>$hash_text),
1014                                 -class => "text"}, $hash_text);
1015                 $line =~ s/$hash_text/$link/;
1016         }
1017         return $line;
1020 # format marker of refs pointing to given object
1021 sub format_ref_marker {
1022         my ($refs, $id) = @_;
1023         my $markers = '';
1025         if (defined $refs->{$id}) {
1026                 foreach my $ref (@{$refs->{$id}}) {
1027                         my ($type, $name) = qw();
1028                         # e.g. tags/v2.6.11 or heads/next
1029                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
1030                                 $type = $1;
1031                                 $name = $2;
1032                         } else {
1033                                 $type = "ref";
1034                                 $name = $ref;
1035                         }
1037                         $markers .= " <span class=\"$type\" title=\"$ref\">" .
1038                                     esc_html($name) . "</span>";
1039                 }
1040         }
1042         if ($markers) {
1043                 return ' <span class="refs">'. $markers . '</span>';
1044         } else {
1045                 return "";
1046         }
1049 # format, perhaps shortened and with markers, title line
1050 sub format_subject_html {
1051         my ($long, $short, $href, $extra) = @_;
1052         $extra = '' unless defined($extra);
1054         if (length($short) < length($long)) {
1055                 return $cgi->a({-href => $href, -class => "list subject",
1056                                 -title => to_utf8($long)},
1057                        esc_html($short) . $extra);
1058         } else {
1059                 return $cgi->a({-href => $href, -class => "list subject"},
1060                        esc_html($long)  . $extra);
1061         }
1064 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1065 sub format_git_diff_header_line {
1066         my $line = shift;
1067         my $diffinfo = shift;
1068         my ($from, $to) = @_;
1070         if ($diffinfo->{'nparents'}) {
1071                 # combined diff
1072                 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1073                 if ($to->{'href'}) {
1074                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1075                                          esc_path($to->{'file'}));
1076                 } else { # file was deleted (no href)
1077                         $line .= esc_path($to->{'file'});
1078                 }
1079         } else {
1080                 # "ordinary" diff
1081                 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1082                 if ($from->{'href'}) {
1083                         $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1084                                          'a/' . esc_path($from->{'file'}));
1085                 } else { # file was added (no href)
1086                         $line .= 'a/' . esc_path($from->{'file'});
1087                 }
1088                 $line .= ' ';
1089                 if ($to->{'href'}) {
1090                         $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1091                                          'b/' . esc_path($to->{'file'}));
1092                 } else { # file was deleted
1093                         $line .= 'b/' . esc_path($to->{'file'});
1094                 }
1095         }
1097         return "<div class=\"diff header\">$line</div>\n";
1100 # format extended diff header line, before patch itself
1101 sub format_extended_diff_header_line {
1102         my $line = shift;
1103         my $diffinfo = shift;
1104         my ($from, $to) = @_;
1106         # match <path>
1107         if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1108                 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1109                                        esc_path($from->{'file'}));
1110         }
1111         if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1112                 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1113                                  esc_path($to->{'file'}));
1114         }
1115         # match single <mode>
1116         if ($line =~ m/\s(\d{6})$/) {
1117                 $line .= '<span class="info"> (' .
1118                          file_type_long($1) .
1119                          ')</span>';
1120         }
1121         # match <hash>
1122         if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1123                 # can match only for combined diff
1124                 $line = 'index ';
1125                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1126                         if ($from->{'href'}[$i]) {
1127                                 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1128                                                   -class=>"hash"},
1129                                                  substr($diffinfo->{'from_id'}[$i],0,7));
1130                         } else {
1131                                 $line .= '0' x 7;
1132                         }
1133                         # separator
1134                         $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1135                 }
1136                 $line .= '..';
1137                 if ($to->{'href'}) {
1138                         $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1139                                          substr($diffinfo->{'to_id'},0,7));
1140                 } else {
1141                         $line .= '0' x 7;
1142                 }
1144         } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1145                 # can match only for ordinary diff
1146                 my ($from_link, $to_link);
1147                 if ($from->{'href'}) {
1148                         $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1149                                              substr($diffinfo->{'from_id'},0,7));
1150                 } else {
1151                         $from_link = '0' x 7;
1152                 }
1153                 if ($to->{'href'}) {
1154                         $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1155                                            substr($diffinfo->{'to_id'},0,7));
1156                 } else {
1157                         $to_link = '0' x 7;
1158                 }
1159                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1160                 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1161         }
1163         return $line . "<br/>\n";
1166 # format from-file/to-file diff header
1167 sub format_diff_from_to_header {
1168         my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1169         my $line;
1170         my $result = '';
1172         $line = $from_line;
1173         #assert($line =~ m/^---/) if DEBUG;
1174         # no extra formatting for "^--- /dev/null"
1175         if (! $diffinfo->{'nparents'}) {
1176                 # ordinary (single parent) diff
1177                 if ($line =~ m!^--- "?a/!) {
1178                         if ($from->{'href'}) {
1179                                 $line = '--- a/' .
1180                                         $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1181                                                 esc_path($from->{'file'}));
1182                         } else {
1183                                 $line = '--- a/' .
1184                                         esc_path($from->{'file'});
1185                         }
1186                 }
1187                 $result .= qq!<div class="diff from_file">$line</div>\n!;
1189         } else {
1190                 # combined diff (merge commit)
1191                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1192                         if ($from->{'href'}[$i]) {
1193                                 $line = '--- ' .
1194                                         $cgi->a({-href=>href(action=>"blobdiff",
1195                                                              hash_parent=>$diffinfo->{'from_id'}[$i],
1196                                                              hash_parent_base=>$parents[$i],
1197                                                              file_parent=>$from->{'file'}[$i],
1198                                                              hash=>$diffinfo->{'to_id'},
1199                                                              hash_base=>$hash,
1200                                                              file_name=>$to->{'file'}),
1201                                                  -class=>"path",
1202                                                  -title=>"diff" . ($i+1)},
1203                                                 $i+1) .
1204                                         '/' .
1205                                         $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1206                                                 esc_path($from->{'file'}[$i]));
1207                         } else {
1208                                 $line = '--- /dev/null';
1209                         }
1210                         $result .= qq!<div class="diff from_file">$line</div>\n!;
1211                 }
1212         }
1214         $line = $to_line;
1215         #assert($line =~ m/^\+\+\+/) if DEBUG;
1216         # no extra formatting for "^+++ /dev/null"
1217         if ($line =~ m!^\+\+\+ "?b/!) {
1218                 if ($to->{'href'}) {
1219                         $line = '+++ b/' .
1220                                 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1221                                         esc_path($to->{'file'}));
1222                 } else {
1223                         $line = '+++ b/' .
1224                                 esc_path($to->{'file'});
1225                 }
1226         }
1227         $result .= qq!<div class="diff to_file">$line</div>\n!;
1229         return $result;
1232 # create note for patch simplified by combined diff
1233 sub format_diff_cc_simplified {
1234         my ($diffinfo, @parents) = @_;
1235         my $result = '';
1237         $result .= "<div class=\"diff header\">" .
1238                    "diff --cc ";
1239         if (!is_deleted($diffinfo)) {
1240                 $result .= $cgi->a({-href => href(action=>"blob",
1241                                                   hash_base=>$hash,
1242                                                   hash=>$diffinfo->{'to_id'},
1243                                                   file_name=>$diffinfo->{'to_file'}),
1244                                     -class => "path"},
1245                                    esc_path($diffinfo->{'to_file'}));
1246         } else {
1247                 $result .= esc_path($diffinfo->{'to_file'});
1248         }
1249         $result .= "</div>\n" . # class="diff header"
1250                    "<div class=\"diff nodifferences\">" .
1251                    "Simple merge" .
1252                    "</div>\n"; # class="diff nodifferences"
1254         return $result;
1257 # format patch (diff) line (not to be used for diff headers)
1258 sub format_diff_line {
1259         my $line = shift;
1260         my ($from, $to) = @_;
1261         my $diff_class = "";
1263         chomp $line;
1265         if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1266                 # combined diff
1267                 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1268                 if ($line =~ m/^\@{3}/) {
1269                         $diff_class = " chunk_header";
1270                 } elsif ($line =~ m/^\\/) {
1271                         $diff_class = " incomplete";
1272                 } elsif ($prefix =~ tr/+/+/) {
1273                         $diff_class = " add";
1274                 } elsif ($prefix =~ tr/-/-/) {
1275                         $diff_class = " rem";
1276                 }
1277         } else {
1278                 # assume ordinary diff
1279                 my $char = substr($line, 0, 1);
1280                 if ($char eq '+') {
1281                         $diff_class = " add";
1282                 } elsif ($char eq '-') {
1283                         $diff_class = " rem";
1284                 } elsif ($char eq '@') {
1285                         $diff_class = " chunk_header";
1286                 } elsif ($char eq "\\") {
1287                         $diff_class = " incomplete";
1288                 }
1289         }
1290         $line = untabify($line);
1291         if ($from && $to && $line =~ m/^\@{2} /) {
1292                 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1293                         $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1295                 $from_lines = 0 unless defined $from_lines;
1296                 $to_lines   = 0 unless defined $to_lines;
1298                 if ($from->{'href'}) {
1299                         $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1300                                              -class=>"list"}, $from_text);
1301                 }
1302                 if ($to->{'href'}) {
1303                         $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1304                                              -class=>"list"}, $to_text);
1305                 }
1306                 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1307                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1308                 return "<div class=\"diff$diff_class\">$line</div>\n";
1309         } elsif ($from && $to && $line =~ m/^\@{3}/) {
1310                 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1311                 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1313                 @from_text = split(' ', $ranges);
1314                 for (my $i = 0; $i < @from_text; ++$i) {
1315                         ($from_start[$i], $from_nlines[$i]) =
1316                                 (split(',', substr($from_text[$i], 1)), 0);
1317                 }
1319                 $to_text   = pop @from_text;
1320                 $to_start  = pop @from_start;
1321                 $to_nlines = pop @from_nlines;
1323                 $line = "<span class=\"chunk_info\">$prefix ";
1324                 for (my $i = 0; $i < @from_text; ++$i) {
1325                         if ($from->{'href'}[$i]) {
1326                                 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1327                                                   -class=>"list"}, $from_text[$i]);
1328                         } else {
1329                                 $line .= $from_text[$i];
1330                         }
1331                         $line .= " ";
1332                 }
1333                 if ($to->{'href'}) {
1334                         $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1335                                           -class=>"list"}, $to_text);
1336                 } else {
1337                         $line .= $to_text;
1338                 }
1339                 $line .= " $prefix</span>" .
1340                          "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1341                 return "<div class=\"diff$diff_class\">$line</div>\n";
1342         }
1343         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1346 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1347 # linked.  Pass the hash of the tree/commit to snapshot.
1348 sub format_snapshot_links {
1349         my ($hash) = @_;
1350         my @snapshot_fmts = gitweb_check_feature('snapshot');
1351         @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1352         my $num_fmts = @snapshot_fmts;
1353         if ($num_fmts > 1) {
1354                 # A parenthesized list of links bearing format names.
1355                 # e.g. "snapshot (_tar.gz_ _zip_)"
1356                 return "snapshot (" . join(' ', map
1357                         $cgi->a({
1358                                 -href => href(
1359                                         action=>"snapshot",
1360                                         hash=>$hash,
1361                                         snapshot_format=>$_
1362                                 )
1363                         }, $known_snapshot_formats{$_}{'display'})
1364                 , @snapshot_fmts) . ")";
1365         } elsif ($num_fmts == 1) {
1366                 # A single "snapshot" link whose tooltip bears the format name.
1367                 # i.e. "_snapshot_"
1368                 my ($fmt) = @snapshot_fmts;
1369                 return
1370                         $cgi->a({
1371                                 -href => href(
1372                                         action=>"snapshot",
1373                                         hash=>$hash,
1374                                         snapshot_format=>$fmt
1375                                 ),
1376                                 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1377                         }, "snapshot");
1378         } else { # $num_fmts == 0
1379                 return undef;
1380         }
1383 ## ----------------------------------------------------------------------
1384 ## git utility subroutines, invoking git commands
1386 # returns path to the core git executable and the --git-dir parameter as list
1387 sub git_cmd {
1388         return $GIT, '--git-dir='.$git_dir;
1391 # returns path to the core git executable and the --git-dir parameter as string
1392 sub git_cmd_str {
1393         return join(' ', git_cmd());
1396 # get HEAD ref of given project as hash
1397 sub git_get_head_hash {
1398         my $project = shift;
1399         my $o_git_dir = $git_dir;
1400         my $retval = undef;
1401         $git_dir = "$projectroot/$project";
1402         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1403                 my $head = <$fd>;
1404                 close $fd;
1405                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1406                         $retval = $1;
1407                 }
1408         }
1409         if (defined $o_git_dir) {
1410                 $git_dir = $o_git_dir;
1411         }
1412         return $retval;
1415 # get type of given object
1416 sub git_get_type {
1417         my $hash = shift;
1419         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1420         my $type = <$fd>;
1421         close $fd or return;
1422         chomp $type;
1423         return $type;
1426 sub git_get_project_config {
1427         my ($key, $type) = @_;
1429         return unless ($key);
1430         $key =~ s/^gitweb\.//;
1431         return if ($key =~ m/\W/);
1433         my @x = (git_cmd(), 'config');
1434         if (defined $type) { push @x, $type; }
1435         push @x, "--get";
1436         push @x, "gitweb.$key";
1437         my $val = qx(@x);
1438         chomp $val;
1439         return ($val);
1442 # get hash of given path at given ref
1443 sub git_get_hash_by_path {
1444         my $base = shift;
1445         my $path = shift || return undef;
1446         my $type = shift;
1448         $path =~ s,/+$,,;
1450         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1451                 or die_error(undef, "Open git-ls-tree failed");
1452         my $line = <$fd>;
1453         close $fd or return undef;
1455         if (!defined $line) {
1456                 # there is no tree or hash given by $path at $base
1457                 return undef;
1458         }
1460         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1461         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1462         if (defined $type && $type ne $2) {
1463                 # type doesn't match
1464                 return undef;
1465         }
1466         return $3;
1469 # get path of entry with given hash at given tree-ish (ref)
1470 # used to get 'from' filename for combined diff (merge commit) for renames
1471 sub git_get_path_by_hash {
1472         my $base = shift || return;
1473         my $hash = shift || return;
1475         local $/ = "\0";
1477         open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1478                 or return undef;
1479         while (my $line = <$fd>) {
1480                 chomp $line;
1482                 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423  gitweb'
1483                 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f  gitweb/README'
1484                 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1485                         close $fd;
1486                         return $1;
1487                 }
1488         }
1489         close $fd;
1490         return undef;
1493 ## ......................................................................
1494 ## git utility functions, directly accessing git repository
1496 sub git_get_project_description {
1497         my $path = shift;
1499         open my $fd, "$projectroot/$path/description" or return undef;
1500         my $descr = <$fd>;
1501         close $fd;
1502         if (defined $descr) {
1503                 chomp $descr;
1504         }
1505         return $descr;
1508 sub git_get_project_url_list {
1509         my $path = shift;
1511         open my $fd, "$projectroot/$path/cloneurl" or return;
1512         my @git_project_url_list = map { chomp; $_ } <$fd>;
1513         close $fd;
1515         return wantarray ? @git_project_url_list : \@git_project_url_list;
1518 sub git_get_projects_list {
1519         my ($filter) = @_;
1520         my @list;
1522         $filter ||= '';
1523         $filter =~ s/\.git$//;
1525         my ($check_forks) = gitweb_check_feature('forks');
1527         if (-d $projects_list) {
1528                 # search in directory
1529                 my $dir = $projects_list . ($filter ? "/$filter" : '');
1530                 # remove the trailing "/"
1531                 $dir =~ s!/+$!!;
1532                 my $pfxlen = length("$dir");
1533                 my $pfxdepth = ($dir =~ tr!/!!);
1535                 File::Find::find({
1536                         follow_fast => 1, # follow symbolic links
1537                         follow_skip => 2, # ignore duplicates
1538                         dangling_symlinks => 0, # ignore dangling symlinks, silently
1539                         wanted => sub {
1540                                 # skip project-list toplevel, if we get it.
1541                                 return if (m!^[/.]$!);
1542                                 # only directories can be git repositories
1543                                 return unless (-d $_);
1544                                 # don't traverse too deep (Find is super slow on os x)
1545                                 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
1546                                         $File::Find::prune = 1;
1547                                         return;
1548                                 }
1550                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
1551                                 # we check related file in $projectroot
1552                                 if ($check_forks and $subdir =~ m#/.#) {
1553                                         $File::Find::prune = 1;
1554                                 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1555                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1556                                         $File::Find::prune = 1;
1557                                 }
1558                         },
1559                 }, "$dir");
1561         } elsif (-f $projects_list) {
1562                 # read from file(url-encoded):
1563                 # 'git%2Fgit.git Linus+Torvalds'
1564                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1565                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1566                 my %paths;
1567                 open my ($fd), $projects_list or return;
1568         PROJECT:
1569                 while (my $line = <$fd>) {
1570                         chomp $line;
1571                         my ($path, $owner) = split ' ', $line;
1572                         $path = unescape($path);
1573                         $owner = unescape($owner);
1574                         if (!defined $path) {
1575                                 next;
1576                         }
1577                         if ($filter ne '') {
1578                                 # looking for forks;
1579                                 my $pfx = substr($path, 0, length($filter));
1580                                 if ($pfx ne $filter) {
1581                                         next PROJECT;
1582                                 }
1583                                 my $sfx = substr($path, length($filter));
1584                                 if ($sfx !~ /^\/.*\.git$/) {
1585                                         next PROJECT;
1586                                 }
1587                         } elsif ($check_forks) {
1588                         PATH:
1589                                 foreach my $filter (keys %paths) {
1590                                         # looking for forks;
1591                                         my $pfx = substr($path, 0, length($filter));
1592                                         if ($pfx ne $filter) {
1593                                                 next PATH;
1594                                         }
1595                                         my $sfx = substr($path, length($filter));
1596                                         if ($sfx !~ /^\/.*\.git$/) {
1597                                                 next PATH;
1598                                         }
1599                                         # is a fork, don't include it in
1600                                         # the list
1601                                         next PROJECT;
1602                                 }
1603                         }
1604                         if (check_export_ok("$projectroot/$path")) {
1605                                 my $pr = {
1606                                         path => $path,
1607                                         owner => to_utf8($owner),
1608                                 };
1609                                 push @list, $pr;
1610                                 (my $forks_path = $path) =~ s/\.git$//;
1611                                 $paths{$forks_path}++;
1612                         }
1613                 }
1614                 close $fd;
1615         }
1616         return @list;
1619 our $gitweb_project_owner = undef;
1620 sub git_get_project_list_from_file {
1622         return if (defined $gitweb_project_owner);
1624         $gitweb_project_owner = {};
1625         # read from file (url-encoded):
1626         # 'git%2Fgit.git Linus+Torvalds'
1627         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1628         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1629         if (-f $projects_list) {
1630                 open (my $fd , $projects_list);
1631                 while (my $line = <$fd>) {
1632                         chomp $line;
1633                         my ($pr, $ow) = split ' ', $line;
1634                         $pr = unescape($pr);
1635                         $ow = unescape($ow);
1636                         $gitweb_project_owner->{$pr} = to_utf8($ow);
1637                 }
1638                 close $fd;
1639         }
1642 sub git_get_project_owner {
1643         my $project = shift;
1644         my $owner;
1646         return undef unless $project;
1648         if (!defined $gitweb_project_owner) {
1649                 git_get_project_list_from_file();
1650         }
1652         if (exists $gitweb_project_owner->{$project}) {
1653                 $owner = $gitweb_project_owner->{$project};
1654         }
1655         if (!defined $owner) {
1656                 $owner = get_file_owner("$projectroot/$project");
1657         }
1659         return $owner;
1662 sub git_get_last_activity {
1663         my ($path) = @_;
1664         my $fd;
1666         $git_dir = "$projectroot/$path";
1667         open($fd, "-|", git_cmd(), 'for-each-ref',
1668              '--format=%(committer)',
1669              '--sort=-committerdate',
1670              '--count=1',
1671              'refs/heads') or return;
1672         my $most_recent = <$fd>;
1673         close $fd or return;
1674         if (defined $most_recent &&
1675             $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1676                 my $timestamp = $1;
1677                 my $age = time - $timestamp;
1678                 return ($age, age_string($age));
1679         }
1680         return (undef, undef);
1683 sub git_get_references {
1684         my $type = shift || "";
1685         my %refs;
1686         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1687         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1688         open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1689                 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1690                 or return;
1692         while (my $line = <$fd>) {
1693                 chomp $line;
1694                 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1695                         if (defined $refs{$1}) {
1696                                 push @{$refs{$1}}, $2;
1697                         } else {
1698                                 $refs{$1} = [ $2 ];
1699                         }
1700                 }
1701         }
1702         close $fd or return;
1703         return \%refs;
1706 sub git_get_rev_name_tags {
1707         my $hash = shift || return undef;
1709         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1710                 or return;
1711         my $name_rev = <$fd>;
1712         close $fd;
1714         if ($name_rev =~ m|^$hash tags/(.*)$|) {
1715                 return $1;
1716         } else {
1717                 # catches also '$hash undefined' output
1718                 return undef;
1719         }
1722 ## ----------------------------------------------------------------------
1723 ## parse to hash functions
1725 sub parse_date {
1726         my $epoch = shift;
1727         my $tz = shift || "-0000";
1729         my %date;
1730         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1731         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1732         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1733         $date{'hour'} = $hour;
1734         $date{'minute'} = $min;
1735         $date{'mday'} = $mday;
1736         $date{'day'} = $days[$wday];
1737         $date{'month'} = $months[$mon];
1738         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1739                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1740         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1741                              $mday, $months[$mon], $hour ,$min;
1742         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1743                              1900+$year, $mon, $mday, $hour ,$min, $sec;
1745         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1746         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1747         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1748         $date{'hour_local'} = $hour;
1749         $date{'minute_local'} = $min;
1750         $date{'tz_local'} = $tz;
1751         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1752                                   1900+$year, $mon+1, $mday,
1753                                   $hour, $min, $sec, $tz);
1754         return %date;
1757 sub parse_tag {
1758         my $tag_id = shift;
1759         my %tag;
1760         my @comment;
1762         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1763         $tag{'id'} = $tag_id;
1764         while (my $line = <$fd>) {
1765                 chomp $line;
1766                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1767                         $tag{'object'} = $1;
1768                 } elsif ($line =~ m/^type (.+)$/) {
1769                         $tag{'type'} = $1;
1770                 } elsif ($line =~ m/^tag (.+)$/) {
1771                         $tag{'name'} = $1;
1772                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1773                         $tag{'author'} = $1;
1774                         $tag{'epoch'} = $2;
1775                         $tag{'tz'} = $3;
1776                 } elsif ($line =~ m/--BEGIN/) {
1777                         push @comment, $line;
1778                         last;
1779                 } elsif ($line eq "") {
1780                         last;
1781                 }
1782         }
1783         push @comment, <$fd>;
1784         $tag{'comment'} = \@comment;
1785         close $fd or return;
1786         if (!defined $tag{'name'}) {
1787                 return
1788         };
1789         return %tag
1792 sub parse_commit_text {
1793         my ($commit_text, $withparents) = @_;
1794         my @commit_lines = split '\n', $commit_text;
1795         my %co;
1797         pop @commit_lines; # Remove '\0'
1799         if (! @commit_lines) {
1800                 return;
1801         }
1803         my $header = shift @commit_lines;
1804         if ($header !~ m/^[0-9a-fA-F]{40}/) {
1805                 return;
1806         }
1807         ($co{'id'}, my @parents) = split ' ', $header;
1808         while (my $line = shift @commit_lines) {
1809                 last if $line eq "\n";
1810                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1811                         $co{'tree'} = $1;
1812                 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
1813                         push @parents, $1;
1814                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1815                         $co{'author'} = $1;
1816                         $co{'author_epoch'} = $2;
1817                         $co{'author_tz'} = $3;
1818                         if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1819                                 $co{'author_name'}  = $1;
1820                                 $co{'author_email'} = $2;
1821                         } else {
1822                                 $co{'author_name'} = $co{'author'};
1823                         }
1824                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1825                         $co{'committer'} = $1;
1826                         $co{'committer_epoch'} = $2;
1827                         $co{'committer_tz'} = $3;
1828                         $co{'committer_name'} = $co{'committer'};
1829                         if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1830                                 $co{'committer_name'}  = $1;
1831                                 $co{'committer_email'} = $2;
1832                         } else {
1833                                 $co{'committer_name'} = $co{'committer'};
1834                         }
1835                 }
1836         }
1837         if (!defined $co{'tree'}) {
1838                 return;
1839         };
1840         $co{'parents'} = \@parents;
1841         $co{'parent'} = $parents[0];
1843         foreach my $title (@commit_lines) {
1844                 $title =~ s/^    //;
1845                 if ($title ne "") {
1846                         $co{'title'} = chop_str($title, 80, 5);
1847                         # remove leading stuff of merges to make the interesting part visible
1848                         if (length($title) > 50) {
1849                                 $title =~ s/^Automatic //;
1850                                 $title =~ s/^merge (of|with) /Merge ... /i;
1851                                 if (length($title) > 50) {
1852                                         $title =~ s/(http|rsync):\/\///;
1853                                 }
1854                                 if (length($title) > 50) {
1855                                         $title =~ s/(master|www|rsync)\.//;
1856                                 }
1857                                 if (length($title) > 50) {
1858                                         $title =~ s/kernel.org:?//;
1859                                 }
1860                                 if (length($title) > 50) {
1861                                         $title =~ s/\/pub\/scm//;
1862                                 }
1863                         }
1864                         $co{'title_short'} = chop_str($title, 50, 5);
1865                         last;
1866                 }
1867         }
1868         if ($co{'title'} eq "") {
1869                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1870         }
1871         # remove added spaces
1872         foreach my $line (@commit_lines) {
1873                 $line =~ s/^    //;
1874         }
1875         $co{'comment'} = \@commit_lines;
1877         my $age = time - $co{'committer_epoch'};
1878         $co{'age'} = $age;
1879         $co{'age_string'} = age_string($age);
1880         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1881         if ($age > 60*60*24*7*2) {
1882                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1883                 $co{'age_string_age'} = $co{'age_string'};
1884         } else {
1885                 $co{'age_string_date'} = $co{'age_string'};
1886                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1887         }
1888         return %co;
1891 sub parse_commit {
1892         my ($commit_id) = @_;
1893         my %co;
1895         local $/ = "\0";
1897         open my $fd, "-|", git_cmd(), "rev-list",
1898                 "--parents",
1899                 "--header",
1900                 "--max-count=1",
1901                 $commit_id,
1902                 "--",
1903                 or die_error(undef, "Open git-rev-list failed");
1904         %co = parse_commit_text(<$fd>, 1);
1905         close $fd;
1907         return %co;
1910 sub parse_commits {
1911         my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
1912         my @cos;
1914         $maxcount ||= 1;
1915         $skip ||= 0;
1917         local $/ = "\0";
1919         open my $fd, "-|", git_cmd(), "rev-list",
1920                 "--header",
1921                 ($arg ? ($arg) : ()),
1922                 ("--max-count=" . $maxcount),
1923                 ("--skip=" . $skip),
1924                 @extra_options,
1925                 $commit_id,
1926                 "--",
1927                 ($filename ? ($filename) : ())
1928                 or die_error(undef, "Open git-rev-list failed");
1929         while (my $line = <$fd>) {
1930                 my %co = parse_commit_text($line);
1931                 push @cos, \%co;
1932         }
1933         close $fd;
1935         return wantarray ? @cos : \@cos;
1938 # parse ref from ref_file, given by ref_id, with given type
1939 sub parse_ref {
1940         my $ref_file = shift;
1941         my $ref_id = shift;
1942         my $type = shift || git_get_type($ref_id);
1943         my %ref_item;
1945         $ref_item{'type'} = $type;
1946         $ref_item{'id'} = $ref_id;
1947         $ref_item{'epoch'} = 0;
1948         $ref_item{'age'} = "unknown";
1949         if ($type eq "tag") {
1950                 my %tag = parse_tag($ref_id);
1951                 $ref_item{'comment'} = $tag{'comment'};
1952                 if ($tag{'type'} eq "commit") {
1953                         my %co = parse_commit($tag{'object'});
1954                         $ref_item{'epoch'} = $co{'committer_epoch'};
1955                         $ref_item{'age'} = $co{'age_string'};
1956                 } elsif (defined($tag{'epoch'})) {
1957                         my $age = time - $tag{'epoch'};
1958                         $ref_item{'epoch'} = $tag{'epoch'};
1959                         $ref_item{'age'} = age_string($age);
1960                 }
1961                 $ref_item{'reftype'} = $tag{'type'};
1962                 $ref_item{'name'} = $tag{'name'};
1963                 $ref_item{'refid'} = $tag{'object'};
1964         } elsif ($type eq "commit"){
1965                 my %co = parse_commit($ref_id);
1966                 $ref_item{'reftype'} = "commit";
1967                 $ref_item{'name'} = $ref_file;
1968                 $ref_item{'title'} = $co{'title'};
1969                 $ref_item{'refid'} = $ref_id;
1970                 $ref_item{'epoch'} = $co{'committer_epoch'};
1971                 $ref_item{'age'} = $co{'age_string'};
1972         } else {
1973                 $ref_item{'reftype'} = $type;
1974                 $ref_item{'name'} = $ref_file;
1975                 $ref_item{'refid'} = $ref_id;
1976         }
1978         return %ref_item;
1981 # parse line of git-diff-tree "raw" output
1982 sub parse_difftree_raw_line {
1983         my $line = shift;
1984         my %res;
1986         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1987         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1988         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1989                 $res{'from_mode'} = $1;
1990                 $res{'to_mode'} = $2;
1991                 $res{'from_id'} = $3;
1992                 $res{'to_id'} = $4;
1993                 $res{'status'} = $5;
1994                 $res{'similarity'} = $6;
1995                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1996                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1997                 } else {
1998                         $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
1999                 }
2000         }
2001         # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2002         # combined diff (for merge commit)
2003         elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2004                 $res{'nparents'}  = length($1);
2005                 $res{'from_mode'} = [ split(' ', $2) ];
2006                 $res{'to_mode'} = pop @{$res{'from_mode'}};
2007                 $res{'from_id'} = [ split(' ', $3) ];
2008                 $res{'to_id'} = pop @{$res{'from_id'}};
2009                 $res{'status'} = [ split('', $4) ];
2010                 $res{'to_file'} = unquote($5);
2011         }
2012         # 'c512b523472485aef4fff9e57b229d9d243c967f'
2013         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2014                 $res{'commit'} = $1;
2015         }
2017         return wantarray ? %res : \%res;
2020 # wrapper: return parsed line of git-diff-tree "raw" output
2021 # (the argument might be raw line, or parsed info)
2022 sub parsed_difftree_line {
2023         my $line_or_ref = shift;
2025         if (ref($line_or_ref) eq "HASH") {
2026                 # pre-parsed (or generated by hand)
2027                 return $line_or_ref;
2028         } else {
2029                 return parse_difftree_raw_line($line_or_ref);
2030         }
2033 # parse line of git-ls-tree output
2034 sub parse_ls_tree_line ($;%) {
2035         my $line = shift;
2036         my %opts = @_;
2037         my %res;
2039         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
2040         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2042         $res{'mode'} = $1;
2043         $res{'type'} = $2;
2044         $res{'hash'} = $3;
2045         if ($opts{'-z'}) {
2046                 $res{'name'} = $4;
2047         } else {
2048                 $res{'name'} = unquote($4);
2049         }
2051         return wantarray ? %res : \%res;
2054 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2055 sub parse_from_to_diffinfo {
2056         my ($diffinfo, $from, $to, @parents) = @_;
2058         if ($diffinfo->{'nparents'}) {
2059                 # combined diff
2060                 $from->{'file'} = [];
2061                 $from->{'href'} = [];
2062                 fill_from_file_info($diffinfo, @parents)
2063                         unless exists $diffinfo->{'from_file'};
2064                 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2065                         $from->{'file'}[$i] =
2066                                 defined $diffinfo->{'from_file'}[$i] ?
2067                                         $diffinfo->{'from_file'}[$i] :
2068                                         $diffinfo->{'to_file'};
2069                         if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2070                                 $from->{'href'}[$i] = href(action=>"blob",
2071                                                            hash_base=>$parents[$i],
2072                                                            hash=>$diffinfo->{'from_id'}[$i],
2073                                                            file_name=>$from->{'file'}[$i]);
2074                         } else {
2075                                 $from->{'href'}[$i] = undef;
2076                         }
2077                 }
2078         } else {
2079                 # ordinary (not combined) diff
2080                 $from->{'file'} = $diffinfo->{'from_file'};
2081                 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2082                         $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2083                                                hash=>$diffinfo->{'from_id'},
2084                                                file_name=>$from->{'file'});
2085                 } else {
2086                         delete $from->{'href'};
2087                 }
2088         }
2090         $to->{'file'} = $diffinfo->{'to_file'};
2091         if (!is_deleted($diffinfo)) { # file exists in result
2092                 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2093                                      hash=>$diffinfo->{'to_id'},
2094                                      file_name=>$to->{'file'});
2095         } else {
2096                 delete $to->{'href'};
2097         }
2100 ## ......................................................................
2101 ## parse to array of hashes functions
2103 sub git_get_heads_list {
2104         my $limit = shift;
2105         my @headslist;
2107         open my $fd, '-|', git_cmd(), 'for-each-ref',
2108                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2109                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2110                 'refs/heads'
2111                 or return;
2112         while (my $line = <$fd>) {
2113                 my %ref_item;
2115                 chomp $line;
2116                 my ($refinfo, $committerinfo) = split(/\0/, $line);
2117                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2118                 my ($committer, $epoch, $tz) =
2119                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2120                 $name =~ s!^refs/heads/!!;
2122                 $ref_item{'name'}  = $name;
2123                 $ref_item{'id'}    = $hash;
2124                 $ref_item{'title'} = $title || '(no commit message)';
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                 }
2132                 push @headslist, \%ref_item;
2133         }
2134         close $fd;
2136         return wantarray ? @headslist : \@headslist;
2139 sub git_get_tags_list {
2140         my $limit = shift;
2141         my @tagslist;
2143         open my $fd, '-|', git_cmd(), 'for-each-ref',
2144                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2145                 '--format=%(objectname) %(objecttype) %(refname) '.
2146                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2147                 'refs/tags'
2148                 or return;
2149         while (my $line = <$fd>) {
2150                 my %ref_item;
2152                 chomp $line;
2153                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2154                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2155                 my ($creator, $epoch, $tz) =
2156                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2157                 $name =~ s!^refs/tags/!!;
2159                 $ref_item{'type'} = $type;
2160                 $ref_item{'id'} = $id;
2161                 $ref_item{'name'} = $name;
2162                 if ($type eq "tag") {
2163                         $ref_item{'subject'} = $title;
2164                         $ref_item{'reftype'} = $reftype;
2165                         $ref_item{'refid'}   = $refid;
2166                 } else {
2167                         $ref_item{'reftype'} = $type;
2168                         $ref_item{'refid'}   = $id;
2169                 }
2171                 if ($type eq "tag" || $type eq "commit") {
2172                         $ref_item{'epoch'} = $epoch;
2173                         if ($epoch) {
2174                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2175                         } else {
2176                                 $ref_item{'age'} = "unknown";
2177                         }
2178                 }
2180                 push @tagslist, \%ref_item;
2181         }
2182         close $fd;
2184         return wantarray ? @tagslist : \@tagslist;
2187 ## ----------------------------------------------------------------------
2188 ## filesystem-related functions
2190 sub get_file_owner {
2191         my $path = shift;
2193         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2194         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2195         if (!defined $gcos) {
2196                 return undef;
2197         }
2198         my $owner = $gcos;
2199         $owner =~ s/[,;].*$//;
2200         return to_utf8($owner);
2203 ## ......................................................................
2204 ## mimetype related functions
2206 sub mimetype_guess_file {
2207         my $filename = shift;
2208         my $mimemap = shift;
2209         -r $mimemap or return undef;
2211         my %mimemap;
2212         open(MIME, $mimemap) or return undef;
2213         while (<MIME>) {
2214                 next if m/^#/; # skip comments
2215                 my ($mime, $exts) = split(/\t+/);
2216                 if (defined $exts) {
2217                         my @exts = split(/\s+/, $exts);
2218                         foreach my $ext (@exts) {
2219                                 $mimemap{$ext} = $mime;
2220                         }
2221                 }
2222         }
2223         close(MIME);
2225         $filename =~ /\.([^.]*)$/;
2226         return $mimemap{$1};
2229 sub mimetype_guess {
2230         my $filename = shift;
2231         my $mime;
2232         $filename =~ /\./ or return undef;
2234         if ($mimetypes_file) {
2235                 my $file = $mimetypes_file;
2236                 if ($file !~ m!^/!) { # if it is relative path
2237                         # it is relative to project
2238                         $file = "$projectroot/$project/$file";
2239                 }
2240                 $mime = mimetype_guess_file($filename, $file);
2241         }
2242         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2243         return $mime;
2246 sub blob_mimetype {
2247         my $fd = shift;
2248         my $filename = shift;
2250         if ($filename) {
2251                 my $mime = mimetype_guess($filename);
2252                 $mime and return $mime;
2253         }
2255         # just in case
2256         return $default_blob_plain_mimetype unless $fd;
2258         if (-T $fd) {
2259                 return 'text/plain' .
2260                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
2261         } elsif (! $filename) {
2262                 return 'application/octet-stream';
2263         } elsif ($filename =~ m/\.png$/i) {
2264                 return 'image/png';
2265         } elsif ($filename =~ m/\.gif$/i) {
2266                 return 'image/gif';
2267         } elsif ($filename =~ m/\.jpe?g$/i) {
2268                 return 'image/jpeg';
2269         } else {
2270                 return 'application/octet-stream';
2271         }
2274 ## ======================================================================
2275 ## functions printing HTML: header, footer, error page
2277 sub git_header_html {
2278         my $status = shift || "200 OK";
2279         my $expires = shift;
2281         my $title = "$site_name";
2282         if (defined $project) {
2283                 $title .= " - " . to_utf8($project);
2284                 if (defined $action) {
2285                         $title .= "/$action";
2286                         if (defined $file_name) {
2287                                 $title .= " - " . esc_path($file_name);
2288                                 if ($action eq "tree" && $file_name !~ m|/$|) {
2289                                         $title .= "/";
2290                                 }
2291                         }
2292                 }
2293         }
2294         my $content_type;
2295         # require explicit support from the UA if we are to send the page as
2296         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2297         # we have to do this because MSIE sometimes globs '*/*', pretending to
2298         # support xhtml+xml but choking when it gets what it asked for.
2299         if (defined $cgi->http('HTTP_ACCEPT') &&
2300             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2301             $cgi->Accept('application/xhtml+xml') != 0) {
2302                 $content_type = 'application/xhtml+xml';
2303         } else {
2304                 $content_type = 'text/html';
2305         }
2306         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2307                            -status=> $status, -expires => $expires);
2308         my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2309         print <<EOF;
2310 <?xml version="1.0" encoding="utf-8"?>
2311 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2312 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2313 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2314 <!-- git core binaries version $git_version -->
2315 <head>
2316 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2317 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2318 <meta name="robots" content="index, nofollow"/>
2319 <title>$title</title>
2320 EOF
2321 # print out each stylesheet that exist
2322         if (defined $stylesheet) {
2323 #provides backwards capability for those people who define style sheet in a config file
2324                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2325         } else {
2326                 foreach my $stylesheet (@stylesheets) {
2327                         next unless $stylesheet;
2328                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2329                 }
2330         }
2331         if (defined $project) {
2332                 printf('<link rel="alternate" title="%s log RSS feed" '.
2333                        'href="%s" type="application/rss+xml" />'."\n",
2334                        esc_param($project), href(action=>"rss"));
2335                 printf('<link rel="alternate" title="%s log RSS feed (no merges)" '.
2336                        'href="%s" type="application/rss+xml" />'."\n",
2337                        esc_param($project), href(action=>"rss",
2338                                                  extra_options=>"--no-merges"));
2339                 printf('<link rel="alternate" title="%s log Atom feed" '.
2340                        'href="%s" type="application/atom+xml" />'."\n",
2341                        esc_param($project), href(action=>"atom"));
2342                 printf('<link rel="alternate" title="%s log Atom feed (no merges)" '.
2343                        'href="%s" type="application/atom+xml" />'."\n",
2344                        esc_param($project), href(action=>"atom",
2345                                                  extra_options=>"--no-merges"));
2346         } else {
2347                 printf('<link rel="alternate" title="%s projects list" '.
2348                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
2349                        $site_name, href(project=>undef, action=>"project_index"));
2350                 printf('<link rel="alternate" title="%s projects feeds" '.
2351                        'href="%s" type="text/x-opml"/>'."\n",
2352                        $site_name, href(project=>undef, action=>"opml"));
2353         }
2354         if (defined $favicon) {
2355                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
2356         }
2358         print "</head>\n" .
2359               "<body>\n";
2361         if (-f $site_header) {
2362                 open (my $fd, $site_header);
2363                 print <$fd>;
2364                 close $fd;
2365         }
2367         print "<div class=\"page_header\">\n" .
2368               $cgi->a({-href => esc_url($logo_url),
2369                        -title => $logo_label},
2370                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2371         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2372         if (defined $project) {
2373                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2374                 if (defined $action) {
2375                         print " / $action";
2376                 }
2377                 print "\n";
2378         }
2379         print "</div>\n";
2381         my ($have_search) = gitweb_check_feature('search');
2382         if ((defined $project) && ($have_search)) {
2383                 if (!defined $searchtext) {
2384                         $searchtext = "";
2385                 }
2386                 my $search_hash;
2387                 if (defined $hash_base) {
2388                         $search_hash = $hash_base;
2389                 } elsif (defined $hash) {
2390                         $search_hash = $hash;
2391                 } else {
2392                         $search_hash = "HEAD";
2393                 }
2394                 my $action = $my_uri;
2395                 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2396                 if ($use_pathinfo) {
2397                         $action .= "/$project";
2398                 } else {
2399                         $cgi->param("p", $project);
2400                 }
2401                 $cgi->param("a", "search");
2402                 $cgi->param("h", $search_hash);
2403                 print $cgi->startform(-method => "get", -action => $action) .
2404                       "<div class=\"search\">\n" .
2405                       (!$use_pathinfo && $cgi->hidden(-name => "p") . "\n") .
2406                       $cgi->hidden(-name => "a") . "\n" .
2407                       $cgi->hidden(-name => "h") . "\n" .
2408                       $cgi->popup_menu(-name => 'st', -default => 'commit',
2409                                        -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2410                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2411                       " search:\n",
2412                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2413                       "</div>" .
2414                       $cgi->end_form() . "\n";
2415         }
2418 sub git_footer_html {
2419         print "<div class=\"page_footer\">\n";
2420         if (defined $project) {
2421                 my $descr = git_get_project_description($project);
2422                 if (defined $descr) {
2423                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2424                 }
2425                 print $cgi->a({-href => href(action=>"rss"),
2426                               -class => "rss_logo"}, "RSS") . " ";
2427                 print $cgi->a({-href => href(action=>"atom"),
2428                               -class => "rss_logo"}, "Atom") . "\n";
2429         } else {
2430                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
2431                               -class => "rss_logo"}, "OPML") . " ";
2432                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2433                               -class => "rss_logo"}, "TXT") . "\n";
2434         }
2435         print "</div>\n" ;
2437         if (-f $site_footer) {
2438                 open (my $fd, $site_footer);
2439                 print <$fd>;
2440                 close $fd;
2441         }
2443         print "</body>\n" .
2444               "</html>";
2447 sub die_error {
2448         my $status = shift || "403 Forbidden";
2449         my $error = shift || "Malformed query, file missing or permission denied";
2451         git_header_html($status);
2452         print <<EOF;
2453 <div class="page_body">
2454 <br /><br />
2455 $status - $error
2456 <br />
2457 </div>
2458 EOF
2459         git_footer_html();
2460         exit;
2463 ## ----------------------------------------------------------------------
2464 ## functions printing or outputting HTML: navigation
2466 sub git_print_page_nav {
2467         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2468         $extra = '' if !defined $extra; # pager or formats
2470         my @navs = qw(summary shortlog log commit commitdiff tree);
2471         if ($suppress) {
2472                 @navs = grep { $_ ne $suppress } @navs;
2473         }
2475         my %arg = map { $_ => {action=>$_} } @navs;
2476         if (defined $head) {
2477                 for (qw(commit commitdiff)) {
2478                         $arg{$_}{'hash'} = $head;
2479                 }
2480                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2481                         for (qw(shortlog log)) {
2482                                 $arg{$_}{'hash'} = $head;
2483                         }
2484                 }
2485         }
2486         $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2487         $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2489         print "<div class=\"page_nav\">\n" .
2490                 (join " | ",
2491                  map { $_ eq $current ?
2492                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2493                  } @navs);
2494         print "<br/>\n$extra<br/>\n" .
2495               "</div>\n";
2498 sub format_paging_nav {
2499         my ($action, $hash, $head, $page, $nrevs) = @_;
2500         my $paging_nav;
2503         if ($hash ne $head || $page) {
2504                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2505         } else {
2506                 $paging_nav .= "HEAD";
2507         }
2509         if ($page > 0) {
2510                 $paging_nav .= " &sdot; " .
2511                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
2512                                  -accesskey => "p", -title => "Alt-p"}, "prev");
2513         } else {
2514                 $paging_nav .= " &sdot; prev";
2515         }
2517         if ($nrevs >= (100 * ($page+1)-1)) {
2518                 $paging_nav .= " &sdot; " .
2519                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
2520                                  -accesskey => "n", -title => "Alt-n"}, "next");
2521         } else {
2522                 $paging_nav .= " &sdot; next";
2523         }
2525         return $paging_nav;
2528 ## ......................................................................
2529 ## functions printing or outputting HTML: div
2531 sub git_print_header_div {
2532         my ($action, $title, $hash, $hash_base) = @_;
2533         my %args = ();
2535         $args{'action'} = $action;
2536         $args{'hash'} = $hash if $hash;
2537         $args{'hash_base'} = $hash_base if $hash_base;
2539         print "<div class=\"header\">\n" .
2540               $cgi->a({-href => href(%args), -class => "title"},
2541               $title ? $title : $action) .
2542               "\n</div>\n";
2545 #sub git_print_authorship (\%) {
2546 sub git_print_authorship {
2547         my $co = shift;
2549         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2550         print "<div class=\"author_date\">" .
2551               esc_html($co->{'author_name'}) .
2552               " [$ad{'rfc2822'}";
2553         if ($ad{'hour_local'} < 6) {
2554                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2555                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2556         } else {
2557                 printf(" (%02d:%02d %s)",
2558                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2559         }
2560         print "]</div>\n";
2563 sub git_print_page_path {
2564         my $name = shift;
2565         my $type = shift;
2566         my $hb = shift;
2569         print "<div class=\"page_path\">";
2570         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2571                       -title => 'tree root'}, to_utf8("[$project]"));
2572         print " / ";
2573         if (defined $name) {
2574                 my @dirname = split '/', $name;
2575                 my $basename = pop @dirname;
2576                 my $fullname = '';
2578                 foreach my $dir (@dirname) {
2579                         $fullname .= ($fullname ? '/' : '') . $dir;
2580                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2581                                                      hash_base=>$hb),
2582                                       -title => $fullname}, esc_path($dir));
2583                         print " / ";
2584                 }
2585                 if (defined $type && $type eq 'blob') {
2586                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2587                                                      hash_base=>$hb),
2588                                       -title => $name}, esc_path($basename));
2589                 } elsif (defined $type && $type eq 'tree') {
2590                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2591                                                      hash_base=>$hb),
2592                                       -title => $name}, esc_path($basename));
2593                         print " / ";
2594                 } else {
2595                         print esc_path($basename);
2596                 }
2597         }
2598         print "<br/></div>\n";
2601 # sub git_print_log (\@;%) {
2602 sub git_print_log ($;%) {
2603         my $log = shift;
2604         my %opts = @_;
2606         if ($opts{'-remove_title'}) {
2607                 # remove title, i.e. first line of log
2608                 shift @$log;
2609         }
2610         # remove leading empty lines
2611         while (defined $log->[0] && $log->[0] eq "") {
2612                 shift @$log;
2613         }
2615         # print log
2616         my $signoff = 0;
2617         my $empty = 0;
2618         foreach my $line (@$log) {
2619                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2620                         $signoff = 1;
2621                         $empty = 0;
2622                         if (! $opts{'-remove_signoff'}) {
2623                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2624                                 next;
2625                         } else {
2626                                 # remove signoff lines
2627                                 next;
2628                         }
2629                 } else {
2630                         $signoff = 0;
2631                 }
2633                 # print only one empty line
2634                 # do not print empty line after signoff
2635                 if ($line eq "") {
2636                         next if ($empty || $signoff);
2637                         $empty = 1;
2638                 } else {
2639                         $empty = 0;
2640                 }
2642                 print format_log_line_html($line) . "<br/>\n";
2643         }
2645         if ($opts{'-final_empty_line'}) {
2646                 # end with single empty line
2647                 print "<br/>\n" unless $empty;
2648         }
2651 # return link target (what link points to)
2652 sub git_get_link_target {
2653         my $hash = shift;
2654         my $link_target;
2656         # read link
2657         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2658                 or return;
2659         {
2660                 local $/;
2661                 $link_target = <$fd>;
2662         }
2663         close $fd
2664                 or return;
2666         return $link_target;
2669 # given link target, and the directory (basedir) the link is in,
2670 # return target of link relative to top directory (top tree);
2671 # return undef if it is not possible (including absolute links).
2672 sub normalize_link_target {
2673         my ($link_target, $basedir, $hash_base) = @_;
2675         # we can normalize symlink target only if $hash_base is provided
2676         return unless $hash_base;
2678         # absolute symlinks (beginning with '/') cannot be normalized
2679         return if (substr($link_target, 0, 1) eq '/');
2681         # normalize link target to path from top (root) tree (dir)
2682         my $path;
2683         if ($basedir) {
2684                 $path = $basedir . '/' . $link_target;
2685         } else {
2686                 # we are in top (root) tree (dir)
2687                 $path = $link_target;
2688         }
2690         # remove //, /./, and /../
2691         my @path_parts;
2692         foreach my $part (split('/', $path)) {
2693                 # discard '.' and ''
2694                 next if (!$part || $part eq '.');
2695                 # handle '..'
2696                 if ($part eq '..') {
2697                         if (@path_parts) {
2698                                 pop @path_parts;
2699                         } else {
2700                                 # link leads outside repository (outside top dir)
2701                                 return;
2702                         }
2703                 } else {
2704                         push @path_parts, $part;
2705                 }
2706         }
2707         $path = join('/', @path_parts);
2709         return $path;
2712 # print tree entry (row of git_tree), but without encompassing <tr> element
2713 sub git_print_tree_entry {
2714         my ($t, $basedir, $hash_base, $have_blame) = @_;
2716         my %base_key = ();
2717         $base_key{'hash_base'} = $hash_base if defined $hash_base;
2719         # The format of a table row is: mode list link.  Where mode is
2720         # the mode of the entry, list is the name of the entry, an href,
2721         # and link is the action links of the entry.
2723         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2724         if ($t->{'type'} eq "blob") {
2725                 print "<td class=\"list\">" .
2726                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2727                                                file_name=>"$basedir$t->{'name'}", %base_key),
2728                                 -class => "list"}, esc_path($t->{'name'}));
2729                 if (S_ISLNK(oct $t->{'mode'})) {
2730                         my $link_target = git_get_link_target($t->{'hash'});
2731                         if ($link_target) {
2732                                 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2733                                 if (defined $norm_target) {
2734                                         print " -> " .
2735                                               $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2736                                                                      file_name=>$norm_target),
2737                                                        -title => $norm_target}, esc_path($link_target));
2738                                 } else {
2739                                         print " -> " . esc_path($link_target);
2740                                 }
2741                         }
2742                 }
2743                 print "</td>\n";
2744                 print "<td class=\"link\">";
2745                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2746                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2747                               "blob");
2748                 if ($have_blame) {
2749                         print " | " .
2750                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2751                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
2752                                       "blame");
2753                 }
2754                 if (defined $hash_base) {
2755                         print " | " .
2756                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2757                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2758                                       "history");
2759                 }
2760                 print " | " .
2761                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2762                                                file_name=>"$basedir$t->{'name'}")},
2763                                 "raw");
2764                 print "</td>\n";
2766         } elsif ($t->{'type'} eq "tree") {
2767                 print "<td class=\"list\">";
2768                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2769                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2770                               esc_path($t->{'name'}));
2771                 print "</td>\n";
2772                 print "<td class=\"link\">";
2773                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2774                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2775                               "tree");
2776                 if (defined $hash_base) {
2777                         print " | " .
2778                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2779                                                      file_name=>"$basedir$t->{'name'}")},
2780                                       "history");
2781                 }
2782                 print "</td>\n";
2783         } else {
2784                 # unknown object: we can only present history for it
2785                 # (this includes 'commit' object, i.e. submodule support)
2786                 print "<td class=\"list\">" .
2787                       esc_path($t->{'name'}) .
2788                       "</td>\n";
2789                 print "<td class=\"link\">";
2790                 if (defined $hash_base) {
2791                         print $cgi->a({-href => href(action=>"history",
2792                                                      hash_base=>$hash_base,
2793                                                      file_name=>"$basedir$t->{'name'}")},
2794                                       "history");
2795                 }
2796                 print "</td>\n";
2797         }
2800 ## ......................................................................
2801 ## functions printing large fragments of HTML
2803 # get pre-image filenames for merge (combined) diff
2804 sub fill_from_file_info {
2805         my ($diff, @parents) = @_;
2807         $diff->{'from_file'} = [ ];
2808         $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
2809         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2810                 if ($diff->{'status'}[$i] eq 'R' ||
2811                     $diff->{'status'}[$i] eq 'C') {
2812                         $diff->{'from_file'}[$i] =
2813                                 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
2814                 }
2815         }
2817         return $diff;
2820 # is current raw difftree line of file deletion
2821 sub is_deleted {
2822         my $diffinfo = shift;
2824         return $diffinfo->{'to_id'} eq ('0' x 40);
2827 # does patch correspond to [previous] difftree raw line
2828 # $diffinfo  - hashref of parsed raw diff format
2829 # $patchinfo - hashref of parsed patch diff format
2830 #              (the same keys as in $diffinfo)
2831 sub is_patch_split {
2832         my ($diffinfo, $patchinfo) = @_;
2834         return defined $diffinfo && defined $patchinfo
2835                 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
2839 sub git_difftree_body {
2840         my ($difftree, $hash, @parents) = @_;
2841         my ($parent) = $parents[0];
2842         my ($have_blame) = gitweb_check_feature('blame');
2843         print "<div class=\"list_head\">\n";
2844         if ($#{$difftree} > 10) {
2845                 print(($#{$difftree} + 1) . " files changed:\n");
2846         }
2847         print "</div>\n";
2849         print "<table class=\"" .
2850               (@parents > 1 ? "combined " : "") .
2851               "diff_tree\">\n";
2853         # header only for combined diff in 'commitdiff' view
2854         my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
2855         if ($has_header) {
2856                 # table header
2857                 print "<thead><tr>\n" .
2858                        "<th></th><th></th>\n"; # filename, patchN link
2859                 for (my $i = 0; $i < @parents; $i++) {
2860                         my $par = $parents[$i];
2861                         print "<th>" .
2862                               $cgi->a({-href => href(action=>"commitdiff",
2863                                                      hash=>$hash, hash_parent=>$par),
2864                                        -title => 'commitdiff to parent number ' .
2865                                                   ($i+1) . ': ' . substr($par,0,7)},
2866                                       $i+1) .
2867                               "&nbsp;</th>\n";
2868                 }
2869                 print "</tr></thead>\n<tbody>\n";
2870         }
2872         my $alternate = 1;
2873         my $patchno = 0;
2874         foreach my $line (@{$difftree}) {
2875                 my $diff = parsed_difftree_line($line);
2877                 if ($alternate) {
2878                         print "<tr class=\"dark\">\n";
2879                 } else {
2880                         print "<tr class=\"light\">\n";
2881                 }
2882                 $alternate ^= 1;
2884                 if (exists $diff->{'nparents'}) { # combined diff
2886                         fill_from_file_info($diff, @parents)
2887                                 unless exists $diff->{'from_file'};
2889                         if (!is_deleted($diff)) {
2890                                 # file exists in the result (child) commit
2891                                 print "<td>" .
2892                                       $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2893                                                              file_name=>$diff->{'to_file'},
2894                                                              hash_base=>$hash),
2895                                               -class => "list"}, esc_path($diff->{'to_file'})) .
2896                                       "</td>\n";
2897                         } else {
2898                                 print "<td>" .
2899                                       esc_path($diff->{'to_file'}) .
2900                                       "</td>\n";
2901                         }
2903                         if ($action eq 'commitdiff') {
2904                                 # link to patch
2905                                 $patchno++;
2906                                 print "<td class=\"link\">" .
2907                                       $cgi->a({-href => "#patch$patchno"}, "patch") .
2908                                       " | " .
2909                                       "</td>\n";
2910                         }
2912                         my $has_history = 0;
2913                         my $not_deleted = 0;
2914                         for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
2915                                 my $hash_parent = $parents[$i];
2916                                 my $from_hash = $diff->{'from_id'}[$i];
2917                                 my $from_path = $diff->{'from_file'}[$i];
2918                                 my $status = $diff->{'status'}[$i];
2920                                 $has_history ||= ($status ne 'A');
2921                                 $not_deleted ||= ($status ne 'D');
2923                                 if ($status eq 'A') {
2924                                         print "<td  class=\"link\" align=\"right\"> | </td>\n";
2925                                 } elsif ($status eq 'D') {
2926                                         print "<td class=\"link\">" .
2927                                               $cgi->a({-href => href(action=>"blob",
2928                                                                      hash_base=>$hash,
2929                                                                      hash=>$from_hash,
2930                                                                      file_name=>$from_path)},
2931                                                       "blob" . ($i+1)) .
2932                                               " | </td>\n";
2933                                 } else {
2934                                         if ($diff->{'to_id'} eq $from_hash) {
2935                                                 print "<td class=\"link nochange\">";
2936                                         } else {
2937                                                 print "<td class=\"link\">";
2938                                         }
2939                                         print $cgi->a({-href => href(action=>"blobdiff",
2940                                                                      hash=>$diff->{'to_id'},
2941                                                                      hash_parent=>$from_hash,
2942                                                                      hash_base=>$hash,
2943                                                                      hash_parent_base=>$hash_parent,
2944                                                                      file_name=>$diff->{'to_file'},
2945                                                                      file_parent=>$from_path)},
2946                                                       "diff" . ($i+1)) .
2947                                               " | </td>\n";
2948                                 }
2949                         }
2951                         print "<td class=\"link\">";
2952                         if ($not_deleted) {
2953                                 print $cgi->a({-href => href(action=>"blob",
2954                                                              hash=>$diff->{'to_id'},
2955                                                              file_name=>$diff->{'to_file'},
2956                                                              hash_base=>$hash)},
2957                                               "blob");
2958                                 print " | " if ($has_history);
2959                         }
2960                         if ($has_history) {
2961                                 print $cgi->a({-href => href(action=>"history",
2962                                                              file_name=>$diff->{'to_file'},
2963                                                              hash_base=>$hash)},
2964                                               "history");
2965                         }
2966                         print "</td>\n";
2968                         print "</tr>\n";
2969                         next; # instead of 'else' clause, to avoid extra indent
2970                 }
2971                 # else ordinary diff
2973                 my ($to_mode_oct, $to_mode_str, $to_file_type);
2974                 my ($from_mode_oct, $from_mode_str, $from_file_type);
2975                 if ($diff->{'to_mode'} ne ('0' x 6)) {
2976                         $to_mode_oct = oct $diff->{'to_mode'};
2977                         if (S_ISREG($to_mode_oct)) { # only for regular file
2978                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2979                         }
2980                         $to_file_type = file_type($diff->{'to_mode'});
2981                 }
2982                 if ($diff->{'from_mode'} ne ('0' x 6)) {
2983                         $from_mode_oct = oct $diff->{'from_mode'};
2984                         if (S_ISREG($to_mode_oct)) { # only for regular file
2985                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2986                         }
2987                         $from_file_type = file_type($diff->{'from_mode'});
2988                 }
2990                 if ($diff->{'status'} eq "A") { # created
2991                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2992                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2993                         $mode_chng   .= "]</span>";
2994                         print "<td>";
2995                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
2996                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
2997                                       -class => "list"}, esc_path($diff->{'file'}));
2998                         print "</td>\n";
2999                         print "<td>$mode_chng</td>\n";
3000                         print "<td class=\"link\">";
3001                         if ($action eq 'commitdiff') {
3002                                 # link to patch
3003                                 $patchno++;
3004                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
3005                                 print " | ";
3006                         }
3007                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3008                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
3009                                       "blob");
3010                         print "</td>\n";
3012                 } elsif ($diff->{'status'} eq "D") { # deleted
3013                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3014                         print "<td>";
3015                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3016                                                      hash_base=>$parent, file_name=>$diff->{'file'}),
3017                                        -class => "list"}, esc_path($diff->{'file'}));
3018                         print "</td>\n";
3019                         print "<td>$mode_chng</td>\n";
3020                         print "<td class=\"link\">";
3021                         if ($action eq 'commitdiff') {
3022                                 # link to patch
3023                                 $patchno++;
3024                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
3025                                 print " | ";
3026                         }
3027                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3028                                                      hash_base=>$parent, file_name=>$diff->{'file'})},
3029                                       "blob") . " | ";
3030                         if ($have_blame) {
3031                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3032                                                              file_name=>$diff->{'file'})},
3033                                               "blame") . " | ";
3034                         }
3035                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3036                                                      file_name=>$diff->{'file'})},
3037                                       "history");
3038                         print "</td>\n";
3040                 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3041                         my $mode_chnge = "";
3042                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3043                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3044                                 if ($from_file_type ne $to_file_type) {
3045                                         $mode_chnge .= " from $from_file_type to $to_file_type";
3046                                 }
3047                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3048                                         if ($from_mode_str && $to_mode_str) {
3049                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3050                                         } elsif ($to_mode_str) {
3051                                                 $mode_chnge .= " mode: $to_mode_str";
3052                                         }
3053                                 }
3054                                 $mode_chnge .= "]</span>\n";
3055                         }
3056                         print "<td>";
3057                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3058                                                      hash_base=>$hash, file_name=>$diff->{'file'}),
3059                                       -class => "list"}, esc_path($diff->{'file'}));
3060                         print "</td>\n";
3061                         print "<td>$mode_chnge</td>\n";
3062                         print "<td class=\"link\">";
3063                         if ($action eq 'commitdiff') {
3064                                 # link to patch
3065                                 $patchno++;
3066                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3067                                       " | ";
3068                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3069                                 # "commit" view and modified file (not onlu mode changed)
3070                                 print $cgi->a({-href => href(action=>"blobdiff",
3071                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3072                                                              hash_base=>$hash, hash_parent_base=>$parent,
3073                                                              file_name=>$diff->{'file'})},
3074                                               "diff") .
3075                                       " | ";
3076                         }
3077                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3078                                                      hash_base=>$hash, file_name=>$diff->{'file'})},
3079                                        "blob") . " | ";
3080                         if ($have_blame) {
3081                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3082                                                              file_name=>$diff->{'file'})},
3083                                               "blame") . " | ";
3084                         }
3085                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3086                                                      file_name=>$diff->{'file'})},
3087                                       "history");
3088                         print "</td>\n";
3090                 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3091                         my %status_name = ('R' => 'moved', 'C' => 'copied');
3092                         my $nstatus = $status_name{$diff->{'status'}};
3093                         my $mode_chng = "";
3094                         if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3095                                 # mode also for directories, so we cannot use $to_mode_str
3096                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3097                         }
3098                         print "<td>" .
3099                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3100                                                      hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3101                                       -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3102                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3103                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3104                                                      hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3105                                       -class => "list"}, esc_path($diff->{'from_file'})) .
3106                               " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3107                               "<td class=\"link\">";
3108                         if ($action eq 'commitdiff') {
3109                                 # link to patch
3110                                 $patchno++;
3111                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3112                                       " | ";
3113                         } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3114                                 # "commit" view and modified file (not only pure rename or copy)
3115                                 print $cgi->a({-href => href(action=>"blobdiff",
3116                                                              hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3117                                                              hash_base=>$hash, hash_parent_base=>$parent,
3118                                                              file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3119                                               "diff") .
3120                                       " | ";
3121                         }
3122                         print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3123                                                      hash_base=>$parent, file_name=>$diff->{'to_file'})},
3124                                       "blob") . " | ";
3125                         if ($have_blame) {
3126                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3127                                                              file_name=>$diff->{'to_file'})},
3128                                               "blame") . " | ";
3129                         }
3130                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3131                                                     file_name=>$diff->{'to_file'})},
3132                                       "history");
3133                         print "</td>\n";
3135                 } # we should not encounter Unmerged (U) or Unknown (X) status
3136                 print "</tr>\n";
3137         }
3138         print "</tbody>" if $has_header;
3139         print "</table>\n";
3142 sub git_patchset_body {
3143         my ($fd, $difftree, $hash, @hash_parents) = @_;
3144         my ($hash_parent) = $hash_parents[0];
3146         my $is_combined = (@hash_parents > 1);
3147         my $patch_idx = 0;
3148         my $patch_number = 0;
3149         my $patch_line;
3150         my $diffinfo;
3151         my $to_name;
3152         my (%from, %to);
3154         print "<div class=\"patchset\">\n";
3156         # skip to first patch
3157         while ($patch_line = <$fd>) {
3158                 chomp $patch_line;
3160                 last if ($patch_line =~ m/^diff /);
3161         }
3163  PATCH:
3164         while ($patch_line) {
3166                 # parse "git diff" header line
3167                 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
3168                         # $1 is from_name, which we do not use
3169                         $to_name = unquote($2);
3170                         $to_name =~ s!^b/!!;
3171                 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
3172                         # $1 is 'cc' or 'combined', which we do not use
3173                         $to_name = unquote($2);
3174                 } else {
3175                         $to_name = undef;
3176                 }
3178                 # check if current patch belong to current raw line
3179                 # and parse raw git-diff line if needed
3180                 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
3181                         # this is continuation of a split patch
3182                         print "<div class=\"patch cont\">\n";
3183                 } else {
3184                         # advance raw git-diff output if needed
3185                         $patch_idx++ if defined $diffinfo;
3187                         # read and prepare patch information
3188                         $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3190                         # compact combined diff output can have some patches skipped
3191                         # find which patch (using pathname of result) we are at now;
3192                         if ($is_combined) {
3193                                 while ($to_name ne $diffinfo->{'to_file'}) {
3194                                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3195                                               format_diff_cc_simplified($diffinfo, @hash_parents) .
3196                                               "</div>\n";  # class="patch"
3198                                         $patch_idx++;
3199                                         $patch_number++;
3201                                         last if $patch_idx > $#$difftree;
3202                                         $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3203                                 }
3204                         }
3206                         # modifies %from, %to hashes
3207                         parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3209                         # this is first patch for raw difftree line with $patch_idx index
3210                         # we index @$difftree array from 0, but number patches from 1
3211                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3212                 }
3214                 # git diff header
3215                 #assert($patch_line =~ m/^diff /) if DEBUG;
3216                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3217                 $patch_number++;
3218                 # print "git diff" header
3219                 print format_git_diff_header_line($patch_line, $diffinfo,
3220                                                   \%from, \%to);
3222                 # print extended diff header
3223                 print "<div class=\"diff extended_header\">\n";
3224         EXTENDED_HEADER:
3225                 while ($patch_line = <$fd>) {
3226                         chomp $patch_line;
3228                         last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3230                         print format_extended_diff_header_line($patch_line, $diffinfo,
3231                                                                \%from, \%to);
3232                 }
3233                 print "</div>\n"; # class="diff extended_header"
3235                 # from-file/to-file diff header
3236                 if (! $patch_line) {
3237                         print "</div>\n"; # class="patch"
3238                         last PATCH;
3239                 }
3240                 next PATCH if ($patch_line =~ m/^diff /);
3241                 #assert($patch_line =~ m/^---/) if DEBUG;
3243                 my $last_patch_line = $patch_line;
3244                 $patch_line = <$fd>;
3245                 chomp $patch_line;
3246                 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3248                 print format_diff_from_to_header($last_patch_line, $patch_line,
3249                                                  $diffinfo, \%from, \%to,
3250                                                  @hash_parents);
3252                 # the patch itself
3253         LINE:
3254                 while ($patch_line = <$fd>) {
3255                         chomp $patch_line;
3257                         next PATCH if ($patch_line =~ m/^diff /);
3259                         print format_diff_line($patch_line, \%from, \%to);
3260                 }
3262         } continue {
3263                 print "</div>\n"; # class="patch"
3264         }
3266         # for compact combined (--cc) format, with chunk and patch simpliciaction
3267         # patchset might be empty, but there might be unprocessed raw lines
3268         for (++$patch_idx if $patch_number > 0;
3269              $patch_idx < @$difftree;
3270              ++$patch_idx) {
3271                 # read and prepare patch information
3272                 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3274                 # generate anchor for "patch" links in difftree / whatchanged part
3275                 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3276                       format_diff_cc_simplified($diffinfo, @hash_parents) .
3277                       "</div>\n";  # class="patch"
3279                 $patch_number++;
3280         }
3282         if ($patch_number == 0) {
3283                 if (@hash_parents > 1) {
3284                         print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3285                 } else {
3286                         print "<div class=\"diff nodifferences\">No differences found</div>\n";
3287                 }
3288         }
3290         print "</div>\n"; # class="patchset"
3293 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3295 sub git_project_list_body {
3296         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3298         my ($check_forks) = gitweb_check_feature('forks');
3300         my @projects;
3301         foreach my $pr (@$projlist) {
3302                 my (@aa) = git_get_last_activity($pr->{'path'});
3303                 unless (@aa) {
3304                         next;
3305                 }
3306                 ($pr->{'age'}, $pr->{'age_string'}) = @aa;
3307                 if (!defined $pr->{'descr'}) {
3308                         my $descr = git_get_project_description($pr->{'path'}) || "";
3309                         $pr->{'descr_long'} = to_utf8($descr);
3310                         $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3311                 }
3312                 if (!defined $pr->{'owner'}) {
3313                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3314                 }
3315                 if ($check_forks) {
3316                         my $pname = $pr->{'path'};
3317                         if (($pname =~ s/\.git$//) &&
3318                             ($pname !~ /\/$/) &&
3319                             (-d "$projectroot/$pname")) {
3320                                 $pr->{'forks'} = "-d $projectroot/$pname";
3321                         }
3322                         else {
3323                                 $pr->{'forks'} = 0;
3324                         }
3325                 }
3326                 push @projects, $pr;
3327         }
3329         $order ||= $default_projects_order;
3330         $from = 0 unless defined $from;
3331         $to = $#projects if (!defined $to || $#projects < $to);
3333         print "<table class=\"project_list\">\n";
3334         unless ($no_header) {
3335                 print "<tr>\n";
3336                 if ($check_forks) {
3337                         print "<th></th>\n";
3338                 }
3339                 if ($order eq "project") {
3340                         @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
3341                         print "<th>Project</th>\n";
3342                 } else {
3343                         print "<th>" .
3344                               $cgi->a({-href => href(project=>undef, order=>'project'),
3345                                        -class => "header"}, "Project") .
3346                               "</th>\n";
3347                 }
3348                 if ($order eq "descr") {
3349                         @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
3350                         print "<th>Description</th>\n";
3351                 } else {
3352                         print "<th>" .
3353                               $cgi->a({-href => href(project=>undef, order=>'descr'),
3354                                        -class => "header"}, "Description") .
3355                               "</th>\n";
3356                 }
3357                 if ($order eq "owner") {
3358                         @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
3359                         print "<th>Owner</th>\n";
3360                 } else {
3361                         print "<th>" .
3362                               $cgi->a({-href => href(project=>undef, order=>'owner'),
3363                                        -class => "header"}, "Owner") .
3364                               "</th>\n";
3365                 }
3366                 if ($order eq "age") {
3367                         @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
3368                         print "<th>Last Change</th>\n";
3369                 } else {
3370                         print "<th>" .
3371                               $cgi->a({-href => href(project=>undef, order=>'age'),
3372                                        -class => "header"}, "Last Change") .
3373                               "</th>\n";
3374                 }
3375                 print "<th></th>\n" .
3376                       "</tr>\n";
3377         }
3378         my $alternate = 1;
3379         for (my $i = $from; $i <= $to; $i++) {
3380                 my $pr = $projects[$i];
3381                 if ($alternate) {
3382                         print "<tr class=\"dark\">\n";
3383                 } else {
3384                         print "<tr class=\"light\">\n";
3385                 }
3386                 $alternate ^= 1;
3387                 if ($check_forks) {
3388                         print "<td>";
3389                         if ($pr->{'forks'}) {
3390                                 print "<!-- $pr->{'forks'} -->\n";
3391                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3392                         }
3393                         print "</td>\n";
3394                 }
3395                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3396                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3397                       "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3398                                         -class => "list", -title => $pr->{'descr_long'}},
3399                                         esc_html($pr->{'descr'})) . "</td>\n" .
3400                       "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
3401                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3402                       (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3403                       "<td class=\"link\">" .
3404                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
3405                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3406                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3407                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3408                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3409                       "</td>\n" .
3410                       "</tr>\n";
3411         }
3412         if (defined $extra) {
3413                 print "<tr>\n";
3414                 if ($check_forks) {
3415                         print "<td></td>\n";
3416                 }
3417                 print "<td colspan=\"5\">$extra</td>\n" .
3418                       "</tr>\n";
3419         }
3420         print "</table>\n";
3423 sub git_shortlog_body {
3424         # uses global variable $project
3425         my ($commitlist, $from, $to, $refs, $extra) = @_;
3427         $from = 0 unless defined $from;
3428         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3430         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
3431         my $alternate = 1;
3432         for (my $i = $from; $i <= $to; $i++) {
3433                 my %co = %{$commitlist->[$i]};
3434                 my $commit = $co{'id'};
3435                 my $ref = format_ref_marker($refs, $commit);
3436                 if ($alternate) {
3437                         print "<tr class=\"dark\">\n";
3438                 } else {
3439                         print "<tr class=\"light\">\n";
3440                 }
3441                 $alternate ^= 1;
3442                 my $author = chop_and_escape_str($co{'author_name'}, 10);
3443                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3444                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3445                       "<td><i>" . $author . "</i></td>\n" .
3446                       "<td>";
3447                 print format_subject_html($co{'title'}, $co{'title_short'},
3448                                           href(action=>"commit", hash=>$commit), $ref);
3449                 print "</td>\n" .
3450                       "<td class=\"link\">" .
3451                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3452                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3453                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3454                 my $snapshot_links = format_snapshot_links($commit);
3455                 if (defined $snapshot_links) {
3456                         print " | " . $snapshot_links;
3457                 }
3458                 print "</td>\n" .
3459                       "</tr>\n";
3460         }
3461         if (defined $extra) {
3462                 print "<tr>\n" .
3463                       "<td colspan=\"4\">$extra</td>\n" .
3464                       "</tr>\n";
3465         }
3466         print "</table>\n";
3469 sub git_history_body {
3470         # Warning: assumes constant type (blob or tree) during history
3471         my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3473         $from = 0 unless defined $from;
3474         $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3476         print "<table class=\"history\" cellspacing=\"0\">\n";
3477         my $alternate = 1;
3478         for (my $i = $from; $i <= $to; $i++) {
3479                 my %co = %{$commitlist->[$i]};
3480                 if (!%co) {
3481                         next;
3482                 }
3483                 my $commit = $co{'id'};
3485                 my $ref = format_ref_marker($refs, $commit);
3487                 if ($alternate) {
3488                         print "<tr class=\"dark\">\n";
3489                 } else {
3490                         print "<tr class=\"light\">\n";
3491                 }
3492                 $alternate ^= 1;
3493         # shortlog uses      chop_str($co{'author_name'}, 10)
3494                 my $author = chop_and_escape_str($co{'author_name'}, 15, 3);
3495                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3496                       "<td><i>" . $author . "</i></td>\n" .
3497                       "<td>";
3498                 # originally git_history used chop_str($co{'title'}, 50)
3499                 print format_subject_html($co{'title'}, $co{'title_short'},
3500                                           href(action=>"commit", hash=>$commit), $ref);
3501                 print "</td>\n" .
3502                       "<td class=\"link\">" .
3503                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3504                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3506                 if ($ftype eq 'blob') {
3507                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3508                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
3509                         if (defined $blob_current && defined $blob_parent &&
3510                                         $blob_current ne $blob_parent) {
3511                                 print " | " .
3512                                         $cgi->a({-href => href(action=>"blobdiff",
3513                                                                hash=>$blob_current, hash_parent=>$blob_parent,
3514                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
3515                                                                file_name=>$file_name)},
3516                                                 "diff to current");
3517                         }
3518                 }
3519                 print "</td>\n" .
3520                       "</tr>\n";
3521         }
3522         if (defined $extra) {
3523                 print "<tr>\n" .
3524                       "<td colspan=\"4\">$extra</td>\n" .
3525                       "</tr>\n";
3526         }
3527         print "</table>\n";
3530 sub git_tags_body {
3531         # uses global variable $project
3532         my ($taglist, $from, $to, $extra) = @_;
3533         $from = 0 unless defined $from;
3534         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3536         print "<table class=\"tags\" cellspacing=\"0\">\n";
3537         my $alternate = 1;
3538         for (my $i = $from; $i <= $to; $i++) {
3539                 my $entry = $taglist->[$i];
3540                 my %tag = %$entry;
3541                 my $comment = $tag{'subject'};
3542                 my $comment_short;
3543                 if (defined $comment) {
3544                         $comment_short = chop_str($comment, 30, 5);
3545                 }
3546                 if ($alternate) {
3547                         print "<tr class=\"dark\">\n";
3548                 } else {
3549                         print "<tr class=\"light\">\n";
3550                 }
3551                 $alternate ^= 1;
3552                 if (defined $tag{'age'}) {
3553                         print "<td><i>$tag{'age'}</i></td>\n";
3554                 } else {
3555                         print "<td></td>\n";
3556                 }
3557                 print "<td>" .
3558                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3559                                -class => "list name"}, esc_html($tag{'name'})) .
3560                       "</td>\n" .
3561                       "<td>";
3562                 if (defined $comment) {
3563                         print format_subject_html($comment, $comment_short,
3564                                                   href(action=>"tag", hash=>$tag{'id'}));
3565                 }
3566                 print "</td>\n" .
3567                       "<td class=\"selflink\">";
3568                 if ($tag{'type'} eq "tag") {
3569                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3570                 } else {
3571                         print "&nbsp;";
3572                 }
3573                 print "</td>\n" .
3574                       "<td class=\"link\">" . " | " .
3575                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3576                 if ($tag{'reftype'} eq "commit") {
3577                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
3578                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
3579                 } elsif ($tag{'reftype'} eq "blob") {
3580                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3581                 }
3582                 print "</td>\n" .
3583                       "</tr>";
3584         }
3585         if (defined $extra) {
3586                 print "<tr>\n" .
3587                       "<td colspan=\"5\">$extra</td>\n" .
3588                       "</tr>\n";
3589         }
3590         print "</table>\n";
3593 sub git_heads_body {
3594         # uses global variable $project
3595         my ($headlist, $head, $from, $to, $extra) = @_;
3596         $from = 0 unless defined $from;
3597         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3599         print "<table class=\"heads\" cellspacing=\"0\">\n";
3600         my $alternate = 1;
3601         for (my $i = $from; $i <= $to; $i++) {
3602                 my $entry = $headlist->[$i];
3603                 my %ref = %$entry;
3604                 my $curr = $ref{'id'} eq $head;
3605                 if ($alternate) {
3606                         print "<tr class=\"dark\">\n";
3607                 } else {
3608                         print "<tr class=\"light\">\n";
3609                 }
3610                 $alternate ^= 1;
3611                 print "<td><i>$ref{'age'}</i></td>\n" .
3612                       ($curr ? "<td class=\"current_head\">" : "<td>") .
3613                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
3614                                -class => "list name"},esc_html($ref{'name'})) .
3615                       "</td>\n" .
3616                       "<td class=\"link\">" .
3617                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
3618                       $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
3619                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
3620                       "</td>\n" .
3621                       "</tr>";
3622         }
3623         if (defined $extra) {
3624                 print "<tr>\n" .
3625                       "<td colspan=\"3\">$extra</td>\n" .
3626                       "</tr>\n";
3627         }
3628         print "</table>\n";
3631 sub git_search_grep_body {
3632         my ($commitlist, $from, $to, $extra) = @_;
3633         $from = 0 unless defined $from;
3634         $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3636         print "<table class=\"grep\" cellspacing=\"0\">\n";
3637         my $alternate = 1;
3638         for (my $i = $from; $i <= $to; $i++) {
3639                 my %co = %{$commitlist->[$i]};
3640                 if (!%co) {
3641                         next;
3642                 }
3643                 my $commit = $co{'id'};
3644                 if ($alternate) {
3645                         print "<tr class=\"dark\">\n";
3646                 } else {
3647                         print "<tr class=\"light\">\n";
3648                 }
3649                 $alternate ^= 1;
3650                 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
3651                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3652                       "<td><i>" . $author . "</i></td>\n" .
3653                       "<td>" .
3654                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3655                                chop_and_escape_str($co{'title'}, 50) . "<br/>");
3656                 my $comment = $co{'comment'};
3657                 foreach my $line (@$comment) {
3658                         if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
3659                                 my $lead = esc_html($1) || "";
3660                                 $lead = chop_str($lead, 30, 10);
3661                                 my $match = esc_html($2) || "";
3662                                 my $trail = esc_html($3) || "";
3663                                 $trail = chop_str($trail, 30, 10);
3664                                 my $text = "$lead<span class=\"match\">$match</span>$trail";
3665                                 print chop_str($text, 80, 5) . "<br/>\n";
3666                         }
3667                 }
3668                 print "</td>\n" .
3669                       "<td class=\"link\">" .
3670                       $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3671                       " | " .
3672                       $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3673                 print "</td>\n" .
3674                       "</tr>\n";
3675         }
3676         if (defined $extra) {
3677                 print "<tr>\n" .
3678                       "<td colspan=\"3\">$extra</td>\n" .
3679                       "</tr>\n";
3680         }
3681         print "</table>\n";
3684 ## ======================================================================
3685 ## ======================================================================
3686 ## actions
3688 sub git_project_list {
3689         my $order = $cgi->param('o');
3690         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3691                 die_error(undef, "Unknown order parameter");
3692         }
3694         my @list = git_get_projects_list();
3695         if (!@list) {
3696                 die_error(undef, "No projects found");
3697         }
3699         git_header_html();
3700         if (-f $home_text) {
3701                 print "<div class=\"index_include\">\n";
3702                 open (my $fd, $home_text);
3703                 print <$fd>;
3704                 close $fd;
3705                 print "</div>\n";
3706         }
3707         git_project_list_body(\@list, $order);
3708         git_footer_html();
3711 sub git_forks {
3712         my $order = $cgi->param('o');
3713         if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3714                 die_error(undef, "Unknown order parameter");
3715         }
3717         my @list = git_get_projects_list($project);
3718         if (!@list) {
3719                 die_error(undef, "No forks found");
3720         }
3722         git_header_html();
3723         git_print_page_nav('','');
3724         git_print_header_div('summary', "$project forks");
3725         git_project_list_body(\@list, $order);
3726         git_footer_html();
3729 sub git_project_index {
3730         my @projects = git_get_projects_list($project);
3732         print $cgi->header(
3733                 -type => 'text/plain',
3734                 -charset => 'utf-8',
3735                 -content_disposition => 'inline; filename="index.aux"');
3737         foreach my $pr (@projects) {
3738                 if (!exists $pr->{'owner'}) {
3739                         $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
3740                 }
3742                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
3743                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
3744                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3745                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
3746                 $path  =~ s/ /\+/g;
3747                 $owner =~ s/ /\+/g;
3749                 print "$path $owner\n";
3750         }
3753 sub git_summary {
3754         my $descr = git_get_project_description($project) || "none";
3755         my %co = parse_commit("HEAD");
3756         my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
3757         my $head = $co{'id'};
3759         my $owner = git_get_project_owner($project);
3761         my $refs = git_get_references();
3762         # These get_*_list functions return one more to allow us to see if
3763         # there are more ...
3764         my @taglist  = git_get_tags_list(16);
3765         my @headlist = git_get_heads_list(16);
3766         my @forklist;
3767         my ($check_forks) = gitweb_check_feature('forks');
3769         if ($check_forks) {
3770                 @forklist = git_get_projects_list($project);
3771         }
3773         git_header_html();
3774         git_print_page_nav('summary','', $head);
3776         print "<div class=\"title\">&nbsp;</div>\n";
3777         print "<table cellspacing=\"0\">\n" .
3778               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
3779               "<tr><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
3780         if (defined $cd{'rfc2822'}) {
3781                 print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
3782         }
3784         # use per project git URL list in $projectroot/$project/cloneurl
3785         # or make project git URL from git base URL and project name
3786         my $url_tag = "URL";
3787         my @url_list = git_get_project_url_list($project);
3788         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
3789         foreach my $git_url (@url_list) {
3790                 next unless $git_url;
3791                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
3792                 $url_tag = "";
3793         }
3794         print "</table>\n";
3796         if (-s "$projectroot/$project/README.html") {
3797                 if (open my $fd, "$projectroot/$project/README.html") {
3798                         print "<div class=\"title\">readme</div>\n";
3799                         print $_ while (<$fd>);
3800                         close $fd;
3801                 }
3802         }
3804         # we need to request one more than 16 (0..15) to check if
3805         # those 16 are all
3806         my @commitlist = $head ? parse_commits($head, 17) : ();
3807         if (@commitlist) {
3808                 git_print_header_div('shortlog');
3809                 git_shortlog_body(\@commitlist, 0, 15, $refs,
3810                                   $#commitlist <=  15 ? undef :
3811                                   $cgi->a({-href => href(action=>"shortlog")}, "..."));
3812         }
3814         if (@taglist) {
3815                 git_print_header_div('tags');
3816                 git_tags_body(\@taglist, 0, 15,
3817                               $#taglist <=  15 ? undef :
3818                               $cgi->a({-href => href(action=>"tags")}, "..."));
3819         }
3821         if (@headlist) {
3822                 git_print_header_div('heads');
3823                 git_heads_body(\@headlist, $head, 0, 15,
3824                                $#headlist <= 15 ? undef :
3825                                $cgi->a({-href => href(action=>"heads")}, "..."));
3826         }
3828         if (@forklist) {
3829                 git_print_header_div('forks');
3830                 git_project_list_body(\@forklist, undef, 0, 15,
3831                                       $#forklist <= 15 ? undef :
3832                                       $cgi->a({-href => href(action=>"forks")}, "..."),
3833                                       'noheader');
3834         }
3836         git_footer_html();
3839 sub git_tag {
3840         my $head = git_get_head_hash($project);
3841         git_header_html();
3842         git_print_page_nav('','', $head,undef,$head);
3843         my %tag = parse_tag($hash);
3845         if (! %tag) {
3846                 die_error(undef, "Unknown tag object");
3847         }
3849         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3850         print "<div class=\"title_text\">\n" .
3851               "<table cellspacing=\"0\">\n" .
3852               "<tr>\n" .
3853               "<td>object</td>\n" .
3854               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3855                                $tag{'object'}) . "</td>\n" .
3856               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3857                                               $tag{'type'}) . "</td>\n" .
3858               "</tr>\n";
3859         if (defined($tag{'author'})) {
3860                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3861                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3862                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
3863                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3864                         "</td></tr>\n";
3865         }
3866         print "</table>\n\n" .
3867               "</div>\n";
3868         print "<div class=\"page_body\">";
3869         my $comment = $tag{'comment'};
3870         foreach my $line (@$comment) {
3871                 chomp $line;
3872                 print esc_html($line, -nbsp=>1) . "<br/>\n";
3873         }
3874         print "</div>\n";
3875         git_footer_html();
3878 sub git_blame2 {
3879         my $fd;
3880         my $ftype;
3882         my ($have_blame) = gitweb_check_feature('blame');
3883         if (!$have_blame) {
3884                 die_error('403 Permission denied', "Permission denied");
3885         }
3886         die_error('404 Not Found', "File name not defined") if (!$file_name);
3887         $hash_base ||= git_get_head_hash($project);
3888         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3889         my %co = parse_commit($hash_base)
3890                 or die_error(undef, "Reading commit failed");
3891         if (!defined $hash) {
3892                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3893                         or die_error(undef, "Error looking up file");
3894         }
3895         $ftype = git_get_type($hash);
3896         if ($ftype !~ "blob") {
3897                 die_error('400 Bad Request', "Object is not a blob");
3898         }
3899         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3900               $file_name, $hash_base)
3901                 or die_error(undef, "Open git-blame failed");
3902         git_header_html();
3903         my $formats_nav =
3904                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3905                         "blob") .
3906                 " | " .
3907                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3908                         "history") .
3909                 " | " .
3910                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3911                         "HEAD");
3912         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3913         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3914         git_print_page_path($file_name, $ftype, $hash_base);
3915         my @rev_color = (qw(light2 dark2));
3916         my $num_colors = scalar(@rev_color);
3917         my $current_color = 0;
3918         my $last_rev;
3919         print <<HTML;
3920 <div class="page_body">
3921 <table class="blame">
3922 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3923 HTML
3924         my %metainfo = ();
3925         while (1) {
3926                 $_ = <$fd>;
3927                 last unless defined $_;
3928                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
3929                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3930                 if (!exists $metainfo{$full_rev}) {
3931                         $metainfo{$full_rev} = {};
3932                 }
3933                 my $meta = $metainfo{$full_rev};
3934                 while (<$fd>) {
3935                         last if (s/^\t//);
3936                         if (/^(\S+) (.*)$/) {
3937                                 $meta->{$1} = $2;
3938                         }
3939                 }
3940                 my $data = $_;
3941                 chomp $data;
3942                 my $rev = substr($full_rev, 0, 8);
3943                 my $author = $meta->{'author'};
3944                 my %date = parse_date($meta->{'author-time'},
3945                                       $meta->{'author-tz'});
3946                 my $date = $date{'iso-tz'};
3947                 if ($group_size) {
3948                         $current_color = ++$current_color % $num_colors;
3949                 }
3950                 print "<tr class=\"$rev_color[$current_color]\">\n";
3951                 if ($group_size) {
3952                         print "<td class=\"sha1\"";
3953                         print " title=\"". esc_html($author) . ", $date\"";
3954                         print " rowspan=\"$group_size\"" if ($group_size > 1);
3955                         print ">";
3956                         print $cgi->a({-href => href(action=>"commit",
3957                                                      hash=>$full_rev,
3958                                                      file_name=>$file_name)},
3959                                       esc_html($rev));
3960                         print "</td>\n";
3961                 }
3962                 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
3963                         or die_error(undef, "Open git-rev-parse failed");
3964                 my $parent_commit = <$dd>;
3965                 close $dd;
3966                 chomp($parent_commit);
3967                 my $blamed = href(action => 'blame',
3968                                   file_name => $meta->{'filename'},
3969                                   hash_base => $parent_commit);
3970                 print "<td class=\"linenr\">";
3971                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
3972                                 -id => "l$lineno",
3973                                 -class => "linenr" },
3974                               esc_html($lineno));
3975                 print "</td>";
3976                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3977                 print "</tr>\n";
3978         }
3979         print "</table>\n";
3980         print "</div>";
3981         close $fd
3982                 or print "Reading blob failed\n";
3983         git_footer_html();
3986 sub git_blame {
3987         my $fd;
3989         my ($have_blame) = gitweb_check_feature('blame');
3990         if (!$have_blame) {
3991                 die_error('403 Permission denied', "Permission denied");
3992         }
3993         die_error('404 Not Found', "File name not defined") if (!$file_name);
3994         $hash_base ||= git_get_head_hash($project);
3995         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3996         my %co = parse_commit($hash_base)
3997                 or die_error(undef, "Reading commit failed");
3998         if (!defined $hash) {
3999                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4000                         or die_error(undef, "Error lookup file");
4001         }
4002         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
4003                 or die_error(undef, "Open git-annotate failed");
4004         git_header_html();
4005         my $formats_nav =
4006                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
4007                         "blob") .
4008                 " | " .
4009                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
4010                         "history") .
4011                 " | " .
4012                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4013                         "HEAD");
4014         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4015         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4016         git_print_page_path($file_name, 'blob', $hash_base);
4017         print "<div class=\"page_body\">\n";
4018         print <<HTML;
4019 <table class="blame">
4020   <tr>
4021     <th>Commit</th>
4022     <th>Age</th>
4023     <th>Author</th>
4024     <th>Line</th>
4025     <th>Data</th>
4026   </tr>
4027 HTML
4028         my @line_class = (qw(light dark));
4029         my $line_class_len = scalar (@line_class);
4030         my $line_class_num = $#line_class;
4031         while (my $line = <$fd>) {
4032                 my $long_rev;
4033                 my $short_rev;
4034                 my $author;
4035                 my $time;
4036                 my $lineno;
4037                 my $data;
4038                 my $age;
4039                 my $age_str;
4040                 my $age_class;
4042                 chomp $line;
4043                 $line_class_num = ($line_class_num + 1) % $line_class_len;
4045                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
4046                         $long_rev = $1;
4047                         $author   = $2;
4048                         $time     = $3;
4049                         $lineno   = $4;
4050                         $data     = $5;
4051                 } else {
4052                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
4053                         next;
4054                 }
4055                 $short_rev  = substr ($long_rev, 0, 8);
4056                 $age        = time () - $time;
4057                 $age_str    = age_string ($age);
4058                 $age_str    =~ s/ /&nbsp;/g;
4059                 $age_class  = age_class($age);
4060                 $author     = esc_html ($author);
4061                 $author     =~ s/ /&nbsp;/g;
4063                 $data = untabify($data);
4064                 $data = esc_html ($data);
4066                 print <<HTML;
4067   <tr class="$line_class[$line_class_num]">
4068     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
4069     <td class="$age_class">$age_str</td>
4070     <td>$author</td>
4071     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
4072     <td class="pre">$data</td>
4073   </tr>
4074 HTML
4075         } # while (my $line = <$fd>)
4076         print "</table>\n\n";
4077         close $fd
4078                 or print "Reading blob failed.\n";
4079         print "</div>";
4080         git_footer_html();
4083 sub git_tags {
4084         my $head = git_get_head_hash($project);
4085         git_header_html();
4086         git_print_page_nav('','', $head,undef,$head);
4087         git_print_header_div('summary', $project);
4089         my @tagslist = git_get_tags_list();
4090         if (@tagslist) {
4091                 git_tags_body(\@tagslist);
4092         }
4093         git_footer_html();
4096 sub git_heads {
4097         my $head = git_get_head_hash($project);
4098         git_header_html();
4099         git_print_page_nav('','', $head,undef,$head);
4100         git_print_header_div('summary', $project);
4102         my @headslist = git_get_heads_list();
4103         if (@headslist) {
4104                 git_heads_body(\@headslist, $head);
4105         }
4106         git_footer_html();
4109 sub git_blob_plain {
4110         my $expires;
4112         if (!defined $hash) {
4113                 if (defined $file_name) {
4114                         my $base = $hash_base || git_get_head_hash($project);
4115                         $hash = git_get_hash_by_path($base, $file_name, "blob")
4116                                 or die_error(undef, "Error lookup file");
4117                 } else {
4118                         die_error(undef, "No file name defined");
4119                 }
4120         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4121                 # blobs defined by non-textual hash id's can be cached
4122                 $expires = "+1d";
4123         }
4125         my $type = shift;
4126         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4127                 or die_error(undef, "Couldn't cat $file_name, $hash");
4129         $type ||= blob_mimetype($fd, $file_name);
4131         # save as filename, even when no $file_name is given
4132         my $save_as = "$hash";
4133         if (defined $file_name) {
4134                 $save_as = $file_name;
4135         } elsif ($type =~ m/^text\//) {
4136                 $save_as .= '.txt';
4137         }
4139         print $cgi->header(
4140                 -type => "$type",
4141                 -expires=>$expires,
4142                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
4143         undef $/;
4144         binmode STDOUT, ':raw';
4145         print <$fd>;
4146         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4147         $/ = "\n";
4148         close $fd;
4151 sub git_blob {
4152         my $expires;
4154         if (!defined $hash) {
4155                 if (defined $file_name) {
4156                         my $base = $hash_base || git_get_head_hash($project);
4157                         $hash = git_get_hash_by_path($base, $file_name, "blob")
4158                                 or die_error(undef, "Error lookup file");
4159                 } else {
4160                         die_error(undef, "No file name defined");
4161                 }
4162         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4163                 # blobs defined by non-textual hash id's can be cached
4164                 $expires = "+1d";
4165         }
4167         my ($have_blame) = gitweb_check_feature('blame');
4168         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4169                 or die_error(undef, "Couldn't cat $file_name, $hash");
4170         my $mimetype = blob_mimetype($fd, $file_name);
4171         if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
4172                 close $fd;
4173                 return git_blob_plain($mimetype);
4174         }
4175         # we can have blame only for text/* mimetype
4176         $have_blame &&= ($mimetype =~ m!^text/!);
4178         git_header_html(undef, $expires);
4179         my $formats_nav = '';
4180         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4181                 if (defined $file_name) {
4182                         if ($have_blame) {
4183                                 $formats_nav .=
4184                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
4185                                                                hash=>$hash, file_name=>$file_name)},
4186                                                 "blame") .
4187                                         " | ";
4188                         }
4189                         $formats_nav .=
4190                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4191                                                        hash=>$hash, file_name=>$file_name)},
4192                                         "history") .
4193                                 " | " .
4194                                 $cgi->a({-href => href(action=>"blob_plain",
4195                                                        hash=>$hash, file_name=>$file_name)},
4196                                         "raw") .
4197                                 " | " .
4198                                 $cgi->a({-href => href(action=>"blob",
4199                                                        hash_base=>"HEAD", file_name=>$file_name)},
4200                                         "HEAD");
4201                 } else {
4202                         $formats_nav .=
4203                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
4204                 }
4205                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4206                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4207         } else {
4208                 print "<div class=\"page_nav\">\n" .
4209                       "<br/><br/></div>\n" .
4210                       "<div class=\"title\">$hash</div>\n";
4211         }
4212         git_print_page_path($file_name, "blob", $hash_base);
4213         print "<div class=\"page_body\">\n";
4214         if ($mimetype =~ m!^text/!) {
4215                 my $nr;
4216                 while (my $line = <$fd>) {
4217                         chomp $line;
4218                         $nr++;
4219                         $line = untabify($line);
4220                         printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4221                                $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4222                 }
4223         } elsif ($mimetype =~ m!^image/!) {
4224                 print qq!<img type="$mimetype"!;
4225                 if ($file_name) {
4226                         print qq! alt="$file_name" title="$file_name"!;
4227                 }
4228                 print qq! src="! .
4229                       href(action=>"blob_plain", hash=>$hash,
4230                            hash_base=>$hash_base, file_name=>$file_name) .
4231                       qq!" />\n!;
4232         }
4233         close $fd
4234                 or print "Reading blob failed.\n";
4235         print "</div>";
4236         git_footer_html();
4239 sub git_tree {
4240         if (!defined $hash_base) {
4241                 $hash_base = "HEAD";
4242         }
4243         if (!defined $hash) {
4244                 if (defined $file_name) {
4245                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4246                 } else {
4247                         $hash = $hash_base;
4248                 }
4249         }
4250         $/ = "\0";
4251         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4252                 or die_error(undef, "Open git-ls-tree failed");
4253         my @entries = map { chomp; $_ } <$fd>;
4254         close $fd or die_error(undef, "Reading tree failed");
4255         $/ = "\n";
4257         my $refs = git_get_references();
4258         my $ref = format_ref_marker($refs, $hash_base);
4259         git_header_html();
4260         my $basedir = '';
4261         my ($have_blame) = gitweb_check_feature('blame');
4262         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4263                 my @views_nav = ();
4264                 if (defined $file_name) {
4265                         push @views_nav,
4266                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4267                                                        hash=>$hash, file_name=>$file_name)},
4268                                         "history"),
4269                                 $cgi->a({-href => href(action=>"tree",
4270                                                        hash_base=>"HEAD", file_name=>$file_name)},
4271                                         "HEAD"),
4272                 }
4273                 my $snapshot_links = format_snapshot_links($hash);
4274                 if (defined $snapshot_links) {
4275                         # FIXME: Should be available when we have no hash base as well.
4276                         push @views_nav, $snapshot_links;
4277                 }
4278                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4279                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4280         } else {
4281                 undef $hash_base;
4282                 print "<div class=\"page_nav\">\n";
4283                 print "<br/><br/></div>\n";
4284                 print "<div class=\"title\">$hash</div>\n";
4285         }
4286         if (defined $file_name) {
4287                 $basedir = $file_name;
4288                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4289                         $basedir .= '/';
4290                 }
4291         }
4292         git_print_page_path($file_name, 'tree', $hash_base);
4293         print "<div class=\"page_body\">\n";
4294         print "<table cellspacing=\"0\">\n";
4295         my $alternate = 1;
4296         # '..' (top directory) link if possible
4297         if (defined $hash_base &&
4298             defined $file_name && $file_name =~ m![^/]+$!) {
4299                 if ($alternate) {
4300                         print "<tr class=\"dark\">\n";
4301                 } else {
4302                         print "<tr class=\"light\">\n";
4303                 }
4304                 $alternate ^= 1;
4306                 my $up = $file_name;
4307                 $up =~ s!/?[^/]+$!!;
4308                 undef $up unless $up;
4309                 # based on git_print_tree_entry
4310                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4311                 print '<td class="list">';
4312                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4313                                              file_name=>$up)},
4314                               "..");
4315                 print "</td>\n";
4316                 print "<td class=\"link\"></td>\n";
4318                 print "</tr>\n";
4319         }
4320         foreach my $line (@entries) {
4321                 my %t = parse_ls_tree_line($line, -z => 1);
4323                 if ($alternate) {
4324                         print "<tr class=\"dark\">\n";
4325                 } else {
4326                         print "<tr class=\"light\">\n";
4327                 }
4328                 $alternate ^= 1;
4330                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4332                 print "</tr>\n";
4333         }
4334         print "</table>\n" .
4335               "</div>";
4336         git_footer_html();
4339 sub git_snapshot {
4340         my @supported_fmts = gitweb_check_feature('snapshot');
4341         @supported_fmts = filter_snapshot_fmts(@supported_fmts);
4343         my $format = $cgi->param('sf');
4344         if (!@supported_fmts) {
4345                 die_error('403 Permission denied', "Permission denied");
4346         }
4347         # default to first supported snapshot format
4348         $format ||= $supported_fmts[0];
4349         if ($format !~ m/^[a-z0-9]+$/) {
4350                 die_error(undef, "Invalid snapshot format parameter");
4351         } elsif (!exists($known_snapshot_formats{$format})) {
4352                 die_error(undef, "Unknown snapshot format");
4353         } elsif (!grep($_ eq $format, @supported_fmts)) {
4354                 die_error(undef, "Unsupported snapshot format");
4355         }
4357         if (!defined $hash) {
4358                 $hash = git_get_head_hash($project);
4359         }
4361         my $git_command = git_cmd_str();
4362         my $name = $project;
4363         $name =~ s,([^/])/*\.git$,$1,;
4364         $name = basename($name);
4365         my $filename = to_utf8($name);
4366         $name =~ s/\047/\047\\\047\047/g;
4367         my $cmd;
4368         $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4369         $cmd = "$git_command archive " .
4370                 "--format=$known_snapshot_formats{$format}{'format'} " .
4371                 "--prefix=\'$name\'/ $hash";
4372         if (exists $known_snapshot_formats{$format}{'compressor'}) {
4373                 $cmd .= ' | ' . join ' ', @{$known_snapshot_formats{$format}{'compressor'}};
4374         }
4376         print $cgi->header(
4377                 -type => $known_snapshot_formats{$format}{'type'},
4378                 -content_disposition => 'inline; filename="' . "$filename" . '"',
4379                 -status => '200 OK');
4381         open my $fd, "-|", $cmd
4382                 or die_error(undef, "Execute git-archive failed");
4383         binmode STDOUT, ':raw';
4384         print <$fd>;
4385         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4386         close $fd;
4389 sub git_log {
4390         my $head = git_get_head_hash($project);
4391         if (!defined $hash) {
4392                 $hash = $head;
4393         }
4394         if (!defined $page) {
4395                 $page = 0;
4396         }
4397         my $refs = git_get_references();
4399         my @commitlist = parse_commits($hash, 101, (100 * $page));
4401         my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
4403         git_header_html();
4404         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4406         if (!@commitlist) {
4407                 my %co = parse_commit($hash);
4409                 git_print_header_div('summary', $project);
4410                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4411         }
4412         my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4413         for (my $i = 0; $i <= $to; $i++) {
4414                 my %co = %{$commitlist[$i]};
4415                 next if !%co;
4416                 my $commit = $co{'id'};
4417                 my $ref = format_ref_marker($refs, $commit);
4418                 my %ad = parse_date($co{'author_epoch'});
4419                 git_print_header_div('commit',
4420                                "<span class=\"age\">$co{'age_string'}</span>" .
4421                                esc_html($co{'title'}) . $ref,
4422                                $commit);
4423                 print "<div class=\"title_text\">\n" .
4424                       "<div class=\"log_link\">\n" .
4425                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4426                       " | " .
4427                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4428                       " | " .
4429                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4430                       "<br/>\n" .
4431                       "</div>\n" .
4432                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
4433                       "</div>\n";
4435                 print "<div class=\"log_body\">\n";
4436                 git_print_log($co{'comment'}, -final_empty_line=> 1);
4437                 print "</div>\n";
4438         }
4439         if ($#commitlist >= 100) {
4440                 print "<div class=\"page_nav\">\n";
4441                 print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
4442                                -accesskey => "n", -title => "Alt-n"}, "next");
4443                 print "</div>\n";
4444         }
4445         git_footer_html();
4448 sub git_commit {
4449         $hash ||= $hash_base || "HEAD";
4450         my %co = parse_commit($hash);
4451         if (!%co) {
4452                 die_error(undef, "Unknown commit object");
4453         }
4454         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4455         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4457         my $parent  = $co{'parent'};
4458         my $parents = $co{'parents'}; # listref
4460         # we need to prepare $formats_nav before any parameter munging
4461         my $formats_nav;
4462         if (!defined $parent) {
4463                 # --root commitdiff
4464                 $formats_nav .= '(initial)';
4465         } elsif (@$parents == 1) {
4466                 # single parent commit
4467                 $formats_nav .=
4468                         '(parent: ' .
4469                         $cgi->a({-href => href(action=>"commit",
4470                                                hash=>$parent)},
4471                                 esc_html(substr($parent, 0, 7))) .
4472                         ')';
4473         } else {
4474                 # merge commit
4475                 $formats_nav .=
4476                         '(merge: ' .
4477                         join(' ', map {
4478                                 $cgi->a({-href => href(action=>"commit",
4479                                                        hash=>$_)},
4480                                         esc_html(substr($_, 0, 7)));
4481                         } @$parents ) .
4482                         ')';
4483         }
4485         if (!defined $parent) {
4486                 $parent = "--root";
4487         }
4488         my @difftree;
4489         open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4490                 @diff_opts,
4491                 (@$parents <= 1 ? $parent : '-c'),
4492                 $hash, "--"
4493                 or die_error(undef, "Open git-diff-tree failed");
4494         @difftree = map { chomp; $_ } <$fd>;
4495         close $fd or die_error(undef, "Reading git-diff-tree failed");
4497         # non-textual hash id's can be cached
4498         my $expires;
4499         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4500                 $expires = "+1d";
4501         }
4502         my $refs = git_get_references();
4503         my $ref = format_ref_marker($refs, $co{'id'});
4505         git_header_html(undef, $expires);
4506         git_print_page_nav('commit', '',
4507                            $hash, $co{'tree'}, $hash,
4508                            $formats_nav);
4510         if (defined $co{'parent'}) {
4511                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4512         } else {
4513                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4514         }
4515         print "<div class=\"title_text\">\n" .
4516               "<table cellspacing=\"0\">\n";
4517         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4518               "<tr>" .
4519               "<td></td><td> $ad{'rfc2822'}";
4520         if ($ad{'hour_local'} < 6) {
4521                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4522                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4523         } else {
4524                 printf(" (%02d:%02d %s)",
4525                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4526         }
4527         print "</td>" .
4528               "</tr>\n";
4529         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4530         print "<tr><td></td><td> $cd{'rfc2822'}" .
4531               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4532               "</td></tr>\n";
4533         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4534         print "<tr>" .
4535               "<td>tree</td>" .
4536               "<td class=\"sha1\">" .
4537               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4538                        class => "list"}, $co{'tree'}) .
4539               "</td>" .
4540               "<td class=\"link\">" .
4541               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4542                       "tree");
4543         my $snapshot_links = format_snapshot_links($hash);
4544         if (defined $snapshot_links) {
4545                 print " | " . $snapshot_links;
4546         }
4547         print "</td>" .
4548               "</tr>\n";
4550         foreach my $par (@$parents) {
4551                 print "<tr>" .
4552                       "<td>parent</td>" .
4553                       "<td class=\"sha1\">" .
4554                       $cgi->a({-href => href(action=>"commit", hash=>$par),
4555                                class => "list"}, $par) .
4556                       "</td>" .
4557                       "<td class=\"link\">" .
4558                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4559                       " | " .
4560                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4561                       "</td>" .
4562                       "</tr>\n";
4563         }
4564         print "</table>".
4565               "</div>\n";
4567         print "<div class=\"page_body\">\n";
4568         git_print_log($co{'comment'});
4569         print "</div>\n";
4571         git_difftree_body(\@difftree, $hash, @$parents);
4573         git_footer_html();
4576 sub git_object {
4577         # object is defined by:
4578         # - hash or hash_base alone
4579         # - hash_base and file_name
4580         my $type;
4582         # - hash or hash_base alone
4583         if ($hash || ($hash_base && !defined $file_name)) {
4584                 my $object_id = $hash || $hash_base;
4586                 my $git_command = git_cmd_str();
4587                 open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
4588                         or die_error('404 Not Found', "Object does not exist");
4589                 $type = <$fd>;
4590                 chomp $type;
4591                 close $fd
4592                         or die_error('404 Not Found', "Object does not exist");
4594         # - hash_base and file_name
4595         } elsif ($hash_base && defined $file_name) {
4596                 $file_name =~ s,/+$,,;
4598                 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4599                         or die_error('404 Not Found', "Base object does not exist");
4601                 # here errors should not hapen
4602                 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4603                         or die_error(undef, "Open git-ls-tree failed");
4604                 my $line = <$fd>;
4605                 close $fd;
4607                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
4608                 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4609                         die_error('404 Not Found', "File or directory for given base does not exist");
4610                 }
4611                 $type = $2;
4612                 $hash = $3;
4613         } else {
4614                 die_error('404 Not Found', "Not enough information to find object");
4615         }
4617         print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4618                                           hash=>$hash, hash_base=>$hash_base,
4619                                           file_name=>$file_name),
4620                              -status => '302 Found');
4623 sub git_blobdiff {
4624         my $format = shift || 'html';
4626         my $fd;
4627         my @difftree;
4628         my %diffinfo;
4629         my $expires;
4631         # preparing $fd and %diffinfo for git_patchset_body
4632         # new style URI
4633         if (defined $hash_base && defined $hash_parent_base) {
4634                 if (defined $file_name) {
4635                         # read raw output
4636                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4637                                 $hash_parent_base, $hash_base,
4638                                 "--", (defined $file_parent ? $file_parent : ()), $file_name
4639                                 or die_error(undef, "Open git-diff-tree failed");
4640                         @difftree = map { chomp; $_ } <$fd>;
4641                         close $fd
4642                                 or die_error(undef, "Reading git-diff-tree failed");
4643                         @difftree
4644                                 or die_error('404 Not Found', "Blob diff not found");
4646                 } elsif (defined $hash &&
4647                          $hash =~ /[0-9a-fA-F]{40}/) {
4648                         # try to find filename from $hash
4650                         # read filtered raw output
4651                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4652                                 $hash_parent_base, $hash_base, "--"
4653                                 or die_error(undef, "Open git-diff-tree failed");
4654                         @difftree =
4655                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
4656                                 # $hash == to_id
4657                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4658                                 map { chomp; $_ } <$fd>;
4659                         close $fd
4660                                 or die_error(undef, "Reading git-diff-tree failed");
4661                         @difftree
4662                                 or die_error('404 Not Found', "Blob diff not found");
4664                 } else {
4665                         die_error('404 Not Found', "Missing one of the blob diff parameters");
4666                 }
4668                 if (@difftree > 1) {
4669                         die_error('404 Not Found', "Ambiguous blob diff specification");
4670                 }
4672                 %diffinfo = parse_difftree_raw_line($difftree[0]);
4673                 $file_parent ||= $diffinfo{'from_file'} || $file_name;
4674                 $file_name   ||= $diffinfo{'to_file'};
4676                 $hash_parent ||= $diffinfo{'from_id'};
4677                 $hash        ||= $diffinfo{'to_id'};
4679                 # non-textual hash id's can be cached
4680                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4681                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4682                         $expires = '+1d';
4683                 }
4685                 # open patch output
4686                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4687                         '-p', ($format eq 'html' ? "--full-index" : ()),
4688                         $hash_parent_base, $hash_base,
4689                         "--", (defined $file_parent ? $file_parent : ()), $file_name
4690                         or die_error(undef, "Open git-diff-tree failed");
4691         }
4693         # old/legacy style URI
4694         if (!%diffinfo && # if new style URI failed
4695             defined $hash && defined $hash_parent) {
4696                 # fake git-diff-tree raw output
4697                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4698                 $diffinfo{'from_id'} = $hash_parent;
4699                 $diffinfo{'to_id'}   = $hash;
4700                 if (defined $file_name) {
4701                         if (defined $file_parent) {
4702                                 $diffinfo{'status'} = '2';
4703                                 $diffinfo{'from_file'} = $file_parent;
4704                                 $diffinfo{'to_file'}   = $file_name;
4705                         } else { # assume not renamed
4706                                 $diffinfo{'status'} = '1';
4707                                 $diffinfo{'from_file'} = $file_name;
4708                                 $diffinfo{'to_file'}   = $file_name;
4709                         }
4710                 } else { # no filename given
4711                         $diffinfo{'status'} = '2';
4712                         $diffinfo{'from_file'} = $hash_parent;
4713                         $diffinfo{'to_file'}   = $hash;
4714                 }
4716                 # non-textual hash id's can be cached
4717                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4718                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4719                         $expires = '+1d';
4720                 }
4722                 # open patch output
4723                 open $fd, "-|", git_cmd(), "diff", @diff_opts,
4724                         '-p', ($format eq 'html' ? "--full-index" : ()),
4725                         $hash_parent, $hash, "--"
4726                         or die_error(undef, "Open git-diff failed");
4727         } else  {
4728                 die_error('404 Not Found', "Missing one of the blob diff parameters")
4729                         unless %diffinfo;
4730         }
4732         # header
4733         if ($format eq 'html') {
4734                 my $formats_nav =
4735                         $cgi->a({-href => href(action=>"blobdiff_plain",
4736                                                hash=>$hash, hash_parent=>$hash_parent,
4737                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
4738                                                file_name=>$file_name, file_parent=>$file_parent)},
4739                                 "raw");
4740                 git_header_html(undef, $expires);
4741                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4742                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4743                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4744                 } else {
4745                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4746                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4747                 }
4748                 if (defined $file_name) {
4749                         git_print_page_path($file_name, "blob", $hash_base);
4750                 } else {
4751                         print "<div class=\"page_path\"></div>\n";
4752                 }
4754         } elsif ($format eq 'plain') {
4755                 print $cgi->header(
4756                         -type => 'text/plain',
4757                         -charset => 'utf-8',
4758                         -expires => $expires,
4759                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4761                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4763         } else {
4764                 die_error(undef, "Unknown blobdiff format");
4765         }
4767         # patch
4768         if ($format eq 'html') {
4769                 print "<div class=\"page_body\">\n";
4771                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4772                 close $fd;
4774                 print "</div>\n"; # class="page_body"
4775                 git_footer_html();
4777         } else {
4778                 while (my $line = <$fd>) {
4779                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4780                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4782                         print $line;
4784                         last if $line =~ m!^\+\+\+!;
4785                 }
4786                 local $/ = undef;
4787                 print <$fd>;
4788                 close $fd;
4789         }
4792 sub git_blobdiff_plain {
4793         git_blobdiff('plain');
4796 sub git_commitdiff {
4797         my $format = shift || 'html';
4798         $hash ||= $hash_base || "HEAD";
4799         my %co = parse_commit($hash);
4800         if (!%co) {
4801                 die_error(undef, "Unknown commit object");
4802         }
4804         # choose format for commitdiff for merge
4805         if (! defined $hash_parent && @{$co{'parents'}} > 1) {
4806                 $hash_parent = '--cc';
4807         }
4808         # we need to prepare $formats_nav before almost any parameter munging
4809         my $formats_nav;
4810         if ($format eq 'html') {
4811                 $formats_nav =
4812                         $cgi->a({-href => href(action=>"commitdiff_plain",
4813                                                hash=>$hash, hash_parent=>$hash_parent)},
4814                                 "raw");
4816                 if (defined $hash_parent &&
4817                     $hash_parent ne '-c' && $hash_parent ne '--cc') {
4818                         # commitdiff with two commits given
4819                         my $hash_parent_short = $hash_parent;
4820                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4821                                 $hash_parent_short = substr($hash_parent, 0, 7);
4822                         }
4823                         $formats_nav .=
4824                                 ' (from';
4825                         for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
4826                                 if ($co{'parents'}[$i] eq $hash_parent) {
4827                                         $formats_nav .= ' parent ' . ($i+1);
4828                                         last;
4829                                 }
4830                         }
4831                         $formats_nav .= ': ' .
4832                                 $cgi->a({-href => href(action=>"commitdiff",
4833                                                        hash=>$hash_parent)},
4834                                         esc_html($hash_parent_short)) .
4835                                 ')';
4836                 } elsif (!$co{'parent'}) {
4837                         # --root commitdiff
4838                         $formats_nav .= ' (initial)';
4839                 } elsif (scalar @{$co{'parents'}} == 1) {
4840                         # single parent commit
4841                         $formats_nav .=
4842                                 ' (parent: ' .
4843                                 $cgi->a({-href => href(action=>"commitdiff",
4844                                                        hash=>$co{'parent'})},
4845                                         esc_html(substr($co{'parent'}, 0, 7))) .
4846                                 ')';
4847                 } else {
4848                         # merge commit
4849                         if ($hash_parent eq '--cc') {
4850                                 $formats_nav .= ' | ' .
4851                                         $cgi->a({-href => href(action=>"commitdiff",
4852                                                                hash=>$hash, hash_parent=>'-c')},
4853                                                 'combined');
4854                         } else { # $hash_parent eq '-c'
4855                                 $formats_nav .= ' | ' .
4856                                         $cgi->a({-href => href(action=>"commitdiff",
4857                                                                hash=>$hash, hash_parent=>'--cc')},
4858                                                 'compact');
4859                         }
4860                         $formats_nav .=
4861                                 ' (merge: ' .
4862                                 join(' ', map {
4863                                         $cgi->a({-href => href(action=>"commitdiff",
4864                                                                hash=>$_)},
4865                                                 esc_html(substr($_, 0, 7)));
4866                                 } @{$co{'parents'}} ) .
4867                                 ')';
4868                 }
4869         }
4871         my $hash_parent_param = $hash_parent;
4872         if (!defined $hash_parent_param) {
4873                 # --cc for multiple parents, --root for parentless
4874                 $hash_parent_param =
4875                         @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
4876         }
4878         # read commitdiff
4879         my $fd;
4880         my @difftree;
4881         if ($format eq 'html') {
4882                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4883                         "--no-commit-id", "--patch-with-raw", "--full-index",
4884                         $hash_parent_param, $hash, "--"
4885                         or die_error(undef, "Open git-diff-tree failed");
4887                 while (my $line = <$fd>) {
4888                         chomp $line;
4889                         # empty line ends raw part of diff-tree output
4890                         last unless $line;
4891                         push @difftree, scalar parse_difftree_raw_line($line);
4892                 }
4894         } elsif ($format eq 'plain') {
4895                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4896                         '-p', $hash_parent_param, $hash, "--"
4897                         or die_error(undef, "Open git-diff-tree failed");
4899         } else {
4900                 die_error(undef, "Unknown commitdiff format");
4901         }
4903         # non-textual hash id's can be cached
4904         my $expires;
4905         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4906                 $expires = "+1d";
4907         }
4909         # write commit message
4910         if ($format eq 'html') {
4911                 my $refs = git_get_references();
4912                 my $ref = format_ref_marker($refs, $co{'id'});
4914                 git_header_html(undef, $expires);
4915                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4916                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4917                 git_print_authorship(\%co);
4918                 print "<div class=\"page_body\">\n";
4919                 if (@{$co{'comment'}} > 1) {
4920                         print "<div class=\"log\">\n";
4921                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4922                         print "</div>\n"; # class="log"
4923                 }
4925         } elsif ($format eq 'plain') {
4926                 my $refs = git_get_references("tags");
4927                 my $tagname = git_get_rev_name_tags($hash);
4928                 my $filename = basename($project) . "-$hash.patch";
4930                 print $cgi->header(
4931                         -type => 'text/plain',
4932                         -charset => 'utf-8',
4933                         -expires => $expires,
4934                         -content_disposition => 'inline; filename="' . "$filename" . '"');
4935                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4936                 print <<TEXT;
4937 From: $co{'author'}
4938 Date: $ad{'rfc2822'} ($ad{'tz_local'})
4939 Subject: $co{'title'}
4940 TEXT
4941                 print "X-Git-Tag: $tagname\n" if $tagname;
4942                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4944                 foreach my $line (@{$co{'comment'}}) {
4945                         print "$line\n";
4946                 }
4947                 print "---\n\n";
4948         }
4950         # write patch
4951         if ($format eq 'html') {
4952                 my $use_parents = !defined $hash_parent ||
4953                         $hash_parent eq '-c' || $hash_parent eq '--cc';
4954                 git_difftree_body(\@difftree, $hash,
4955                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
4956                 print "<br/>\n";
4958                 git_patchset_body($fd, \@difftree, $hash,
4959                                   $use_parents ? @{$co{'parents'}} : $hash_parent);
4960                 close $fd;
4961                 print "</div>\n"; # class="page_body"
4962                 git_footer_html();
4964         } elsif ($format eq 'plain') {
4965                 local $/ = undef;
4966                 print <$fd>;
4967                 close $fd
4968                         or print "Reading git-diff-tree failed\n";
4969         }
4972 sub git_commitdiff_plain {
4973         git_commitdiff('plain');
4976 sub git_history {
4977         if (!defined $hash_base) {
4978                 $hash_base = git_get_head_hash($project);
4979         }
4980         if (!defined $page) {
4981                 $page = 0;
4982         }
4983         my $ftype;
4984         my %co = parse_commit($hash_base);
4985         if (!%co) {
4986                 die_error(undef, "Unknown commit object");
4987         }
4989         my $refs = git_get_references();
4990         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4992         if (!defined $hash && defined $file_name) {
4993                 $hash = git_get_hash_by_path($hash_base, $file_name);
4994         }
4995         if (defined $hash) {
4996                 $ftype = git_get_type($hash);
4997         }
4999         my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
5001         my $paging_nav = '';
5002         if ($page > 0) {
5003                 $paging_nav .=
5004                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5005                                                file_name=>$file_name)},
5006                                 "first");
5007                 $paging_nav .= " &sdot; " .
5008                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5009                                                file_name=>$file_name, page=>$page-1),
5010                                  -accesskey => "p", -title => "Alt-p"}, "prev");
5011         } else {
5012                 $paging_nav .= "first";
5013                 $paging_nav .= " &sdot; prev";
5014         }
5015         if ($#commitlist >= 100) {
5016                 $paging_nav .= " &sdot; " .
5017                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5018                                                file_name=>$file_name, page=>$page+1),
5019                                  -accesskey => "n", -title => "Alt-n"}, "next");
5020         } else {
5021                 $paging_nav .= " &sdot; next";
5022         }
5023         my $next_link = '';
5024         if ($#commitlist >= 100) {
5025                 $next_link =
5026                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5027                                                file_name=>$file_name, page=>$page+1),
5028                                  -accesskey => "n", -title => "Alt-n"}, "next");
5029         }
5031         git_header_html();
5032         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5033         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5034         git_print_page_path($file_name, $ftype, $hash_base);
5036         git_history_body(\@commitlist, 0, 99,
5037                          $refs, $hash_base, $ftype, $next_link);
5039         git_footer_html();
5042 sub git_search {
5043         my ($have_search) = gitweb_check_feature('search');
5044         if (!$have_search) {
5045                 die_error('403 Permission denied', "Permission denied");
5046         }
5047         if (!defined $searchtext) {
5048                 die_error(undef, "Text field empty");
5049         }
5050         if (!defined $hash) {
5051                 $hash = git_get_head_hash($project);
5052         }
5053         my %co = parse_commit($hash);
5054         if (!%co) {
5055                 die_error(undef, "Unknown commit object");
5056         }
5057         if (!defined $page) {
5058                 $page = 0;
5059         }
5061         $searchtype ||= 'commit';
5062         if ($searchtype eq 'pickaxe') {
5063                 # pickaxe may take all resources of your box and run for several minutes
5064                 # with every query - so decide by yourself how public you make this feature
5065                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5066                 if (!$have_pickaxe) {
5067                         die_error('403 Permission denied', "Permission denied");
5068                 }
5069         }
5070         if ($searchtype eq 'grep') {
5071                 my ($have_grep) = gitweb_check_feature('grep');
5072                 if (!$have_grep) {
5073                         die_error('403 Permission denied', "Permission denied");
5074                 }
5075         }
5077         git_header_html();
5079         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5080                 my $greptype;
5081                 if ($searchtype eq 'commit') {
5082                         $greptype = "--grep=";
5083                 } elsif ($searchtype eq 'author') {
5084                         $greptype = "--author=";
5085                 } elsif ($searchtype eq 'committer') {
5086                         $greptype = "--committer=";
5087                 }
5088                 $greptype .= $search_regexp;
5089                 my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
5091                 my $paging_nav = '';
5092                 if ($page > 0) {
5093                         $paging_nav .=
5094                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5095                                                        searchtext=>$searchtext, searchtype=>$searchtype)},
5096                                         "first");
5097                         $paging_nav .= " &sdot; " .
5098                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5099                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5100                                                        page=>$page-1),
5101                                          -accesskey => "p", -title => "Alt-p"}, "prev");
5102                 } else {
5103                         $paging_nav .= "first";
5104                         $paging_nav .= " &sdot; prev";
5105                 }
5106                 if ($#commitlist >= 100) {
5107                         $paging_nav .= " &sdot; " .
5108                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5109                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5110                                                        page=>$page+1),
5111                                          -accesskey => "n", -title => "Alt-n"}, "next");
5112                 } else {
5113                         $paging_nav .= " &sdot; next";
5114                 }
5115                 my $next_link = '';
5116                 if ($#commitlist >= 100) {
5117                         $next_link =
5118                                 $cgi->a({-href => href(action=>"search", hash=>$hash,
5119                                                        searchtext=>$searchtext, searchtype=>$searchtype,
5120                                                        page=>$page+1),
5121                                          -accesskey => "n", -title => "Alt-n"}, "next");
5122                 }
5124                 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5125                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5126                 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5127         }
5129         if ($searchtype eq 'pickaxe') {
5130                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5131                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5133                 print "<table cellspacing=\"0\">\n";
5134                 my $alternate = 1;
5135                 $/ = "\n";
5136                 my $git_command = git_cmd_str();
5137                 my $searchqtext = $searchtext;
5138                 $searchqtext =~ s/'/'\\''/;
5139                 open my $fd, "-|", "$git_command rev-list $hash | " .
5140                         "$git_command diff-tree -r --stdin -S\'$searchqtext\'";
5141                 undef %co;
5142                 my @files;
5143                 while (my $line = <$fd>) {
5144                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
5145                                 my %set;
5146                                 $set{'file'} = $6;
5147                                 $set{'from_id'} = $3;
5148                                 $set{'to_id'} = $4;
5149                                 $set{'id'} = $set{'to_id'};
5150                                 if ($set{'id'} =~ m/0{40}/) {
5151                                         $set{'id'} = $set{'from_id'};
5152                                 }
5153                                 if ($set{'id'} =~ m/0{40}/) {
5154                                         next;
5155                                 }
5156                                 push @files, \%set;
5157                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
5158                                 if (%co) {
5159                                         if ($alternate) {
5160                                                 print "<tr class=\"dark\">\n";
5161                                         } else {
5162                                                 print "<tr class=\"light\">\n";
5163                                         }
5164                                         $alternate ^= 1;
5165                                         my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5166                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5167                                               "<td><i>" . $author . "</i></td>\n" .
5168                                               "<td>" .
5169                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5170                                                       -class => "list subject"},
5171                                                       chop_and_escape_str($co{'title'}, 50) . "<br/>");
5172                                         while (my $setref = shift @files) {
5173                                                 my %set = %$setref;
5174                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5175                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
5176                                                               -class => "list"},
5177                                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5178                                                       "<br/>\n";
5179                                         }
5180                                         print "</td>\n" .
5181                                               "<td class=\"link\">" .
5182                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5183                                               " | " .
5184                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5185                                         print "</td>\n" .
5186                                               "</tr>\n";
5187                                 }
5188                                 %co = parse_commit($1);
5189                         }
5190                 }
5191                 close $fd;
5193                 print "</table>\n";
5194         }
5196         if ($searchtype eq 'grep') {
5197                 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5198                 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5200                 print "<table cellspacing=\"0\">\n";
5201                 my $alternate = 1;
5202                 my $matches = 0;
5203                 $/ = "\n";
5204                 open my $fd, "-|", git_cmd(), 'grep', '-n', '-i', '-E', $searchtext, $co{'tree'};
5205                 my $lastfile = '';
5206                 while (my $line = <$fd>) {
5207                         chomp $line;
5208                         my ($file, $lno, $ltext, $binary);
5209                         last if ($matches++ > 1000);
5210                         if ($line =~ /^Binary file (.+) matches$/) {
5211                                 $file = $1;
5212                                 $binary = 1;
5213                         } else {
5214                                 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5215                         }
5216                         if ($file ne $lastfile) {
5217                                 $lastfile and print "</td></tr>\n";
5218                                 if ($alternate++) {
5219                                         print "<tr class=\"dark\">\n";
5220                                 } else {
5221                                         print "<tr class=\"light\">\n";
5222                                 }
5223                                 print "<td class=\"list\">".
5224                                         $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5225                                                                file_name=>"$file"),
5226                                                 -class => "list"}, esc_path($file));
5227                                 print "</td><td>\n";
5228                                 $lastfile = $file;
5229                         }
5230                         if ($binary) {
5231                                 print "<div class=\"binary\">Binary file</div>\n";
5232                         } else {
5233                                 $ltext = untabify($ltext);
5234                                 if ($ltext =~ m/^(.*)($searchtext)(.*)$/i) {
5235                                         $ltext = esc_html($1, -nbsp=>1);
5236                                         $ltext .= '<span class="match">';
5237                                         $ltext .= esc_html($2, -nbsp=>1);
5238                                         $ltext .= '</span>';
5239                                         $ltext .= esc_html($3, -nbsp=>1);
5240                                 } else {
5241                                         $ltext = esc_html($ltext, -nbsp=>1);
5242                                 }
5243                                 print "<div class=\"pre\">" .
5244                                         $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5245                                                                file_name=>"$file").'#l'.$lno,
5246                                                 -class => "linenr"}, sprintf('%4i', $lno))
5247                                         . ' ' .  $ltext . "</div>\n";
5248                         }
5249                 }
5250                 if ($lastfile) {
5251                         print "</td></tr>\n";
5252                         if ($matches > 1000) {
5253                                 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5254                         }
5255                 } else {
5256                         print "<div class=\"diff nodifferences\">No matches found</div>\n";
5257                 }
5258                 close $fd;
5260                 print "</table>\n";
5261         }
5262         git_footer_html();
5265 sub git_search_help {
5266         git_header_html();
5267         git_print_page_nav('','', $hash,$hash,$hash);
5268         print <<EOT;
5269 <dl>
5270 <dt><b>commit</b></dt>
5271 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
5272 EOT
5273         my ($have_grep) = gitweb_check_feature('grep');
5274         if ($have_grep) {
5275                 print <<EOT;
5276 <dt><b>grep</b></dt>
5277 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5278     a different one) are searched for the given
5279 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a>
5280 (POSIX extended) and the matches are listed. On large
5281 trees, this search can take a while and put some strain on the server, so please use it with
5282 some consideration.</dd>
5283 EOT
5284         }
5285         print <<EOT;
5286 <dt><b>author</b></dt>
5287 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
5288 <dt><b>committer</b></dt>
5289 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
5290 EOT
5291         my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5292         if ($have_pickaxe) {
5293                 print <<EOT;
5294 <dt><b>pickaxe</b></dt>
5295 <dd>All commits that caused the string to appear or disappear from any file (changes that
5296 added, removed or "modified" the string) will be listed. This search can take a while and
5297 takes a lot of strain on the server, so please use it wisely.</dd>
5298 EOT
5299         }
5300         print "</dl>\n";
5301         git_footer_html();
5304 sub git_shortlog {
5305         my $head = git_get_head_hash($project);
5306         if (!defined $hash) {
5307                 $hash = $head;
5308         }
5309         if (!defined $page) {
5310                 $page = 0;
5311         }
5312         my $refs = git_get_references();
5314         my @commitlist = parse_commits($hash, 101, (100 * $page));
5316         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
5317         my $next_link = '';
5318         if ($#commitlist >= 100) {
5319                 $next_link =
5320                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
5321                                  -accesskey => "n", -title => "Alt-n"}, "next");
5322         }
5324         git_header_html();
5325         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5326         git_print_header_div('summary', $project);
5328         git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5330         git_footer_html();
5333 ## ......................................................................
5334 ## feeds (RSS, Atom; OPML)
5336 sub git_feed {
5337         my $format = shift || 'atom';
5338         my ($have_blame) = gitweb_check_feature('blame');
5340         # Atom: http://www.atomenabled.org/developers/syndication/
5341         # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5342         if ($format ne 'rss' && $format ne 'atom') {
5343                 die_error(undef, "Unknown web feed format");
5344         }
5346         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5347         my $head = $hash || 'HEAD';
5348         my @commitlist = parse_commits($head, 150, 0, undef, $file_name);
5350         my %latest_commit;
5351         my %latest_date;
5352         my $content_type = "application/$format+xml";
5353         if (defined $cgi->http('HTTP_ACCEPT') &&
5354                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5355                 # browser (feed reader) prefers text/xml
5356                 $content_type = 'text/xml';
5357         }
5358         if (defined($commitlist[0])) {
5359                 %latest_commit = %{$commitlist[0]};
5360                 %latest_date   = parse_date($latest_commit{'author_epoch'});
5361                 print $cgi->header(
5362                         -type => $content_type,
5363                         -charset => 'utf-8',
5364                         -last_modified => $latest_date{'rfc2822'});
5365         } else {
5366                 print $cgi->header(
5367                         -type => $content_type,
5368                         -charset => 'utf-8');
5369         }
5371         # Optimization: skip generating the body if client asks only
5372         # for Last-Modified date.
5373         return if ($cgi->request_method() eq 'HEAD');
5375         # header variables
5376         my $title = "$site_name - $project/$action";
5377         my $feed_type = 'log';
5378         if (defined $hash) {
5379                 $title .= " - '$hash'";
5380                 $feed_type = 'branch log';
5381                 if (defined $file_name) {
5382                         $title .= " :: $file_name";
5383                         $feed_type = 'history';
5384                 }
5385         } elsif (defined $file_name) {
5386                 $title .= " - $file_name";
5387                 $feed_type = 'history';
5388         }
5389         $title .= " $feed_type";
5390         my $descr = git_get_project_description($project);
5391         if (defined $descr) {
5392                 $descr = esc_html($descr);
5393         } else {
5394                 $descr = "$project " .
5395                          ($format eq 'rss' ? 'RSS' : 'Atom') .
5396                          " feed";
5397         }
5398         my $owner = git_get_project_owner($project);
5399         $owner = esc_html($owner);
5401         #header
5402         my $alt_url;
5403         if (defined $file_name) {
5404                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5405         } elsif (defined $hash) {
5406                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5407         } else {
5408                 $alt_url = href(-full=>1, action=>"summary");
5409         }
5410         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5411         if ($format eq 'rss') {
5412                 print <<XML;
5413 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5414 <channel>
5415 XML
5416                 print "<title>$title</title>\n" .
5417                       "<link>$alt_url</link>\n" .
5418                       "<description>$descr</description>\n" .
5419                       "<language>en</language>\n";
5420         } elsif ($format eq 'atom') {
5421                 print <<XML;
5422 <feed xmlns="http://www.w3.org/2005/Atom">
5423 XML
5424                 print "<title>$title</title>\n" .
5425                       "<subtitle>$descr</subtitle>\n" .
5426                       '<link rel="alternate" type="text/html" href="' .
5427                       $alt_url . '" />' . "\n" .
5428                       '<link rel="self" type="' . $content_type . '" href="' .
5429                       $cgi->self_url() . '" />' . "\n" .
5430                       "<id>" . href(-full=>1) . "</id>\n" .
5431                       # use project owner for feed author
5432                       "<author><name>$owner</name></author>\n";
5433                 if (defined $favicon) {
5434                         print "<icon>" . esc_url($favicon) . "</icon>\n";
5435                 }
5436                 if (defined $logo_url) {
5437                         # not twice as wide as tall: 72 x 27 pixels
5438                         print "<logo>" . esc_url($logo) . "</logo>\n";
5439                 }
5440                 if (! %latest_date) {
5441                         # dummy date to keep the feed valid until commits trickle in:
5442                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
5443                 } else {
5444                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
5445                 }
5446         }
5448         # contents
5449         for (my $i = 0; $i <= $#commitlist; $i++) {
5450                 my %co = %{$commitlist[$i]};
5451                 my $commit = $co{'id'};
5452                 # we read 150, we always show 30 and the ones more recent than 48 hours
5453                 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5454                         last;
5455                 }
5456                 my %cd = parse_date($co{'author_epoch'});
5458                 # get list of changed files
5459                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5460                         $co{'parent'} || "--root",
5461                         $co{'id'}, "--", (defined $file_name ? $file_name : ())
5462                         or next;
5463                 my @difftree = map { chomp; $_ } <$fd>;
5464                 close $fd
5465                         or next;
5467                 # print element (entry, item)
5468                 my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
5469                 if ($format eq 'rss') {
5470                         print "<item>\n" .
5471                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
5472                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
5473                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5474                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5475                               "<link>$co_url</link>\n" .
5476                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
5477                               "<content:encoded>" .
5478                               "<![CDATA[\n";
5479                 } elsif ($format eq 'atom') {
5480                         print "<entry>\n" .
5481                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5482                               "<updated>$cd{'iso-8601'}</updated>\n" .
5483                               "<author>\n" .
5484                               "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
5485                         if ($co{'author_email'}) {
5486                                 print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
5487                         }
5488                         print "</author>\n" .
5489                               # use committer for contributor
5490                               "<contributor>\n" .
5491                               "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5492                         if ($co{'committer_email'}) {
5493                                 print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5494                         }
5495                         print "</contributor>\n" .
5496                               "<published>$cd{'iso-8601'}</published>\n" .
5497                               "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5498                               "<id>$co_url</id>\n" .
5499                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5500                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5501                 }
5502                 my $comment = $co{'comment'};
5503                 print "<pre>\n";
5504                 foreach my $line (@$comment) {
5505                         $line = esc_html($line);
5506                         print "$line\n";
5507                 }
5508                 print "</pre><ul>\n";
5509                 foreach my $difftree_line (@difftree) {
5510                         my %difftree = parse_difftree_raw_line($difftree_line);
5511                         next if !$difftree{'from_id'};
5513                         my $file = $difftree{'file'} || $difftree{'to_file'};
5515                         print "<li>" .
5516                               "[" .
5517                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5518                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5519                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5520                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
5521                                       -title => "diff"}, 'D');
5522                         if ($have_blame) {
5523                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
5524                                                              file_name=>$file, hash_base=>$commit),
5525                                               -title => "blame"}, 'B');
5526                         }
5527                         # if this is not a feed of a file history
5528                         if (!defined $file_name || $file_name ne $file) {
5529                                 print $cgi->a({-href => href(-full=>1, action=>"history",
5530                                                              file_name=>$file, hash=>$commit),
5531                                               -title => "history"}, 'H');
5532                         }
5533                         $file = esc_path($file);
5534                         print "] ".
5535                               "$file</li>\n";
5536                 }
5537                 if ($format eq 'rss') {
5538                         print "</ul>]]>\n" .
5539                               "</content:encoded>\n" .
5540                               "</item>\n";
5541                 } elsif ($format eq 'atom') {
5542                         print "</ul>\n</div>\n" .
5543                               "</content>\n" .
5544                               "</entry>\n";
5545                 }
5546         }
5548         # end of feed
5549         if ($format eq 'rss') {
5550                 print "</channel>\n</rss>\n";
5551         }       elsif ($format eq 'atom') {
5552                 print "</feed>\n";
5553         }
5556 sub git_rss {
5557         git_feed('rss');
5560 sub git_atom {
5561         git_feed('atom');
5564 sub git_opml {
5565         my @list = git_get_projects_list();
5567         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5568         print <<XML;
5569 <?xml version="1.0" encoding="utf-8"?>
5570 <opml version="1.0">
5571 <head>
5572   <title>$site_name OPML Export</title>
5573 </head>
5574 <body>
5575 <outline text="git RSS feeds">
5576 XML
5578         foreach my $pr (@list) {
5579                 my %proj = %$pr;
5580                 my $head = git_get_head_hash($proj{'path'});
5581                 if (!defined $head) {
5582                         next;
5583                 }
5584                 $git_dir = "$projectroot/$proj{'path'}";
5585                 my %co = parse_commit($head);
5586                 if (!%co) {
5587                         next;
5588                 }
5590                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5591                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
5592                 my $html = "$my_url?p=$proj{'path'};a=summary";
5593                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5594         }
5595         print <<XML;
5596 </outline>
5597 </body>
5598 </opml>
5599 XML