Code

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