Code

Use extended SHA1 syntax in merge-recursive conflicts.
[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 our $cgi = new CGI;
22 our $version = "++GIT_VERSION++";
23 our $my_url = $cgi->url();
24 our $my_uri = $cgi->url(-absolute => 1);
26 # core git executable to use
27 # this can just be "git" if your webserver has a sensible PATH
28 our $GIT = "++GIT_BINDIR++/git";
30 # absolute fs-path which will be prepended to the project path
31 #our $projectroot = "/pub/scm";
32 our $projectroot = "++GITWEB_PROJECTROOT++";
34 # target of the home link on top of all pages
35 our $home_link = $my_uri || "/";
37 # string of the home link on top of all pages
38 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
40 # name of your site or organization to appear in page titles
41 # replace this with something more descriptive for clearer bookmarks
42 our $site_name = "++GITWEB_SITENAME++"
43                  || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
45 # filename of html text to include at top of each page
46 our $site_header = "++GITWEB_SITE_HEADER++";
47 # html text to include at home page
48 our $home_text = "++GITWEB_HOMETEXT++";
49 # filename of html text to include at bottom of each page
50 our $site_footer = "++GITWEB_SITE_FOOTER++";
52 # URI of stylesheets
53 our @stylesheets = ("++GITWEB_CSS++");
54 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
55 our $stylesheet = undef;
56 # URI of GIT logo (72x27 size)
57 our $logo = "++GITWEB_LOGO++";
58 # URI of GIT favicon, assumed to be image/png type
59 our $favicon = "++GITWEB_FAVICON++";
61 # URI and label (title) of GIT logo link
62 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
63 #our $logo_label = "git documentation";
64 our $logo_url = "http://git.or.cz/";
65 our $logo_label = "git homepage";
67 # source of projects list
68 our $projects_list = "++GITWEB_LIST++";
70 # show repository only if this file exists
71 # (only effective if this variable evaluates to true)
72 our $export_ok = "++GITWEB_EXPORT_OK++";
74 # only allow viewing of repositories also shown on the overview page
75 our $strict_export = "++GITWEB_STRICT_EXPORT++";
77 # list of git base URLs used for URL to where fetch project from,
78 # i.e. full URL is "$git_base_url/$project"
79 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
81 # default blob_plain mimetype and default charset for text/plain blob
82 our $default_blob_plain_mimetype = 'text/plain';
83 our $default_text_plain_charset  = undef;
85 # file to use for guessing MIME types before trying /etc/mime.types
86 # (relative to the current git repository)
87 our $mimetypes_file = undef;
89 # You define site-wide feature defaults here; override them with
90 # $GITWEB_CONFIG as necessary.
91 our %feature = (
92         # feature => {
93         #       'sub' => feature-sub (subroutine),
94         #       'override' => allow-override (boolean),
95         #       'default' => [ default options...] (array reference)}
96         #
97         # if feature is overridable (it means that allow-override has true value,
98         # then feature-sub will be called with default options as parameters;
99         # return value of feature-sub indicates if to enable specified feature
100         #
101         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
103         # Enable the 'blame' blob view, showing the last commit that modified
104         # each line in the file. This can be very CPU-intensive.
106         # To enable system wide have in $GITWEB_CONFIG
107         # $feature{'blame'}{'default'} = [1];
108         # To have project specific config enable override in $GITWEB_CONFIG
109         # $feature{'blame'}{'override'} = 1;
110         # and in project config gitweb.blame = 0|1;
111         'blame' => {
112                 'sub' => \&feature_blame,
113                 'override' => 0,
114                 'default' => [0]},
116         # Enable the 'snapshot' link, providing a compressed tarball of any
117         # tree. This can potentially generate high traffic if you have large
118         # project.
120         # To disable system wide have in $GITWEB_CONFIG
121         # $feature{'snapshot'}{'default'} = [undef];
122         # To have project specific config enable override in $GITWEB_CONFIG
123         # $feature{'snapshot'}{'override'} = 1;
124         # and in project config gitweb.snapshot = none|gzip|bzip2;
125         'snapshot' => {
126                 'sub' => \&feature_snapshot,
127                 'override' => 0,
128                 #         => [content-encoding, suffix, program]
129                 'default' => ['x-gzip', 'gz', 'gzip']},
131         # Enable text search, which will list the commits which match author,
132         # committer or commit text to a given string.  Enabled by default.
133         'search' => {
134                 'override' => 0,
135                 'default' => [1]},
137         # Enable the pickaxe search, which will list the commits that modified
138         # a given string in a file. This can be practical and quite faster
139         # alternative to 'blame', but still potentially CPU-intensive.
141         # To enable system wide have in $GITWEB_CONFIG
142         # $feature{'pickaxe'}{'default'} = [1];
143         # To have project specific config enable override in $GITWEB_CONFIG
144         # $feature{'pickaxe'}{'override'} = 1;
145         # and in project config gitweb.pickaxe = 0|1;
146         'pickaxe' => {
147                 'sub' => \&feature_pickaxe,
148                 'override' => 0,
149                 'default' => [1]},
151         # Make gitweb use an alternative format of the URLs which can be
152         # more readable and natural-looking: project name is embedded
153         # directly in the path and the query string contains other
154         # auxiliary information. All gitweb installations recognize
155         # URL in either format; this configures in which formats gitweb
156         # generates links.
158         # To enable system wide have in $GITWEB_CONFIG
159         # $feature{'pathinfo'}{'default'} = [1];
160         # Project specific override is not supported.
162         # Note that you will need to change the default location of CSS,
163         # favicon, logo and possibly other files to an absolute URL. Also,
164         # if gitweb.cgi serves as your indexfile, you will need to force
165         # $my_uri to contain the script name in your $GITWEB_CONFIG.
166         'pathinfo' => {
167                 'override' => 0,
168                 'default' => [0]},
170         # Make gitweb consider projects in project root subdirectories
171         # to be forks of existing projects. Given project $projname.git,
172         # projects matching $projname/*.git will not be shown in the main
173         # projects list, instead a '+' mark will be added to $projname
174         # there and a 'forks' view will be enabled for the project, listing
175         # all the forks. This feature is supported only if project list
176         # is taken from a directory, not file.
178         # To enable system wide have in $GITWEB_CONFIG
179         # $feature{'forks'}{'default'} = [1];
180         # Project specific override is not supported.
181         'forks' => {
182                 'override' => 0,
183                 'default' => [0]},
184 );
186 sub gitweb_check_feature {
187         my ($name) = @_;
188         return unless exists $feature{$name};
189         my ($sub, $override, @defaults) = (
190                 $feature{$name}{'sub'},
191                 $feature{$name}{'override'},
192                 @{$feature{$name}{'default'}});
193         if (!$override) { return @defaults; }
194         if (!defined $sub) {
195                 warn "feature $name is not overrideable";
196                 return @defaults;
197         }
198         return $sub->(@defaults);
201 sub feature_blame {
202         my ($val) = git_get_project_config('blame', '--bool');
204         if ($val eq 'true') {
205                 return 1;
206         } elsif ($val eq 'false') {
207                 return 0;
208         }
210         return $_[0];
213 sub feature_snapshot {
214         my ($ctype, $suffix, $command) = @_;
216         my ($val) = git_get_project_config('snapshot');
218         if ($val eq 'gzip') {
219                 return ('x-gzip', 'gz', 'gzip');
220         } elsif ($val eq 'bzip2') {
221                 return ('x-bzip2', 'bz2', 'bzip2');
222         } elsif ($val eq 'none') {
223                 return ();
224         }
226         return ($ctype, $suffix, $command);
229 sub gitweb_have_snapshot {
230         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
231         my $have_snapshot = (defined $ctype && defined $suffix);
233         return $have_snapshot;
236 sub feature_pickaxe {
237         my ($val) = git_get_project_config('pickaxe', '--bool');
239         if ($val eq 'true') {
240                 return (1);
241         } elsif ($val eq 'false') {
242                 return (0);
243         }
245         return ($_[0]);
248 # checking HEAD file with -e is fragile if the repository was
249 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
250 # and then pruned.
251 sub check_head_link {
252         my ($dir) = @_;
253         my $headfile = "$dir/HEAD";
254         return ((-e $headfile) ||
255                 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
258 sub check_export_ok {
259         my ($dir) = @_;
260         return (check_head_link($dir) &&
261                 (!$export_ok || -e "$dir/$export_ok"));
264 # rename detection options for git-diff and git-diff-tree
265 # - default is '-M', with the cost proportional to
266 #   (number of removed files) * (number of new files).
267 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
268 #   (number of changed files + number of removed files) * (number of new files)
269 # - even more costly is '-C', '--find-copies-harder' with cost
270 #   (number of files in the original tree) * (number of new files)
271 # - one might want to include '-B' option, e.g. '-B', '-M'
272 our @diff_opts = ('-M'); # taken from git_commit
274 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
275 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
277 # version of the core git binary
278 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
280 $projects_list ||= $projectroot;
282 # ======================================================================
283 # input validation and dispatch
284 our $action = $cgi->param('a');
285 if (defined $action) {
286         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
287                 die_error(undef, "Invalid action parameter");
288         }
291 # parameters which are pathnames
292 our $project = $cgi->param('p');
293 if (defined $project) {
294         if (!validate_pathname($project) ||
295             !(-d "$projectroot/$project") ||
296             !check_head_link("$projectroot/$project") ||
297             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
298             ($strict_export && !project_in_list($project))) {
299                 undef $project;
300                 die_error(undef, "No such project");
301         }
304 our $file_name = $cgi->param('f');
305 if (defined $file_name) {
306         if (!validate_pathname($file_name)) {
307                 die_error(undef, "Invalid file parameter");
308         }
311 our $file_parent = $cgi->param('fp');
312 if (defined $file_parent) {
313         if (!validate_pathname($file_parent)) {
314                 die_error(undef, "Invalid file parent parameter");
315         }
318 # parameters which are refnames
319 our $hash = $cgi->param('h');
320 if (defined $hash) {
321         if (!validate_refname($hash)) {
322                 die_error(undef, "Invalid hash parameter");
323         }
326 our $hash_parent = $cgi->param('hp');
327 if (defined $hash_parent) {
328         if (!validate_refname($hash_parent)) {
329                 die_error(undef, "Invalid hash parent parameter");
330         }
333 our $hash_base = $cgi->param('hb');
334 if (defined $hash_base) {
335         if (!validate_refname($hash_base)) {
336                 die_error(undef, "Invalid hash base parameter");
337         }
340 our $hash_parent_base = $cgi->param('hpb');
341 if (defined $hash_parent_base) {
342         if (!validate_refname($hash_parent_base)) {
343                 die_error(undef, "Invalid hash parent base parameter");
344         }
347 # other parameters
348 our $page = $cgi->param('pg');
349 if (defined $page) {
350         if ($page =~ m/[^0-9]/) {
351                 die_error(undef, "Invalid page parameter");
352         }
355 our $searchtext = $cgi->param('s');
356 if (defined $searchtext) {
357         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
358                 die_error(undef, "Invalid search parameter");
359         }
360         if (length($searchtext) < 2) {
361                 die_error(undef, "At least two characters are required for search parameter");
362         }
363         $searchtext = quotemeta $searchtext;
366 our $searchtype = $cgi->param('st');
367 if (defined $searchtype) {
368         if ($searchtype =~ m/[^a-z]/) {
369                 die_error(undef, "Invalid searchtype parameter");
370         }
373 # now read PATH_INFO and use it as alternative to parameters
374 sub evaluate_path_info {
375         return if defined $project;
376         my $path_info = $ENV{"PATH_INFO"};
377         return if !$path_info;
378         $path_info =~ s,^/+,,;
379         return if !$path_info;
380         # find which part of PATH_INFO is project
381         $project = $path_info;
382         $project =~ s,/+$,,;
383         while ($project && !check_head_link("$projectroot/$project")) {
384                 $project =~ s,/*[^/]*$,,;
385         }
386         # validate project
387         $project = validate_pathname($project);
388         if (!$project ||
389             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
390             ($strict_export && !project_in_list($project))) {
391                 undef $project;
392                 return;
393         }
394         # do not change any parameters if an action is given using the query string
395         return if $action;
396         $path_info =~ s,^$project/*,,;
397         my ($refname, $pathname) = split(/:/, $path_info, 2);
398         if (defined $pathname) {
399                 # we got "project.git/branch:filename" or "project.git/branch:dir/"
400                 # we could use git_get_type(branch:pathname), but it needs $git_dir
401                 $pathname =~ s,^/+,,;
402                 if (!$pathname || substr($pathname, -1) eq "/") {
403                         $action  ||= "tree";
404                         $pathname =~ s,/$,,;
405                 } else {
406                         $action  ||= "blob_plain";
407                 }
408                 $hash_base ||= validate_refname($refname);
409                 $file_name ||= validate_pathname($pathname);
410         } elsif (defined $refname) {
411                 # we got "project.git/branch"
412                 $action ||= "shortlog";
413                 $hash   ||= validate_refname($refname);
414         }
416 evaluate_path_info();
418 # path to the current git repository
419 our $git_dir;
420 $git_dir = "$projectroot/$project" if $project;
422 # dispatch
423 my %actions = (
424         "blame" => \&git_blame2,
425         "blobdiff" => \&git_blobdiff,
426         "blobdiff_plain" => \&git_blobdiff_plain,
427         "blob" => \&git_blob,
428         "blob_plain" => \&git_blob_plain,
429         "commitdiff" => \&git_commitdiff,
430         "commitdiff_plain" => \&git_commitdiff_plain,
431         "commit" => \&git_commit,
432         "forks" => \&git_forks,
433         "heads" => \&git_heads,
434         "history" => \&git_history,
435         "log" => \&git_log,
436         "rss" => \&git_rss,
437         "atom" => \&git_atom,
438         "search" => \&git_search,
439         "search_help" => \&git_search_help,
440         "shortlog" => \&git_shortlog,
441         "summary" => \&git_summary,
442         "tag" => \&git_tag,
443         "tags" => \&git_tags,
444         "tree" => \&git_tree,
445         "snapshot" => \&git_snapshot,
446         "object" => \&git_object,
447         # those below don't need $project
448         "opml" => \&git_opml,
449         "project_list" => \&git_project_list,
450         "project_index" => \&git_project_index,
451 );
453 if (defined $project) {
454         $action ||= 'summary';
455 } else {
456         $action ||= 'project_list';
458 if (!defined($actions{$action})) {
459         die_error(undef, "Unknown action");
461 if ($action !~ m/^(opml|project_list|project_index)$/ &&
462     !$project) {
463         die_error(undef, "Project needed");
465 $actions{$action}->();
466 exit;
468 ## ======================================================================
469 ## action links
471 sub href(%) {
472         my %params = @_;
473         # default is to use -absolute url() i.e. $my_uri
474         my $href = $params{-full} ? $my_url : $my_uri;
476         # XXX: Warning: If you touch this, check the search form for updating,
477         # too.
479         my @mapping = (
480                 project => "p",
481                 action => "a",
482                 file_name => "f",
483                 file_parent => "fp",
484                 hash => "h",
485                 hash_parent => "hp",
486                 hash_base => "hb",
487                 hash_parent_base => "hpb",
488                 page => "pg",
489                 order => "o",
490                 searchtext => "s",
491                 searchtype => "st",
492         );
493         my %mapping = @mapping;
495         $params{'project'} = $project unless exists $params{'project'};
497         my ($use_pathinfo) = gitweb_check_feature('pathinfo');
498         if ($use_pathinfo) {
499                 # use PATH_INFO for project name
500                 $href .= "/$params{'project'}" if defined $params{'project'};
501                 delete $params{'project'};
503                 # Summary just uses the project path URL
504                 if (defined $params{'action'} && $params{'action'} eq 'summary') {
505                         delete $params{'action'};
506                 }
507         }
509         # now encode the parameters explicitly
510         my @result = ();
511         for (my $i = 0; $i < @mapping; $i += 2) {
512                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
513                 if (defined $params{$name}) {
514                         push @result, $symbol . "=" . esc_param($params{$name});
515                 }
516         }
517         $href .= "?" . join(';', @result) if scalar @result;
519         return $href;
523 ## ======================================================================
524 ## validation, quoting/unquoting and escaping
526 sub validate_pathname {
527         my $input = shift || return undef;
529         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
530         # at the beginning, at the end, and between slashes.
531         # also this catches doubled slashes
532         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
533                 return undef;
534         }
535         # no null characters
536         if ($input =~ m!\0!) {
537                 return undef;
538         }
539         return $input;
542 sub validate_refname {
543         my $input = shift || return undef;
545         # textual hashes are O.K.
546         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
547                 return $input;
548         }
549         # it must be correct pathname
550         $input = validate_pathname($input)
551                 or return undef;
552         # restrictions on ref name according to git-check-ref-format
553         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
554                 return undef;
555         }
556         return $input;
559 # very thin wrapper for decode("utf8", $str, Encode::FB_DEFAULT);
560 sub to_utf8 {
561         my $str = shift;
562         return decode("utf8", $str, Encode::FB_DEFAULT);
565 # quote unsafe chars, but keep the slash, even when it's not
566 # correct, but quoted slashes look too horrible in bookmarks
567 sub esc_param {
568         my $str = shift;
569         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
570         $str =~ s/\+/%2B/g;
571         $str =~ s/ /\+/g;
572         return $str;
575 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
576 sub esc_url {
577         my $str = shift;
578         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
579         $str =~ s/\+/%2B/g;
580         $str =~ s/ /\+/g;
581         return $str;
584 # replace invalid utf8 character with SUBSTITUTION sequence
585 sub esc_html ($;%) {
586         my $str = shift;
587         my %opts = @_;
589         $str = to_utf8($str);
590         $str = escapeHTML($str);
591         if ($opts{'-nbsp'}) {
592                 $str =~ s/ /&nbsp;/g;
593         }
594         $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
595         return $str;
598 # quote control characters and escape filename to HTML
599 sub esc_path {
600         my $str = shift;
601         my %opts = @_;
603         $str = to_utf8($str);
604         $str = escapeHTML($str);
605         if ($opts{'-nbsp'}) {
606                 $str =~ s/ /&nbsp;/g;
607         }
608         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
609         return $str;
612 # Make control characters "printable", using character escape codes (CEC)
613 sub quot_cec {
614         my $cntrl = shift;
615         my %es = ( # character escape codes, aka escape sequences
616                    "\t" => '\t',   # tab            (HT)
617                    "\n" => '\n',   # line feed      (LF)
618                    "\r" => '\r',   # carrige return (CR)
619                    "\f" => '\f',   # form feed      (FF)
620                    "\b" => '\b',   # backspace      (BS)
621                    "\a" => '\a',   # alarm (bell)   (BEL)
622                    "\e" => '\e',   # escape         (ESC)
623                    "\013" => '\v', # vertical tab   (VT)
624                    "\000" => '\0', # nul character  (NUL)
625                    );
626         my $chr = ( (exists $es{$cntrl})
627                     ? $es{$cntrl}
628                     : sprintf('\%03o', ord($cntrl)) );
629         return "<span class=\"cntrl\">$chr</span>";
632 # Alternatively use unicode control pictures codepoints,
633 # Unicode "printable representation" (PR)
634 sub quot_upr {
635         my $cntrl = shift;
636         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
637         return "<span class=\"cntrl\">$chr</span>";
640 # git may return quoted and escaped filenames
641 sub unquote {
642         my $str = shift;
644         sub unq {
645                 my $seq = shift;
646                 my %es = ( # character escape codes, aka escape sequences
647                         't' => "\t",   # tab            (HT, TAB)
648                         'n' => "\n",   # newline        (NL)
649                         'r' => "\r",   # return         (CR)
650                         'f' => "\f",   # form feed      (FF)
651                         'b' => "\b",   # backspace      (BS)
652                         'a' => "\a",   # alarm (bell)   (BEL)
653                         'e' => "\e",   # escape         (ESC)
654                         'v' => "\013", # vertical tab   (VT)
655                 );
657                 if ($seq =~ m/^[0-7]{1,3}$/) {
658                         # octal char sequence
659                         return chr(oct($seq));
660                 } elsif (exists $es{$seq}) {
661                         # C escape sequence, aka character escape code
662                         return $es{$seq}
663                 }
664                 # quoted ordinary character
665                 return $seq;
666         }
668         if ($str =~ m/^"(.*)"$/) {
669                 # needs unquoting
670                 $str = $1;
671                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
672         }
673         return $str;
676 # escape tabs (convert tabs to spaces)
677 sub untabify {
678         my $line = shift;
680         while ((my $pos = index($line, "\t")) != -1) {
681                 if (my $count = (8 - ($pos % 8))) {
682                         my $spaces = ' ' x $count;
683                         $line =~ s/\t/$spaces/;
684                 }
685         }
687         return $line;
690 sub project_in_list {
691         my $project = shift;
692         my @list = git_get_projects_list();
693         return @list && scalar(grep { $_->{'path'} eq $project } @list);
696 ## ----------------------------------------------------------------------
697 ## HTML aware string manipulation
699 sub chop_str {
700         my $str = shift;
701         my $len = shift;
702         my $add_len = shift || 10;
704         # allow only $len chars, but don't cut a word if it would fit in $add_len
705         # if it doesn't fit, cut it if it's still longer than the dots we would add
706         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
707         my $body = $1;
708         my $tail = $2;
709         if (length($tail) > 4) {
710                 $tail = " ...";
711                 $body =~ s/&[^;]*$//; # remove chopped character entities
712         }
713         return "$body$tail";
716 ## ----------------------------------------------------------------------
717 ## functions returning short strings
719 # CSS class for given age value (in seconds)
720 sub age_class {
721         my $age = shift;
723         if ($age < 60*60*2) {
724                 return "age0";
725         } elsif ($age < 60*60*24*2) {
726                 return "age1";
727         } else {
728                 return "age2";
729         }
732 # convert age in seconds to "nn units ago" string
733 sub age_string {
734         my $age = shift;
735         my $age_str;
737         if ($age > 60*60*24*365*2) {
738                 $age_str = (int $age/60/60/24/365);
739                 $age_str .= " years ago";
740         } elsif ($age > 60*60*24*(365/12)*2) {
741                 $age_str = int $age/60/60/24/(365/12);
742                 $age_str .= " months ago";
743         } elsif ($age > 60*60*24*7*2) {
744                 $age_str = int $age/60/60/24/7;
745                 $age_str .= " weeks ago";
746         } elsif ($age > 60*60*24*2) {
747                 $age_str = int $age/60/60/24;
748                 $age_str .= " days ago";
749         } elsif ($age > 60*60*2) {
750                 $age_str = int $age/60/60;
751                 $age_str .= " hours ago";
752         } elsif ($age > 60*2) {
753                 $age_str = int $age/60;
754                 $age_str .= " min ago";
755         } elsif ($age > 2) {
756                 $age_str = int $age;
757                 $age_str .= " sec ago";
758         } else {
759                 $age_str .= " right now";
760         }
761         return $age_str;
764 # convert file mode in octal to symbolic file mode string
765 sub mode_str {
766         my $mode = oct shift;
768         if (S_ISDIR($mode & S_IFMT)) {
769                 return 'drwxr-xr-x';
770         } elsif (S_ISLNK($mode)) {
771                 return 'lrwxrwxrwx';
772         } elsif (S_ISREG($mode)) {
773                 # git cares only about the executable bit
774                 if ($mode & S_IXUSR) {
775                         return '-rwxr-xr-x';
776                 } else {
777                         return '-rw-r--r--';
778                 };
779         } else {
780                 return '----------';
781         }
784 # convert file mode in octal to file type string
785 sub file_type {
786         my $mode = shift;
788         if ($mode !~ m/^[0-7]+$/) {
789                 return $mode;
790         } else {
791                 $mode = oct $mode;
792         }
794         if (S_ISDIR($mode & S_IFMT)) {
795                 return "directory";
796         } elsif (S_ISLNK($mode)) {
797                 return "symlink";
798         } elsif (S_ISREG($mode)) {
799                 return "file";
800         } else {
801                 return "unknown";
802         }
805 # convert file mode in octal to file type description string
806 sub file_type_long {
807         my $mode = shift;
809         if ($mode !~ m/^[0-7]+$/) {
810                 return $mode;
811         } else {
812                 $mode = oct $mode;
813         }
815         if (S_ISDIR($mode & S_IFMT)) {
816                 return "directory";
817         } elsif (S_ISLNK($mode)) {
818                 return "symlink";
819         } elsif (S_ISREG($mode)) {
820                 if ($mode & S_IXUSR) {
821                         return "executable";
822                 } else {
823                         return "file";
824                 };
825         } else {
826                 return "unknown";
827         }
831 ## ----------------------------------------------------------------------
832 ## functions returning short HTML fragments, or transforming HTML fragments
833 ## which don't beling to other sections
835 # format line of commit message.
836 sub format_log_line_html {
837         my $line = shift;
839         $line = esc_html($line, -nbsp=>1);
840         if ($line =~ m/([0-9a-fA-F]{8,40})/) {
841                 my $hash_text = $1;
842                 my $link =
843                         $cgi->a({-href => href(action=>"object", hash=>$hash_text),
844                                 -class => "text"}, $hash_text);
845                 $line =~ s/$hash_text/$link/;
846         }
847         return $line;
850 # format marker of refs pointing to given object
851 sub format_ref_marker {
852         my ($refs, $id) = @_;
853         my $markers = '';
855         if (defined $refs->{$id}) {
856                 foreach my $ref (@{$refs->{$id}}) {
857                         my ($type, $name) = qw();
858                         # e.g. tags/v2.6.11 or heads/next
859                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
860                                 $type = $1;
861                                 $name = $2;
862                         } else {
863                                 $type = "ref";
864                                 $name = $ref;
865                         }
867                         $markers .= " <span class=\"$type\" title=\"$ref\">" .
868                                     esc_html($name) . "</span>";
869                 }
870         }
872         if ($markers) {
873                 return ' <span class="refs">'. $markers . '</span>';
874         } else {
875                 return "";
876         }
879 # format, perhaps shortened and with markers, title line
880 sub format_subject_html {
881         my ($long, $short, $href, $extra) = @_;
882         $extra = '' unless defined($extra);
884         if (length($short) < length($long)) {
885                 return $cgi->a({-href => $href, -class => "list subject",
886                                 -title => to_utf8($long)},
887                        esc_html($short) . $extra);
888         } else {
889                 return $cgi->a({-href => $href, -class => "list subject"},
890                        esc_html($long)  . $extra);
891         }
894 # format patch (diff) line (rather not to be used for diff headers)
895 sub format_diff_line {
896         my $line = shift;
897         my ($from, $to) = @_;
898         my $char = substr($line, 0, 1);
899         my $diff_class = "";
901         chomp $line;
903         if ($char eq '+') {
904                 $diff_class = " add";
905         } elsif ($char eq "-") {
906                 $diff_class = " rem";
907         } elsif ($char eq "@") {
908                 $diff_class = " chunk_header";
909         } elsif ($char eq "\\") {
910                 $diff_class = " incomplete";
911         }
912         $line = untabify($line);
913         if ($from && $to && $line =~ m/^\@{2} /) {
914                 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
915                         $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
917                 $from_lines = 0 unless defined $from_lines;
918                 $to_lines   = 0 unless defined $to_lines;
920                 if ($from->{'href'}) {
921                         $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
922                                              -class=>"list"}, $from_text);
923                 }
924                 if ($to->{'href'}) {
925                         $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
926                                              -class=>"list"}, $to_text);
927                 }
928                 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
929                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
930                 return "<div class=\"diff$diff_class\">$line</div>\n";
931         }
932         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
935 ## ----------------------------------------------------------------------
936 ## git utility subroutines, invoking git commands
938 # returns path to the core git executable and the --git-dir parameter as list
939 sub git_cmd {
940         return $GIT, '--git-dir='.$git_dir;
943 # returns path to the core git executable and the --git-dir parameter as string
944 sub git_cmd_str {
945         return join(' ', git_cmd());
948 # get HEAD ref of given project as hash
949 sub git_get_head_hash {
950         my $project = shift;
951         my $o_git_dir = $git_dir;
952         my $retval = undef;
953         $git_dir = "$projectroot/$project";
954         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
955                 my $head = <$fd>;
956                 close $fd;
957                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
958                         $retval = $1;
959                 }
960         }
961         if (defined $o_git_dir) {
962                 $git_dir = $o_git_dir;
963         }
964         return $retval;
967 # get type of given object
968 sub git_get_type {
969         my $hash = shift;
971         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
972         my $type = <$fd>;
973         close $fd or return;
974         chomp $type;
975         return $type;
978 sub git_get_project_config {
979         my ($key, $type) = @_;
981         return unless ($key);
982         $key =~ s/^gitweb\.//;
983         return if ($key =~ m/\W/);
985         my @x = (git_cmd(), 'repo-config');
986         if (defined $type) { push @x, $type; }
987         push @x, "--get";
988         push @x, "gitweb.$key";
989         my $val = qx(@x);
990         chomp $val;
991         return ($val);
994 # get hash of given path at given ref
995 sub git_get_hash_by_path {
996         my $base = shift;
997         my $path = shift || return undef;
998         my $type = shift;
1000         $path =~ s,/+$,,;
1002         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1003                 or die_error(undef, "Open git-ls-tree failed");
1004         my $line = <$fd>;
1005         close $fd or return undef;
1007         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1008         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1009         if (defined $type && $type ne $2) {
1010                 # type doesn't match
1011                 return undef;
1012         }
1013         return $3;
1016 ## ......................................................................
1017 ## git utility functions, directly accessing git repository
1019 sub git_get_project_description {
1020         my $path = shift;
1022         open my $fd, "$projectroot/$path/description" or return undef;
1023         my $descr = <$fd>;
1024         close $fd;
1025         chomp $descr;
1026         return $descr;
1029 sub git_get_project_url_list {
1030         my $path = shift;
1032         open my $fd, "$projectroot/$path/cloneurl" or return;
1033         my @git_project_url_list = map { chomp; $_ } <$fd>;
1034         close $fd;
1036         return wantarray ? @git_project_url_list : \@git_project_url_list;
1039 sub git_get_projects_list {
1040         my ($filter) = @_;
1041         my @list;
1043         $filter ||= '';
1044         $filter =~ s/\.git$//;
1046         if (-d $projects_list) {
1047                 # search in directory
1048                 my $dir = $projects_list . ($filter ? "/$filter" : '');
1049                 # remove the trailing "/"
1050                 $dir =~ s!/+$!!;
1051                 my $pfxlen = length("$dir");
1053                 my ($check_forks) = gitweb_check_feature('forks');
1055                 File::Find::find({
1056                         follow_fast => 1, # follow symbolic links
1057                         dangling_symlinks => 0, # ignore dangling symlinks, silently
1058                         wanted => sub {
1059                                 # skip project-list toplevel, if we get it.
1060                                 return if (m!^[/.]$!);
1061                                 # only directories can be git repositories
1062                                 return unless (-d $_);
1064                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
1065                                 # we check related file in $projectroot
1066                                 if ($check_forks and $subdir =~ m#/.#) {
1067                                         $File::Find::prune = 1;
1068                                 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1069                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1070                                         $File::Find::prune = 1;
1071                                 }
1072                         },
1073                 }, "$dir");
1075         } elsif (-f $projects_list) {
1076                 # read from file(url-encoded):
1077                 # 'git%2Fgit.git Linus+Torvalds'
1078                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1079                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1080                 open my ($fd), $projects_list or return;
1081                 while (my $line = <$fd>) {
1082                         chomp $line;
1083                         my ($path, $owner) = split ' ', $line;
1084                         $path = unescape($path);
1085                         $owner = unescape($owner);
1086                         if (!defined $path) {
1087                                 next;
1088                         }
1089                         if ($filter ne '') {
1090                                 # looking for forks;
1091                                 my $pfx = substr($path, 0, length($filter));
1092                                 if ($pfx ne $filter) {
1093                                         next;
1094                                 }
1095                                 my $sfx = substr($path, length($filter));
1096                                 if ($sfx !~ /^\/.*\.git$/) {
1097                                         next;
1098                                 }
1099                         }
1100                         if (check_export_ok("$projectroot/$path")) {
1101                                 my $pr = {
1102                                         path => $path,
1103                                         owner => to_utf8($owner),
1104                                 };
1105                                 push @list, $pr
1106                         }
1107                 }
1108                 close $fd;
1109         }
1110         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
1111         return @list;
1114 sub git_get_project_owner {
1115         my $project = shift;
1116         my $owner;
1118         return undef unless $project;
1120         # read from file (url-encoded):
1121         # 'git%2Fgit.git Linus+Torvalds'
1122         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1123         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1124         if (-f $projects_list) {
1125                 open (my $fd , $projects_list);
1126                 while (my $line = <$fd>) {
1127                         chomp $line;
1128                         my ($pr, $ow) = split ' ', $line;
1129                         $pr = unescape($pr);
1130                         $ow = unescape($ow);
1131                         if ($pr eq $project) {
1132                                 $owner = to_utf8($ow);
1133                                 last;
1134                         }
1135                 }
1136                 close $fd;
1137         }
1138         if (!defined $owner) {
1139                 $owner = get_file_owner("$projectroot/$project");
1140         }
1142         return $owner;
1145 sub git_get_last_activity {
1146         my ($path) = @_;
1147         my $fd;
1149         $git_dir = "$projectroot/$path";
1150         open($fd, "-|", git_cmd(), 'for-each-ref',
1151              '--format=%(committer)',
1152              '--sort=-committerdate',
1153              '--count=1',
1154              'refs/heads') or return;
1155         my $most_recent = <$fd>;
1156         close $fd or return;
1157         if ($most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1158                 my $timestamp = $1;
1159                 my $age = time - $timestamp;
1160                 return ($age, age_string($age));
1161         }
1164 sub git_get_references {
1165         my $type = shift || "";
1166         my %refs;
1167         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1168         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1169         open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1170                 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1171                 or return;
1173         while (my $line = <$fd>) {
1174                 chomp $line;
1175                 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1176                         if (defined $refs{$1}) {
1177                                 push @{$refs{$1}}, $2;
1178                         } else {
1179                                 $refs{$1} = [ $2 ];
1180                         }
1181                 }
1182         }
1183         close $fd or return;
1184         return \%refs;
1187 sub git_get_rev_name_tags {
1188         my $hash = shift || return undef;
1190         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1191                 or return;
1192         my $name_rev = <$fd>;
1193         close $fd;
1195         if ($name_rev =~ m|^$hash tags/(.*)$|) {
1196                 return $1;
1197         } else {
1198                 # catches also '$hash undefined' output
1199                 return undef;
1200         }
1203 ## ----------------------------------------------------------------------
1204 ## parse to hash functions
1206 sub parse_date {
1207         my $epoch = shift;
1208         my $tz = shift || "-0000";
1210         my %date;
1211         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1212         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1213         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1214         $date{'hour'} = $hour;
1215         $date{'minute'} = $min;
1216         $date{'mday'} = $mday;
1217         $date{'day'} = $days[$wday];
1218         $date{'month'} = $months[$mon];
1219         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1220                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1221         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1222                              $mday, $months[$mon], $hour ,$min;
1223         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1224                              1900+$year, $mon, $mday, $hour ,$min, $sec;
1226         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1227         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1228         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1229         $date{'hour_local'} = $hour;
1230         $date{'minute_local'} = $min;
1231         $date{'tz_local'} = $tz;
1232         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1233                                   1900+$year, $mon+1, $mday,
1234                                   $hour, $min, $sec, $tz);
1235         return %date;
1238 sub parse_tag {
1239         my $tag_id = shift;
1240         my %tag;
1241         my @comment;
1243         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1244         $tag{'id'} = $tag_id;
1245         while (my $line = <$fd>) {
1246                 chomp $line;
1247                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1248                         $tag{'object'} = $1;
1249                 } elsif ($line =~ m/^type (.+)$/) {
1250                         $tag{'type'} = $1;
1251                 } elsif ($line =~ m/^tag (.+)$/) {
1252                         $tag{'name'} = $1;
1253                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1254                         $tag{'author'} = $1;
1255                         $tag{'epoch'} = $2;
1256                         $tag{'tz'} = $3;
1257                 } elsif ($line =~ m/--BEGIN/) {
1258                         push @comment, $line;
1259                         last;
1260                 } elsif ($line eq "") {
1261                         last;
1262                 }
1263         }
1264         push @comment, <$fd>;
1265         $tag{'comment'} = \@comment;
1266         close $fd or return;
1267         if (!defined $tag{'name'}) {
1268                 return
1269         };
1270         return %tag
1273 sub parse_commit {
1274         my $commit_id = shift;
1275         my $commit_text = shift;
1277         my @commit_lines;
1278         my %co;
1280         if (defined $commit_text) {
1281                 @commit_lines = @$commit_text;
1282         } else {
1283                 local $/ = "\0";
1284                 open my $fd, "-|", git_cmd(), "rev-list",
1285                         "--header", "--parents", "--max-count=1",
1286                         $commit_id, "--"
1287                         or return;
1288                 @commit_lines = split '\n', <$fd>;
1289                 close $fd or return;
1290                 pop @commit_lines;
1291         }
1292         my $header = shift @commit_lines;
1293         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1294                 return;
1295         }
1296         ($co{'id'}, my @parents) = split ' ', $header;
1297         $co{'parents'} = \@parents;
1298         $co{'parent'} = $parents[0];
1299         while (my $line = shift @commit_lines) {
1300                 last if $line eq "\n";
1301                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1302                         $co{'tree'} = $1;
1303                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1304                         $co{'author'} = $1;
1305                         $co{'author_epoch'} = $2;
1306                         $co{'author_tz'} = $3;
1307                         if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
1308                                 $co{'author_name'}  = $1;
1309                                 $co{'author_email'} = $2;
1310                         } else {
1311                                 $co{'author_name'} = $co{'author'};
1312                         }
1313                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1314                         $co{'committer'} = $1;
1315                         $co{'committer_epoch'} = $2;
1316                         $co{'committer_tz'} = $3;
1317                         $co{'committer_name'} = $co{'committer'};
1318                         if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
1319                                 $co{'committer_name'}  = $1;
1320                                 $co{'committer_email'} = $2;
1321                         } else {
1322                                 $co{'committer_name'} = $co{'committer'};
1323                         }
1324                 }
1325         }
1326         if (!defined $co{'tree'}) {
1327                 return;
1328         };
1330         foreach my $title (@commit_lines) {
1331                 $title =~ s/^    //;
1332                 if ($title ne "") {
1333                         $co{'title'} = chop_str($title, 80, 5);
1334                         # remove leading stuff of merges to make the interesting part visible
1335                         if (length($title) > 50) {
1336                                 $title =~ s/^Automatic //;
1337                                 $title =~ s/^merge (of|with) /Merge ... /i;
1338                                 if (length($title) > 50) {
1339                                         $title =~ s/(http|rsync):\/\///;
1340                                 }
1341                                 if (length($title) > 50) {
1342                                         $title =~ s/(master|www|rsync)\.//;
1343                                 }
1344                                 if (length($title) > 50) {
1345                                         $title =~ s/kernel.org:?//;
1346                                 }
1347                                 if (length($title) > 50) {
1348                                         $title =~ s/\/pub\/scm//;
1349                                 }
1350                         }
1351                         $co{'title_short'} = chop_str($title, 50, 5);
1352                         last;
1353                 }
1354         }
1355         if ($co{'title'} eq "") {
1356                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1357         }
1358         # remove added spaces
1359         foreach my $line (@commit_lines) {
1360                 $line =~ s/^    //;
1361         }
1362         $co{'comment'} = \@commit_lines;
1364         my $age = time - $co{'committer_epoch'};
1365         $co{'age'} = $age;
1366         $co{'age_string'} = age_string($age);
1367         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1368         if ($age > 60*60*24*7*2) {
1369                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1370                 $co{'age_string_age'} = $co{'age_string'};
1371         } else {
1372                 $co{'age_string_date'} = $co{'age_string'};
1373                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1374         }
1375         return %co;
1378 # parse ref from ref_file, given by ref_id, with given type
1379 sub parse_ref {
1380         my $ref_file = shift;
1381         my $ref_id = shift;
1382         my $type = shift || git_get_type($ref_id);
1383         my %ref_item;
1385         $ref_item{'type'} = $type;
1386         $ref_item{'id'} = $ref_id;
1387         $ref_item{'epoch'} = 0;
1388         $ref_item{'age'} = "unknown";
1389         if ($type eq "tag") {
1390                 my %tag = parse_tag($ref_id);
1391                 $ref_item{'comment'} = $tag{'comment'};
1392                 if ($tag{'type'} eq "commit") {
1393                         my %co = parse_commit($tag{'object'});
1394                         $ref_item{'epoch'} = $co{'committer_epoch'};
1395                         $ref_item{'age'} = $co{'age_string'};
1396                 } elsif (defined($tag{'epoch'})) {
1397                         my $age = time - $tag{'epoch'};
1398                         $ref_item{'epoch'} = $tag{'epoch'};
1399                         $ref_item{'age'} = age_string($age);
1400                 }
1401                 $ref_item{'reftype'} = $tag{'type'};
1402                 $ref_item{'name'} = $tag{'name'};
1403                 $ref_item{'refid'} = $tag{'object'};
1404         } elsif ($type eq "commit"){
1405                 my %co = parse_commit($ref_id);
1406                 $ref_item{'reftype'} = "commit";
1407                 $ref_item{'name'} = $ref_file;
1408                 $ref_item{'title'} = $co{'title'};
1409                 $ref_item{'refid'} = $ref_id;
1410                 $ref_item{'epoch'} = $co{'committer_epoch'};
1411                 $ref_item{'age'} = $co{'age_string'};
1412         } else {
1413                 $ref_item{'reftype'} = $type;
1414                 $ref_item{'name'} = $ref_file;
1415                 $ref_item{'refid'} = $ref_id;
1416         }
1418         return %ref_item;
1421 # parse line of git-diff-tree "raw" output
1422 sub parse_difftree_raw_line {
1423         my $line = shift;
1424         my %res;
1426         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1427         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1428         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1429                 $res{'from_mode'} = $1;
1430                 $res{'to_mode'} = $2;
1431                 $res{'from_id'} = $3;
1432                 $res{'to_id'} = $4;
1433                 $res{'status'} = $5;
1434                 $res{'similarity'} = $6;
1435                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1436                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1437                 } else {
1438                         $res{'file'} = unquote($7);
1439                 }
1440         }
1441         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1442         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1443                 $res{'commit'} = $1;
1444         }
1446         return wantarray ? %res : \%res;
1449 # parse line of git-ls-tree output
1450 sub parse_ls_tree_line ($;%) {
1451         my $line = shift;
1452         my %opts = @_;
1453         my %res;
1455         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1456         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1458         $res{'mode'} = $1;
1459         $res{'type'} = $2;
1460         $res{'hash'} = $3;
1461         if ($opts{'-z'}) {
1462                 $res{'name'} = $4;
1463         } else {
1464                 $res{'name'} = unquote($4);
1465         }
1467         return wantarray ? %res : \%res;
1470 ## ......................................................................
1471 ## parse to array of hashes functions
1473 sub git_get_heads_list {
1474         my $limit = shift;
1475         my @headslist;
1477         open my $fd, '-|', git_cmd(), 'for-each-ref',
1478                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1479                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1480                 'refs/heads'
1481                 or return;
1482         while (my $line = <$fd>) {
1483                 my %ref_item;
1485                 chomp $line;
1486                 my ($refinfo, $committerinfo) = split(/\0/, $line);
1487                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
1488                 my ($committer, $epoch, $tz) =
1489                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1490                 $name =~ s!^refs/heads/!!;
1492                 $ref_item{'name'}  = $name;
1493                 $ref_item{'id'}    = $hash;
1494                 $ref_item{'title'} = $title || '(no commit message)';
1495                 $ref_item{'epoch'} = $epoch;
1496                 if ($epoch) {
1497                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1498                 } else {
1499                         $ref_item{'age'} = "unknown";
1500                 }
1502                 push @headslist, \%ref_item;
1503         }
1504         close $fd;
1506         return wantarray ? @headslist : \@headslist;
1509 sub git_get_tags_list {
1510         my $limit = shift;
1511         my @tagslist;
1513         open my $fd, '-|', git_cmd(), 'for-each-ref',
1514                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1515                 '--format=%(objectname) %(objecttype) %(refname) '.
1516                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
1517                 'refs/tags'
1518                 or return;
1519         while (my $line = <$fd>) {
1520                 my %ref_item;
1522                 chomp $line;
1523                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
1524                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
1525                 my ($creator, $epoch, $tz) =
1526                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
1527                 $name =~ s!^refs/tags/!!;
1529                 $ref_item{'type'} = $type;
1530                 $ref_item{'id'} = $id;
1531                 $ref_item{'name'} = $name;
1532                 if ($type eq "tag") {
1533                         $ref_item{'subject'} = $title;
1534                         $ref_item{'reftype'} = $reftype;
1535                         $ref_item{'refid'}   = $refid;
1536                 } else {
1537                         $ref_item{'reftype'} = $type;
1538                         $ref_item{'refid'}   = $id;
1539                 }
1541                 if ($type eq "tag" || $type eq "commit") {
1542                         $ref_item{'epoch'} = $epoch;
1543                         if ($epoch) {
1544                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1545                         } else {
1546                                 $ref_item{'age'} = "unknown";
1547                         }
1548                 }
1550                 push @tagslist, \%ref_item;
1551         }
1552         close $fd;
1554         return wantarray ? @tagslist : \@tagslist;
1557 ## ----------------------------------------------------------------------
1558 ## filesystem-related functions
1560 sub get_file_owner {
1561         my $path = shift;
1563         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1564         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1565         if (!defined $gcos) {
1566                 return undef;
1567         }
1568         my $owner = $gcos;
1569         $owner =~ s/[,;].*$//;
1570         return to_utf8($owner);
1573 ## ......................................................................
1574 ## mimetype related functions
1576 sub mimetype_guess_file {
1577         my $filename = shift;
1578         my $mimemap = shift;
1579         -r $mimemap or return undef;
1581         my %mimemap;
1582         open(MIME, $mimemap) or return undef;
1583         while (<MIME>) {
1584                 next if m/^#/; # skip comments
1585                 my ($mime, $exts) = split(/\t+/);
1586                 if (defined $exts) {
1587                         my @exts = split(/\s+/, $exts);
1588                         foreach my $ext (@exts) {
1589                                 $mimemap{$ext} = $mime;
1590                         }
1591                 }
1592         }
1593         close(MIME);
1595         $filename =~ /\.([^.]*)$/;
1596         return $mimemap{$1};
1599 sub mimetype_guess {
1600         my $filename = shift;
1601         my $mime;
1602         $filename =~ /\./ or return undef;
1604         if ($mimetypes_file) {
1605                 my $file = $mimetypes_file;
1606                 if ($file !~ m!^/!) { # if it is relative path
1607                         # it is relative to project
1608                         $file = "$projectroot/$project/$file";
1609                 }
1610                 $mime = mimetype_guess_file($filename, $file);
1611         }
1612         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1613         return $mime;
1616 sub blob_mimetype {
1617         my $fd = shift;
1618         my $filename = shift;
1620         if ($filename) {
1621                 my $mime = mimetype_guess($filename);
1622                 $mime and return $mime;
1623         }
1625         # just in case
1626         return $default_blob_plain_mimetype unless $fd;
1628         if (-T $fd) {
1629                 return 'text/plain' .
1630                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1631         } elsif (! $filename) {
1632                 return 'application/octet-stream';
1633         } elsif ($filename =~ m/\.png$/i) {
1634                 return 'image/png';
1635         } elsif ($filename =~ m/\.gif$/i) {
1636                 return 'image/gif';
1637         } elsif ($filename =~ m/\.jpe?g$/i) {
1638                 return 'image/jpeg';
1639         } else {
1640                 return 'application/octet-stream';
1641         }
1644 ## ======================================================================
1645 ## functions printing HTML: header, footer, error page
1647 sub git_header_html {
1648         my $status = shift || "200 OK";
1649         my $expires = shift;
1651         my $title = "$site_name";
1652         if (defined $project) {
1653                 $title .= " - $project";
1654                 if (defined $action) {
1655                         $title .= "/$action";
1656                         if (defined $file_name) {
1657                                 $title .= " - " . esc_path($file_name);
1658                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1659                                         $title .= "/";
1660                                 }
1661                         }
1662                 }
1663         }
1664         my $content_type;
1665         # require explicit support from the UA if we are to send the page as
1666         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1667         # we have to do this because MSIE sometimes globs '*/*', pretending to
1668         # support xhtml+xml but choking when it gets what it asked for.
1669         if (defined $cgi->http('HTTP_ACCEPT') &&
1670             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1671             $cgi->Accept('application/xhtml+xml') != 0) {
1672                 $content_type = 'application/xhtml+xml';
1673         } else {
1674                 $content_type = 'text/html';
1675         }
1676         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1677                            -status=> $status, -expires => $expires);
1678         print <<EOF;
1679 <?xml version="1.0" encoding="utf-8"?>
1680 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1681 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1682 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1683 <!-- git core binaries version $git_version -->
1684 <head>
1685 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1686 <meta name="generator" content="gitweb/$version git/$git_version"/>
1687 <meta name="robots" content="index, nofollow"/>
1688 <title>$title</title>
1689 EOF
1690 # print out each stylesheet that exist
1691         if (defined $stylesheet) {
1692 #provides backwards capability for those people who define style sheet in a config file
1693                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1694         } else {
1695                 foreach my $stylesheet (@stylesheets) {
1696                         next unless $stylesheet;
1697                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1698                 }
1699         }
1700         if (defined $project) {
1701                 printf('<link rel="alternate" title="%s log RSS feed" '.
1702                        'href="%s" type="application/rss+xml" />'."\n",
1703                        esc_param($project), href(action=>"rss"));
1704                 printf('<link rel="alternate" title="%s log Atom feed" '.
1705                        'href="%s" type="application/atom+xml" />'."\n",
1706                        esc_param($project), href(action=>"atom"));
1707         } else {
1708                 printf('<link rel="alternate" title="%s projects list" '.
1709                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1710                        $site_name, href(project=>undef, action=>"project_index"));
1711                 printf('<link rel="alternate" title="%s projects feeds" '.
1712                        'href="%s" type="text/x-opml"/>'."\n",
1713                        $site_name, href(project=>undef, action=>"opml"));
1714         }
1715         if (defined $favicon) {
1716                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1717         }
1719         print "</head>\n" .
1720               "<body>\n";
1722         if (-f $site_header) {
1723                 open (my $fd, $site_header);
1724                 print <$fd>;
1725                 close $fd;
1726         }
1728         print "<div class=\"page_header\">\n" .
1729               $cgi->a({-href => esc_url($logo_url),
1730                        -title => $logo_label},
1731                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1732         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1733         if (defined $project) {
1734                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1735                 if (defined $action) {
1736                         print " / $action";
1737                 }
1738                 print "\n";
1739         }
1740         my ($have_search) = gitweb_check_feature('search');
1741         if ((defined $project) && ($have_search)) {
1742                 if (!defined $searchtext) {
1743                         $searchtext = "";
1744                 }
1745                 my $search_hash;
1746                 if (defined $hash_base) {
1747                         $search_hash = $hash_base;
1748                 } elsif (defined $hash) {
1749                         $search_hash = $hash;
1750                 } else {
1751                         $search_hash = "HEAD";
1752                 }
1753                 $cgi->param("a", "search");
1754                 $cgi->param("h", $search_hash);
1755                 $cgi->param("p", $project);
1756                 print $cgi->startform(-method => "get", -action => $my_uri) .
1757                       "<div class=\"search\">\n" .
1758                       $cgi->hidden(-name => "p") . "\n" .
1759                       $cgi->hidden(-name => "a") . "\n" .
1760                       $cgi->hidden(-name => "h") . "\n" .
1761                       $cgi->popup_menu(-name => 'st', -default => 'commit',
1762                                        -values => ['commit', 'author', 'committer', 'pickaxe']) .
1763                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
1764                       " search:\n",
1765                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1766                       "</div>" .
1767                       $cgi->end_form() . "\n";
1768         }
1769         print "</div>\n";
1772 sub git_footer_html {
1773         print "<div class=\"page_footer\">\n";
1774         if (defined $project) {
1775                 my $descr = git_get_project_description($project);
1776                 if (defined $descr) {
1777                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1778                 }
1779                 print $cgi->a({-href => href(action=>"rss"),
1780                               -class => "rss_logo"}, "RSS") . " ";
1781                 print $cgi->a({-href => href(action=>"atom"),
1782                               -class => "rss_logo"}, "Atom") . "\n";
1783         } else {
1784                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1785                               -class => "rss_logo"}, "OPML") . " ";
1786                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1787                               -class => "rss_logo"}, "TXT") . "\n";
1788         }
1789         print "</div>\n" ;
1791         if (-f $site_footer) {
1792                 open (my $fd, $site_footer);
1793                 print <$fd>;
1794                 close $fd;
1795         }
1797         print "</body>\n" .
1798               "</html>";
1801 sub die_error {
1802         my $status = shift || "403 Forbidden";
1803         my $error = shift || "Malformed query, file missing or permission denied";
1805         git_header_html($status);
1806         print <<EOF;
1807 <div class="page_body">
1808 <br /><br />
1809 $status - $error
1810 <br />
1811 </div>
1812 EOF
1813         git_footer_html();
1814         exit;
1817 ## ----------------------------------------------------------------------
1818 ## functions printing or outputting HTML: navigation
1820 sub git_print_page_nav {
1821         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1822         $extra = '' if !defined $extra; # pager or formats
1824         my @navs = qw(summary shortlog log commit commitdiff tree);
1825         if ($suppress) {
1826                 @navs = grep { $_ ne $suppress } @navs;
1827         }
1829         my %arg = map { $_ => {action=>$_} } @navs;
1830         if (defined $head) {
1831                 for (qw(commit commitdiff)) {
1832                         $arg{$_}{hash} = $head;
1833                 }
1834                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1835                         for (qw(shortlog log)) {
1836                                 $arg{$_}{hash} = $head;
1837                         }
1838                 }
1839         }
1840         $arg{tree}{hash} = $treehead if defined $treehead;
1841         $arg{tree}{hash_base} = $treebase if defined $treebase;
1843         print "<div class=\"page_nav\">\n" .
1844                 (join " | ",
1845                  map { $_ eq $current ?
1846                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1847                  } @navs);
1848         print "<br/>\n$extra<br/>\n" .
1849               "</div>\n";
1852 sub format_paging_nav {
1853         my ($action, $hash, $head, $page, $nrevs) = @_;
1854         my $paging_nav;
1857         if ($hash ne $head || $page) {
1858                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1859         } else {
1860                 $paging_nav .= "HEAD";
1861         }
1863         if ($page > 0) {
1864                 $paging_nav .= " &sdot; " .
1865                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1866                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1867         } else {
1868                 $paging_nav .= " &sdot; prev";
1869         }
1871         if ($nrevs >= (100 * ($page+1)-1)) {
1872                 $paging_nav .= " &sdot; " .
1873                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1874                                  -accesskey => "n", -title => "Alt-n"}, "next");
1875         } else {
1876                 $paging_nav .= " &sdot; next";
1877         }
1879         return $paging_nav;
1882 ## ......................................................................
1883 ## functions printing or outputting HTML: div
1885 sub git_print_header_div {
1886         my ($action, $title, $hash, $hash_base) = @_;
1887         my %args = ();
1889         $args{action} = $action;
1890         $args{hash} = $hash if $hash;
1891         $args{hash_base} = $hash_base if $hash_base;
1893         print "<div class=\"header\">\n" .
1894               $cgi->a({-href => href(%args), -class => "title"},
1895               $title ? $title : $action) .
1896               "\n</div>\n";
1899 #sub git_print_authorship (\%) {
1900 sub git_print_authorship {
1901         my $co = shift;
1903         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1904         print "<div class=\"author_date\">" .
1905               esc_html($co->{'author_name'}) .
1906               " [$ad{'rfc2822'}";
1907         if ($ad{'hour_local'} < 6) {
1908                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1909                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1910         } else {
1911                 printf(" (%02d:%02d %s)",
1912                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1913         }
1914         print "]</div>\n";
1917 sub git_print_page_path {
1918         my $name = shift;
1919         my $type = shift;
1920         my $hb = shift;
1923         print "<div class=\"page_path\">";
1924         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1925                       -title => 'tree root'}, "[$project]");
1926         print " / ";
1927         if (defined $name) {
1928                 my @dirname = split '/', $name;
1929                 my $basename = pop @dirname;
1930                 my $fullname = '';
1932                 foreach my $dir (@dirname) {
1933                         $fullname .= ($fullname ? '/' : '') . $dir;
1934                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1935                                                      hash_base=>$hb),
1936                                       -title => esc_html($fullname)}, esc_path($dir));
1937                         print " / ";
1938                 }
1939                 if (defined $type && $type eq 'blob') {
1940                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1941                                                      hash_base=>$hb),
1942                                       -title => esc_html($name)}, esc_path($basename));
1943                 } elsif (defined $type && $type eq 'tree') {
1944                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1945                                                      hash_base=>$hb),
1946                                       -title => esc_html($name)}, esc_path($basename));
1947                         print " / ";
1948                 } else {
1949                         print esc_path($basename);
1950                 }
1951         }
1952         print "<br/></div>\n";
1955 # sub git_print_log (\@;%) {
1956 sub git_print_log ($;%) {
1957         my $log = shift;
1958         my %opts = @_;
1960         if ($opts{'-remove_title'}) {
1961                 # remove title, i.e. first line of log
1962                 shift @$log;
1963         }
1964         # remove leading empty lines
1965         while (defined $log->[0] && $log->[0] eq "") {
1966                 shift @$log;
1967         }
1969         # print log
1970         my $signoff = 0;
1971         my $empty = 0;
1972         foreach my $line (@$log) {
1973                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1974                         $signoff = 1;
1975                         $empty = 0;
1976                         if (! $opts{'-remove_signoff'}) {
1977                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1978                                 next;
1979                         } else {
1980                                 # remove signoff lines
1981                                 next;
1982                         }
1983                 } else {
1984                         $signoff = 0;
1985                 }
1987                 # print only one empty line
1988                 # do not print empty line after signoff
1989                 if ($line eq "") {
1990                         next if ($empty || $signoff);
1991                         $empty = 1;
1992                 } else {
1993                         $empty = 0;
1994                 }
1996                 print format_log_line_html($line) . "<br/>\n";
1997         }
1999         if ($opts{'-final_empty_line'}) {
2000                 # end with single empty line
2001                 print "<br/>\n" unless $empty;
2002         }
2005 # return link target (what link points to)
2006 sub git_get_link_target {
2007         my $hash = shift;
2008         my $link_target;
2010         # read link
2011         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2012                 or return;
2013         {
2014                 local $/;
2015                 $link_target = <$fd>;
2016         }
2017         close $fd
2018                 or return;
2020         return $link_target;
2023 # given link target, and the directory (basedir) the link is in,
2024 # return target of link relative to top directory (top tree);
2025 # return undef if it is not possible (including absolute links).
2026 sub normalize_link_target {
2027         my ($link_target, $basedir, $hash_base) = @_;
2029         # we can normalize symlink target only if $hash_base is provided
2030         return unless $hash_base;
2032         # absolute symlinks (beginning with '/') cannot be normalized
2033         return if (substr($link_target, 0, 1) eq '/');
2035         # normalize link target to path from top (root) tree (dir)
2036         my $path;
2037         if ($basedir) {
2038                 $path = $basedir . '/' . $link_target;
2039         } else {
2040                 # we are in top (root) tree (dir)
2041                 $path = $link_target;
2042         }
2044         # remove //, /./, and /../
2045         my @path_parts;
2046         foreach my $part (split('/', $path)) {
2047                 # discard '.' and ''
2048                 next if (!$part || $part eq '.');
2049                 # handle '..'
2050                 if ($part eq '..') {
2051                         if (@path_parts) {
2052                                 pop @path_parts;
2053                         } else {
2054                                 # link leads outside repository (outside top dir)
2055                                 return;
2056                         }
2057                 } else {
2058                         push @path_parts, $part;
2059                 }
2060         }
2061         $path = join('/', @path_parts);
2063         return $path;
2066 # print tree entry (row of git_tree), but without encompassing <tr> element
2067 sub git_print_tree_entry {
2068         my ($t, $basedir, $hash_base, $have_blame) = @_;
2070         my %base_key = ();
2071         $base_key{'hash_base'} = $hash_base if defined $hash_base;
2073         # The format of a table row is: mode list link.  Where mode is
2074         # the mode of the entry, list is the name of the entry, an href,
2075         # and link is the action links of the entry.
2077         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2078         if ($t->{'type'} eq "blob") {
2079                 print "<td class=\"list\">" .
2080                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2081                                                file_name=>"$basedir$t->{'name'}", %base_key),
2082                                 -class => "list"}, esc_path($t->{'name'}));
2083                 if (S_ISLNK(oct $t->{'mode'})) {
2084                         my $link_target = git_get_link_target($t->{'hash'});
2085                         if ($link_target) {
2086                                 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2087                                 if (defined $norm_target) {
2088                                         print " -> " .
2089                                               $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2090                                                                      file_name=>$norm_target),
2091                                                        -title => $norm_target}, esc_path($link_target));
2092                                 } else {
2093                                         print " -> " . esc_path($link_target);
2094                                 }
2095                         }
2096                 }
2097                 print "</td>\n";
2098                 print "<td class=\"link\">";
2099                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2100                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2101                               "blob");
2102                 if ($have_blame) {
2103                         print " | " .
2104                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2105                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
2106                                       "blame");
2107                 }
2108                 if (defined $hash_base) {
2109                         print " | " .
2110                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2111                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2112                                       "history");
2113                 }
2114                 print " | " .
2115                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2116                                                file_name=>"$basedir$t->{'name'}")},
2117                                 "raw");
2118                 print "</td>\n";
2120         } elsif ($t->{'type'} eq "tree") {
2121                 print "<td class=\"list\">";
2122                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2123                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2124                               esc_path($t->{'name'}));
2125                 print "</td>\n";
2126                 print "<td class=\"link\">";
2127                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2128                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2129                               "tree");
2130                 if (defined $hash_base) {
2131                         print " | " .
2132                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2133                                                      file_name=>"$basedir$t->{'name'}")},
2134                                       "history");
2135                 }
2136                 print "</td>\n";
2137         }
2140 ## ......................................................................
2141 ## functions printing large fragments of HTML
2143 sub git_difftree_body {
2144         my ($difftree, $hash, $parent) = @_;
2145         my ($have_blame) = gitweb_check_feature('blame');
2146         print "<div class=\"list_head\">\n";
2147         if ($#{$difftree} > 10) {
2148                 print(($#{$difftree} + 1) . " files changed:\n");
2149         }
2150         print "</div>\n";
2152         print "<table class=\"diff_tree\">\n";
2153         my $alternate = 1;
2154         my $patchno = 0;
2155         foreach my $line (@{$difftree}) {
2156                 my %diff = parse_difftree_raw_line($line);
2158                 if ($alternate) {
2159                         print "<tr class=\"dark\">\n";
2160                 } else {
2161                         print "<tr class=\"light\">\n";
2162                 }
2163                 $alternate ^= 1;
2165                 my ($to_mode_oct, $to_mode_str, $to_file_type);
2166                 my ($from_mode_oct, $from_mode_str, $from_file_type);
2167                 if ($diff{'to_mode'} ne ('0' x 6)) {
2168                         $to_mode_oct = oct $diff{'to_mode'};
2169                         if (S_ISREG($to_mode_oct)) { # only for regular file
2170                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2171                         }
2172                         $to_file_type = file_type($diff{'to_mode'});
2173                 }
2174                 if ($diff{'from_mode'} ne ('0' x 6)) {
2175                         $from_mode_oct = oct $diff{'from_mode'};
2176                         if (S_ISREG($to_mode_oct)) { # only for regular file
2177                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2178                         }
2179                         $from_file_type = file_type($diff{'from_mode'});
2180                 }
2182                 if ($diff{'status'} eq "A") { # created
2183                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2184                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2185                         $mode_chng   .= "]</span>";
2186                         print "<td>";
2187                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2188                                                      hash_base=>$hash, file_name=>$diff{'file'}),
2189                                       -class => "list"}, esc_path($diff{'file'}));
2190                         print "</td>\n";
2191                         print "<td>$mode_chng</td>\n";
2192                         print "<td class=\"link\">";
2193                         if ($action eq 'commitdiff') {
2194                                 # link to patch
2195                                 $patchno++;
2196                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2197                                 print " | ";
2198                         }
2199                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2200                                                      hash_base=>$hash, file_name=>$diff{'file'})},
2201                                       "blob") . " | ";
2202                         print "</td>\n";
2204                 } elsif ($diff{'status'} eq "D") { # deleted
2205                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2206                         print "<td>";
2207                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2208                                                      hash_base=>$parent, file_name=>$diff{'file'}),
2209                                        -class => "list"}, esc_path($diff{'file'}));
2210                         print "</td>\n";
2211                         print "<td>$mode_chng</td>\n";
2212                         print "<td class=\"link\">";
2213                         if ($action eq 'commitdiff') {
2214                                 # link to patch
2215                                 $patchno++;
2216                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2217                                 print " | ";
2218                         }
2219                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2220                                                      hash_base=>$parent, file_name=>$diff{'file'})},
2221                                       "blob") . " | ";
2222                         if ($have_blame) {
2223                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
2224                                                              file_name=>$diff{'file'})},
2225                                               "blame") . " | ";
2226                         }
2227                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2228                                                      file_name=>$diff{'file'})},
2229                                       "history");
2230                         print "</td>\n";
2232                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
2233                         my $mode_chnge = "";
2234                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
2235                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2236                                 if ($from_file_type != $to_file_type) {
2237                                         $mode_chnge .= " from $from_file_type to $to_file_type";
2238                                 }
2239                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2240                                         if ($from_mode_str && $to_mode_str) {
2241                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2242                                         } elsif ($to_mode_str) {
2243                                                 $mode_chnge .= " mode: $to_mode_str";
2244                                         }
2245                                 }
2246                                 $mode_chnge .= "]</span>\n";
2247                         }
2248                         print "<td>";
2249                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2250                                                      hash_base=>$hash, file_name=>$diff{'file'}),
2251                                       -class => "list"}, esc_path($diff{'file'}));
2252                         print "</td>\n";
2253                         print "<td>$mode_chnge</td>\n";
2254                         print "<td class=\"link\">";
2255                         if ($action eq 'commitdiff') {
2256                                 # link to patch
2257                                 $patchno++;
2258                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2259                                       " | ";
2260                         } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2261                                 # "commit" view and modified file (not onlu mode changed)
2262                                 print $cgi->a({-href => href(action=>"blobdiff",
2263                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2264                                                              hash_base=>$hash, hash_parent_base=>$parent,
2265                                                              file_name=>$diff{'file'})},
2266                                               "diff") .
2267                                       " | ";
2268                         }
2269                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2270                                                      hash_base=>$hash, file_name=>$diff{'file'})},
2271                                        "blob") . " | ";
2272                         if ($have_blame) {
2273                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2274                                                              file_name=>$diff{'file'})},
2275                                               "blame") . " | ";
2276                         }
2277                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2278                                                      file_name=>$diff{'file'})},
2279                                       "history");
2280                         print "</td>\n";
2282                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
2283                         my %status_name = ('R' => 'moved', 'C' => 'copied');
2284                         my $nstatus = $status_name{$diff{'status'}};
2285                         my $mode_chng = "";
2286                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
2287                                 # mode also for directories, so we cannot use $to_mode_str
2288                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2289                         }
2290                         print "<td>" .
2291                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2292                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
2293                                       -class => "list"}, esc_path($diff{'to_file'})) . "</td>\n" .
2294                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2295                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2296                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
2297                                       -class => "list"}, esc_path($diff{'from_file'})) .
2298                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2299                               "<td class=\"link\">";
2300                         if ($action eq 'commitdiff') {
2301                                 # link to patch
2302                                 $patchno++;
2303                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2304                                       " | ";
2305                         } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2306                                 # "commit" view and modified file (not only pure rename or copy)
2307                                 print $cgi->a({-href => href(action=>"blobdiff",
2308                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2309                                                              hash_base=>$hash, hash_parent_base=>$parent,
2310                                                              file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
2311                                               "diff") .
2312                                       " | ";
2313                         }
2314                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2315                                                      hash_base=>$parent, file_name=>$diff{'to_file'})},
2316                                       "blob") . " | ";
2317                         if ($have_blame) {
2318                                 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
2319                                                              file_name=>$diff{'to_file'})},
2320                                               "blame") . " | ";
2321                         }
2322                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2323                                                     file_name=>$diff{'to_file'})},
2324                                       "history");
2325                         print "</td>\n";
2327                 } # we should not encounter Unmerged (U) or Unknown (X) status
2328                 print "</tr>\n";
2329         }
2330         print "</table>\n";
2333 sub git_patchset_body {
2334         my ($fd, $difftree, $hash, $hash_parent) = @_;
2336         my $patch_idx = 0;
2337         my $patch_line;
2338         my $diffinfo;
2339         my (%from, %to);
2340         my ($from_id, $to_id);
2342         print "<div class=\"patchset\">\n";
2344         # skip to first patch
2345         while ($patch_line = <$fd>) {
2346                 chomp $patch_line;
2348                 last if ($patch_line =~ m/^diff /);
2349         }
2351  PATCH:
2352         while ($patch_line) {
2353                 my @diff_header;
2355                 # git diff header
2356                 #assert($patch_line =~ m/^diff /) if DEBUG;
2357                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
2358                 push @diff_header, $patch_line;
2360                 # extended diff header
2361         EXTENDED_HEADER:
2362                 while ($patch_line = <$fd>) {
2363                         chomp $patch_line;
2365                         last EXTENDED_HEADER if ($patch_line =~ m/^--- /);
2367                         if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2368                                 $from_id = $1;
2369                                 $to_id   = $2;
2370                         }
2372                         push @diff_header, $patch_line;
2373                 }
2374                 #last PATCH unless $patch_line;
2375                 my $last_patch_line = $patch_line;
2377                 # check if current patch belong to current raw line
2378                 # and parse raw git-diff line if needed
2379                 if (defined $diffinfo &&
2380                     $diffinfo->{'from_id'} eq $from_id &&
2381                     $diffinfo->{'to_id'}   eq $to_id) {
2382                         # this is split patch
2383                         print "<div class=\"patch cont\">\n";
2384                 } else {
2385                         # advance raw git-diff output if needed
2386                         $patch_idx++ if defined $diffinfo;
2388                         # read and prepare patch information
2389                         if (ref($difftree->[$patch_idx]) eq "HASH") {
2390                                 # pre-parsed (or generated by hand)
2391                                 $diffinfo = $difftree->[$patch_idx];
2392                         } else {
2393                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
2394                         }
2395                         $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
2396                         $to{'file'}   = $diffinfo->{'to_file'}   || $diffinfo->{'file'};
2397                         if ($diffinfo->{'status'} ne "A") { # not new (added) file
2398                                 $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2399                                                      hash=>$diffinfo->{'from_id'},
2400                                                      file_name=>$from{'file'});
2401                         }
2402                         if ($diffinfo->{'status'} ne "D") { # not deleted file
2403                                 $to{'href'} = href(action=>"blob", hash_base=>$hash,
2404                                                    hash=>$diffinfo->{'to_id'},
2405                                                    file_name=>$to{'file'});
2406                         }
2407                         # this is first patch for raw difftree line with $patch_idx index
2408                         # we index @$difftree array from 0, but number patches from 1
2409                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
2410                 }
2412                 # print "git diff" header
2413                 $patch_line = shift @diff_header;
2414                 $patch_line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2415                 if ($from{'href'}) {
2416                         $patch_line .= $cgi->a({-href => $from{'href'}, -class => "path"},
2417                                                'a/' . esc_path($from{'file'}));
2418                 } else { # file was added
2419                         $patch_line .= 'a/' . esc_path($from{'file'});
2420                 }
2421                 $patch_line .= ' ';
2422                 if ($to{'href'}) {
2423                         $patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
2424                                                'b/' . esc_path($to{'file'}));
2425                 } else { # file was deleted
2426                         $patch_line .= 'b/' . esc_path($to{'file'});
2427                 }
2428                 print "<div class=\"diff header\">$patch_line</div>\n";
2430                 # print extended diff header
2431                 print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
2432         EXTENDED_HEADER:
2433                 foreach $patch_line (@diff_header) {
2434                         # match <path>
2435                         if ($patch_line =~ s!^((copy|rename) from ).*$!$1! && $from{'href'}) {
2436                                 $patch_line .= $cgi->a({-href=>$from{'href'}, -class=>"path"},
2437                                                         esc_path($from{'file'}));
2438                         }
2439                         if ($patch_line =~ s!^((copy|rename) to ).*$!$1! && $to{'href'}) {
2440                                 $patch_line = $cgi->a({-href=>$to{'href'}, -class=>"path"},
2441                                                       esc_path($to{'file'}));
2442                         }
2443                         # match <mode>
2444                         if ($patch_line =~ m/\s(\d{6})$/) {
2445                                 $patch_line .= '<span class="info"> (' .
2446                                                file_type_long($1) .
2447                                                ')</span>';
2448                         }
2449                         # match <hash>
2450                         if ($patch_line =~ m/^index/) {
2451                                 my ($from_link, $to_link);
2452                                 if ($from{'href'}) {
2453                                         $from_link = $cgi->a({-href=>$from{'href'}, -class=>"hash"},
2454                                                              substr($diffinfo->{'from_id'},0,7));
2455                                 } else {
2456                                         $from_link = '0' x 7;
2457                                 }
2458                                 if ($to{'href'}) {
2459                                         $to_link = $cgi->a({-href=>$to{'href'}, -class=>"hash"},
2460                                                            substr($diffinfo->{'to_id'},0,7));
2461                                 } else {
2462                                         $to_link = '0' x 7;
2463                                 }
2464                                 #affirm {
2465                                 #       my ($from_hash, $to_hash) =
2466                                 #               ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/);
2467                                 #       my ($from_id, $to_id) =
2468                                 #               ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2469                                 #       ($from_hash eq $from_id) && ($to_hash eq $to_id);
2470                                 #} if DEBUG;
2471                                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2472                                 $patch_line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2473                         }
2474                         print $patch_line . "<br/>\n";
2475                 }
2476                 print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
2478                 # from-file/to-file diff header
2479                 $patch_line = $last_patch_line;
2480                 #assert($patch_line =~ m/^---/) if DEBUG;
2481                 if ($from{'href'}) {
2482                         $patch_line = '--- a/' .
2483                                       $cgi->a({-href=>$from{'href'}, -class=>"path"},
2484                                               esc_path($from{'file'}));
2485                 }
2486                 print "<div class=\"diff from_file\">$patch_line</div>\n";
2488                 $patch_line = <$fd>;
2489                 #last PATCH unless $patch_line;
2490                 chomp $patch_line;
2492                 #assert($patch_line =~ m/^+++/) if DEBUG;
2493                 if ($to{'href'}) {
2494                         $patch_line = '+++ b/' .
2495                                       $cgi->a({-href=>$to{'href'}, -class=>"path"},
2496                                               esc_path($to{'file'}));
2497                 }
2498                 print "<div class=\"diff to_file\">$patch_line</div>\n";
2500                 # the patch itself
2501         LINE:
2502                 while ($patch_line = <$fd>) {
2503                         chomp $patch_line;
2505                         next PATCH if ($patch_line =~ m/^diff /);
2507                         print format_diff_line($patch_line, \%from, \%to);
2508                 }
2510         } continue {
2511                 print "</div>\n"; # class="patch"
2512         }
2514         print "</div>\n"; # class="patchset"
2517 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2519 sub git_project_list_body {
2520         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
2522         my ($check_forks) = gitweb_check_feature('forks');
2524         my @projects;
2525         foreach my $pr (@$projlist) {
2526                 my (@aa) = git_get_last_activity($pr->{'path'});
2527                 unless (@aa) {
2528                         next;
2529                 }
2530                 ($pr->{'age'}, $pr->{'age_string'}) = @aa;
2531                 if (!defined $pr->{'descr'}) {
2532                         my $descr = git_get_project_description($pr->{'path'}) || "";
2533                         $pr->{'descr_long'} = to_utf8($descr);
2534                         $pr->{'descr'} = chop_str($descr, 25, 5);
2535                 }
2536                 if (!defined $pr->{'owner'}) {
2537                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2538                 }
2539                 if ($check_forks) {
2540                         my $pname = $pr->{'path'};
2541                         if (($pname =~ s/\.git$//) &&
2542                             ($pname !~ /\/$/) &&
2543                             (-d "$projectroot/$pname")) {
2544                                 $pr->{'forks'} = "-d $projectroot/$pname";
2545                         }
2546                         else {
2547                                 $pr->{'forks'} = 0;
2548                         }
2549                 }
2550                 push @projects, $pr;
2551         }
2553         $order ||= "project";
2554         $from = 0 unless defined $from;
2555         $to = $#projects if (!defined $to || $#projects < $to);
2557         print "<table class=\"project_list\">\n";
2558         unless ($no_header) {
2559                 print "<tr>\n";
2560                 if ($check_forks) {
2561                         print "<th></th>\n";
2562                 }
2563                 if ($order eq "project") {
2564                         @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2565                         print "<th>Project</th>\n";
2566                 } else {
2567                         print "<th>" .
2568                               $cgi->a({-href => href(project=>undef, order=>'project'),
2569                                        -class => "header"}, "Project") .
2570                               "</th>\n";
2571                 }
2572                 if ($order eq "descr") {
2573                         @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2574                         print "<th>Description</th>\n";
2575                 } else {
2576                         print "<th>" .
2577                               $cgi->a({-href => href(project=>undef, order=>'descr'),
2578                                        -class => "header"}, "Description") .
2579                               "</th>\n";
2580                 }
2581                 if ($order eq "owner") {
2582                         @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2583                         print "<th>Owner</th>\n";
2584                 } else {
2585                         print "<th>" .
2586                               $cgi->a({-href => href(project=>undef, order=>'owner'),
2587                                        -class => "header"}, "Owner") .
2588                               "</th>\n";
2589                 }
2590                 if ($order eq "age") {
2591                         @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
2592                         print "<th>Last Change</th>\n";
2593                 } else {
2594                         print "<th>" .
2595                               $cgi->a({-href => href(project=>undef, order=>'age'),
2596                                        -class => "header"}, "Last Change") .
2597                               "</th>\n";
2598                 }
2599                 print "<th></th>\n" .
2600                       "</tr>\n";
2601         }
2602         my $alternate = 1;
2603         for (my $i = $from; $i <= $to; $i++) {
2604                 my $pr = $projects[$i];
2605                 if ($alternate) {
2606                         print "<tr class=\"dark\">\n";
2607                 } else {
2608                         print "<tr class=\"light\">\n";
2609                 }
2610                 $alternate ^= 1;
2611                 if ($check_forks) {
2612                         print "<td>";
2613                         if ($pr->{'forks'}) {
2614                                 print "<!-- $pr->{'forks'} -->\n";
2615                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
2616                         }
2617                         print "</td>\n";
2618                 }
2619                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2620                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2621                       "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2622                                         -class => "list", -title => $pr->{'descr_long'}},
2623                                         esc_html($pr->{'descr'})) . "</td>\n" .
2624                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2625                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
2626                       $pr->{'age_string'} . "</td>\n" .
2627                       "<td class=\"link\">" .
2628                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2629                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2630                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2631                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2632                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
2633                       "</td>\n" .
2634                       "</tr>\n";
2635         }
2636         if (defined $extra) {
2637                 print "<tr>\n";
2638                 if ($check_forks) {
2639                         print "<td></td>\n";
2640                 }
2641                 print "<td colspan=\"5\">$extra</td>\n" .
2642                       "</tr>\n";
2643         }
2644         print "</table>\n";
2647 sub git_shortlog_body {
2648         # uses global variable $project
2649         my ($revlist, $from, $to, $refs, $extra) = @_;
2651         my $have_snapshot = gitweb_have_snapshot();
2653         $from = 0 unless defined $from;
2654         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2656         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2657         my $alternate = 1;
2658         for (my $i = $from; $i <= $to; $i++) {
2659                 my $commit = $revlist->[$i];
2660                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2661                 my $ref = format_ref_marker($refs, $commit);
2662                 my %co = parse_commit($commit);
2663                 if ($alternate) {
2664                         print "<tr class=\"dark\">\n";
2665                 } else {
2666                         print "<tr class=\"light\">\n";
2667                 }
2668                 $alternate ^= 1;
2669                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2670                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2671                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2672                       "<td>";
2673                 print format_subject_html($co{'title'}, $co{'title_short'},
2674                                           href(action=>"commit", hash=>$commit), $ref);
2675                 print "</td>\n" .
2676                       "<td class=\"link\">" .
2677                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2678                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2679                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2680                 if ($have_snapshot) {
2681                         print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2682                 }
2683                 print "</td>\n" .
2684                       "</tr>\n";
2685         }
2686         if (defined $extra) {
2687                 print "<tr>\n" .
2688                       "<td colspan=\"4\">$extra</td>\n" .
2689                       "</tr>\n";
2690         }
2691         print "</table>\n";
2694 sub git_history_body {
2695         # Warning: assumes constant type (blob or tree) during history
2696         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2698         $from = 0 unless defined $from;
2699         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2701         print "<table class=\"history\" cellspacing=\"0\">\n";
2702         my $alternate = 1;
2703         for (my $i = $from; $i <= $to; $i++) {
2704                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2705                         next;
2706                 }
2708                 my $commit = $1;
2709                 my %co = parse_commit($commit);
2710                 if (!%co) {
2711                         next;
2712                 }
2714                 my $ref = format_ref_marker($refs, $commit);
2716                 if ($alternate) {
2717                         print "<tr class=\"dark\">\n";
2718                 } else {
2719                         print "<tr class=\"light\">\n";
2720                 }
2721                 $alternate ^= 1;
2722                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2723                       # shortlog uses      chop_str($co{'author_name'}, 10)
2724                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2725                       "<td>";
2726                 # originally git_history used chop_str($co{'title'}, 50)
2727                 print format_subject_html($co{'title'}, $co{'title_short'},
2728                                           href(action=>"commit", hash=>$commit), $ref);
2729                 print "</td>\n" .
2730                       "<td class=\"link\">" .
2731                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2732                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2734                 if ($ftype eq 'blob') {
2735                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2736                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2737                         if (defined $blob_current && defined $blob_parent &&
2738                                         $blob_current ne $blob_parent) {
2739                                 print " | " .
2740                                         $cgi->a({-href => href(action=>"blobdiff",
2741                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2742                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2743                                                                file_name=>$file_name)},
2744                                                 "diff to current");
2745                         }
2746                 }
2747                 print "</td>\n" .
2748                       "</tr>\n";
2749         }
2750         if (defined $extra) {
2751                 print "<tr>\n" .
2752                       "<td colspan=\"4\">$extra</td>\n" .
2753                       "</tr>\n";
2754         }
2755         print "</table>\n";
2758 sub git_tags_body {
2759         # uses global variable $project
2760         my ($taglist, $from, $to, $extra) = @_;
2761         $from = 0 unless defined $from;
2762         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2764         print "<table class=\"tags\" cellspacing=\"0\">\n";
2765         my $alternate = 1;
2766         for (my $i = $from; $i <= $to; $i++) {
2767                 my $entry = $taglist->[$i];
2768                 my %tag = %$entry;
2769                 my $comment = $tag{'subject'};
2770                 my $comment_short;
2771                 if (defined $comment) {
2772                         $comment_short = chop_str($comment, 30, 5);
2773                 }
2774                 if ($alternate) {
2775                         print "<tr class=\"dark\">\n";
2776                 } else {
2777                         print "<tr class=\"light\">\n";
2778                 }
2779                 $alternate ^= 1;
2780                 print "<td><i>$tag{'age'}</i></td>\n" .
2781                       "<td>" .
2782                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2783                                -class => "list name"}, esc_html($tag{'name'})) .
2784                       "</td>\n" .
2785                       "<td>";
2786                 if (defined $comment) {
2787                         print format_subject_html($comment, $comment_short,
2788                                                   href(action=>"tag", hash=>$tag{'id'}));
2789                 }
2790                 print "</td>\n" .
2791                       "<td class=\"selflink\">";
2792                 if ($tag{'type'} eq "tag") {
2793                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2794                 } else {
2795                         print "&nbsp;";
2796                 }
2797                 print "</td>\n" .
2798                       "<td class=\"link\">" . " | " .
2799                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2800                 if ($tag{'reftype'} eq "commit") {
2801                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2802                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
2803                 } elsif ($tag{'reftype'} eq "blob") {
2804                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2805                 }
2806                 print "</td>\n" .
2807                       "</tr>";
2808         }
2809         if (defined $extra) {
2810                 print "<tr>\n" .
2811                       "<td colspan=\"5\">$extra</td>\n" .
2812                       "</tr>\n";
2813         }
2814         print "</table>\n";
2817 sub git_heads_body {
2818         # uses global variable $project
2819         my ($headlist, $head, $from, $to, $extra) = @_;
2820         $from = 0 unless defined $from;
2821         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2823         print "<table class=\"heads\" cellspacing=\"0\">\n";
2824         my $alternate = 1;
2825         for (my $i = $from; $i <= $to; $i++) {
2826                 my $entry = $headlist->[$i];
2827                 my %ref = %$entry;
2828                 my $curr = $ref{'id'} eq $head;
2829                 if ($alternate) {
2830                         print "<tr class=\"dark\">\n";
2831                 } else {
2832                         print "<tr class=\"light\">\n";
2833                 }
2834                 $alternate ^= 1;
2835                 print "<td><i>$ref{'age'}</i></td>\n" .
2836                       ($curr ? "<td class=\"current_head\">" : "<td>") .
2837                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
2838                                -class => "list name"},esc_html($ref{'name'})) .
2839                       "</td>\n" .
2840                       "<td class=\"link\">" .
2841                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
2842                       $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
2843                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
2844                       "</td>\n" .
2845                       "</tr>";
2846         }
2847         if (defined $extra) {
2848                 print "<tr>\n" .
2849                       "<td colspan=\"3\">$extra</td>\n" .
2850                       "</tr>\n";
2851         }
2852         print "</table>\n";
2855 ## ======================================================================
2856 ## ======================================================================
2857 ## actions
2859 sub git_project_list {
2860         my $order = $cgi->param('o');
2861         if (defined $order && $order !~ m/project|descr|owner|age/) {
2862                 die_error(undef, "Unknown order parameter");
2863         }
2865         my @list = git_get_projects_list();
2866         if (!@list) {
2867                 die_error(undef, "No projects found");
2868         }
2870         git_header_html();
2871         if (-f $home_text) {
2872                 print "<div class=\"index_include\">\n";
2873                 open (my $fd, $home_text);
2874                 print <$fd>;
2875                 close $fd;
2876                 print "</div>\n";
2877         }
2878         git_project_list_body(\@list, $order);
2879         git_footer_html();
2882 sub git_forks {
2883         my $order = $cgi->param('o');
2884         if (defined $order && $order !~ m/project|descr|owner|age/) {
2885                 die_error(undef, "Unknown order parameter");
2886         }
2888         my @list = git_get_projects_list($project);
2889         if (!@list) {
2890                 die_error(undef, "No forks found");
2891         }
2893         git_header_html();
2894         git_print_page_nav('','');
2895         git_print_header_div('summary', "$project forks");
2896         git_project_list_body(\@list, $order);
2897         git_footer_html();
2900 sub git_project_index {
2901         my @projects = git_get_projects_list($project);
2903         print $cgi->header(
2904                 -type => 'text/plain',
2905                 -charset => 'utf-8',
2906                 -content_disposition => 'inline; filename="index.aux"');
2908         foreach my $pr (@projects) {
2909                 if (!exists $pr->{'owner'}) {
2910                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2911                 }
2913                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2914                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2915                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2916                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2917                 $path  =~ s/ /\+/g;
2918                 $owner =~ s/ /\+/g;
2920                 print "$path $owner\n";
2921         }
2924 sub git_summary {
2925         my $descr = git_get_project_description($project) || "none";
2926         my %co = parse_commit("HEAD");
2927         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2928         my $head = $co{'id'};
2930         my $owner = git_get_project_owner($project);
2932         my $refs = git_get_references();
2933         # These get_*_list functions return one more to allow us to see if
2934         # there are more ...
2935         my @taglist  = git_get_tags_list(16);
2936         my @headlist = git_get_heads_list(16);
2937         my @forklist;
2938         my ($check_forks) = gitweb_check_feature('forks');
2940         if ($check_forks) {
2941                 @forklist = git_get_projects_list($project);
2942         }
2944         git_header_html();
2945         git_print_page_nav('summary','', $head);
2947         print "<div class=\"title\">&nbsp;</div>\n";
2948         print "<table cellspacing=\"0\">\n" .
2949               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2950               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2951               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2952         # use per project git URL list in $projectroot/$project/cloneurl
2953         # or make project git URL from git base URL and project name
2954         my $url_tag = "URL";
2955         my @url_list = git_get_project_url_list($project);
2956         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2957         foreach my $git_url (@url_list) {
2958                 next unless $git_url;
2959                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2960                 $url_tag = "";
2961         }
2962         print "</table>\n";
2964         if (-s "$projectroot/$project/README.html") {
2965                 if (open my $fd, "$projectroot/$project/README.html") {
2966                         print "<div class=\"title\">readme</div>\n";
2967                         print $_ while (<$fd>);
2968                         close $fd;
2969                 }
2970         }
2972         # we need to request one more than 16 (0..15) to check if
2973         # those 16 are all
2974         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2975                 $head, "--"
2976                 or die_error(undef, "Open git-rev-list failed");
2977         my @revlist = map { chomp; $_ } <$fd>;
2978         close $fd;
2979         git_print_header_div('shortlog');
2980         git_shortlog_body(\@revlist, 0, 15, $refs,
2981                           $#revlist <=  15 ? undef :
2982                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2984         if (@taglist) {
2985                 git_print_header_div('tags');
2986                 git_tags_body(\@taglist, 0, 15,
2987                               $#taglist <=  15 ? undef :
2988                               $cgi->a({-href => href(action=>"tags")}, "..."));
2989         }
2991         if (@headlist) {
2992                 git_print_header_div('heads');
2993                 git_heads_body(\@headlist, $head, 0, 15,
2994                                $#headlist <= 15 ? undef :
2995                                $cgi->a({-href => href(action=>"heads")}, "..."));
2996         }
2998         if (@forklist) {
2999                 git_print_header_div('forks');
3000                 git_project_list_body(\@forklist, undef, 0, 15,
3001                                       $#forklist <= 15 ? undef :
3002                                       $cgi->a({-href => href(action=>"forks")}, "..."),
3003                                       'noheader');
3004         }
3006         git_footer_html();
3009 sub git_tag {
3010         my $head = git_get_head_hash($project);
3011         git_header_html();
3012         git_print_page_nav('','', $head,undef,$head);
3013         my %tag = parse_tag($hash);
3014         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
3015         print "<div class=\"title_text\">\n" .
3016               "<table cellspacing=\"0\">\n" .
3017               "<tr>\n" .
3018               "<td>object</td>\n" .
3019               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3020                                $tag{'object'}) . "</td>\n" .
3021               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
3022                                               $tag{'type'}) . "</td>\n" .
3023               "</tr>\n";
3024         if (defined($tag{'author'})) {
3025                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
3026                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
3027                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
3028                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
3029                         "</td></tr>\n";
3030         }
3031         print "</table>\n\n" .
3032               "</div>\n";
3033         print "<div class=\"page_body\">";
3034         my $comment = $tag{'comment'};
3035         foreach my $line (@$comment) {
3036                 chomp $line;
3037                 print esc_html($line, -nbsp=>1) . "<br/>\n";
3038         }
3039         print "</div>\n";
3040         git_footer_html();
3043 sub git_blame2 {
3044         my $fd;
3045         my $ftype;
3047         my ($have_blame) = gitweb_check_feature('blame');
3048         if (!$have_blame) {
3049                 die_error('403 Permission denied', "Permission denied");
3050         }
3051         die_error('404 Not Found', "File name not defined") if (!$file_name);
3052         $hash_base ||= git_get_head_hash($project);
3053         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3054         my %co = parse_commit($hash_base)
3055                 or die_error(undef, "Reading commit failed");
3056         if (!defined $hash) {
3057                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3058                         or die_error(undef, "Error looking up file");
3059         }
3060         $ftype = git_get_type($hash);
3061         if ($ftype !~ "blob") {
3062                 die_error("400 Bad Request", "Object is not a blob");
3063         }
3064         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
3065               $file_name, $hash_base)
3066                 or die_error(undef, "Open git-blame failed");
3067         git_header_html();
3068         my $formats_nav =
3069                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3070                         "blob") .
3071                 " | " .
3072                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3073                         "history") .
3074                 " | " .
3075                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3076                         "HEAD");
3077         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3078         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3079         git_print_page_path($file_name, $ftype, $hash_base);
3080         my @rev_color = (qw(light2 dark2));
3081         my $num_colors = scalar(@rev_color);
3082         my $current_color = 0;
3083         my $last_rev;
3084         print <<HTML;
3085 <div class="page_body">
3086 <table class="blame">
3087 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
3088 HTML
3089         my %metainfo = ();
3090         while (1) {
3091                 $_ = <$fd>;
3092                 last unless defined $_;
3093                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
3094                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
3095                 if (!exists $metainfo{$full_rev}) {
3096                         $metainfo{$full_rev} = {};
3097                 }
3098                 my $meta = $metainfo{$full_rev};
3099                 while (<$fd>) {
3100                         last if (s/^\t//);
3101                         if (/^(\S+) (.*)$/) {
3102                                 $meta->{$1} = $2;
3103                         }
3104                 }
3105                 my $data = $_;
3106                 chomp $data;
3107                 my $rev = substr($full_rev, 0, 8);
3108                 my $author = $meta->{'author'};
3109                 my %date = parse_date($meta->{'author-time'},
3110                                       $meta->{'author-tz'});
3111                 my $date = $date{'iso-tz'};
3112                 if ($group_size) {
3113                         $current_color = ++$current_color % $num_colors;
3114                 }
3115                 print "<tr class=\"$rev_color[$current_color]\">\n";
3116                 if ($group_size) {
3117                         print "<td class=\"sha1\"";
3118                         print " title=\"". esc_html($author) . ", $date\"";
3119                         print " rowspan=\"$group_size\"" if ($group_size > 1);
3120                         print ">";
3121                         print $cgi->a({-href => href(action=>"commit",
3122                                                      hash=>$full_rev,
3123                                                      file_name=>$file_name)},
3124                                       esc_html($rev));
3125                         print "</td>\n";
3126                 }
3127                 my $blamed = href(action => 'blame',
3128                                   file_name => $meta->{'filename'},
3129                                   hash_base => $full_rev);
3130                 print "<td class=\"linenr\">";
3131                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
3132                                 -id => "l$lineno",
3133                                 -class => "linenr" },
3134                               esc_html($lineno));
3135                 print "</td>";
3136                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3137                 print "</tr>\n";
3138         }
3139         print "</table>\n";
3140         print "</div>";
3141         close $fd
3142                 or print "Reading blob failed\n";
3143         git_footer_html();
3146 sub git_blame {
3147         my $fd;
3149         my ($have_blame) = gitweb_check_feature('blame');
3150         if (!$have_blame) {
3151                 die_error('403 Permission denied', "Permission denied");
3152         }
3153         die_error('404 Not Found', "File name not defined") if (!$file_name);
3154         $hash_base ||= git_get_head_hash($project);
3155         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3156         my %co = parse_commit($hash_base)
3157                 or die_error(undef, "Reading commit failed");
3158         if (!defined $hash) {
3159                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3160                         or die_error(undef, "Error lookup file");
3161         }
3162         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3163                 or die_error(undef, "Open git-annotate failed");
3164         git_header_html();
3165         my $formats_nav =
3166                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3167                         "blob") .
3168                 " | " .
3169                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3170                         "history") .
3171                 " | " .
3172                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3173                         "HEAD");
3174         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3175         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3176         git_print_page_path($file_name, 'blob', $hash_base);
3177         print "<div class=\"page_body\">\n";
3178         print <<HTML;
3179 <table class="blame">
3180   <tr>
3181     <th>Commit</th>
3182     <th>Age</th>
3183     <th>Author</th>
3184     <th>Line</th>
3185     <th>Data</th>
3186   </tr>
3187 HTML
3188         my @line_class = (qw(light dark));
3189         my $line_class_len = scalar (@line_class);
3190         my $line_class_num = $#line_class;
3191         while (my $line = <$fd>) {
3192                 my $long_rev;
3193                 my $short_rev;
3194                 my $author;
3195                 my $time;
3196                 my $lineno;
3197                 my $data;
3198                 my $age;
3199                 my $age_str;
3200                 my $age_class;
3202                 chomp $line;
3203                 $line_class_num = ($line_class_num + 1) % $line_class_len;
3205                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
3206                         $long_rev = $1;
3207                         $author   = $2;
3208                         $time     = $3;
3209                         $lineno   = $4;
3210                         $data     = $5;
3211                 } else {
3212                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
3213                         next;
3214                 }
3215                 $short_rev  = substr ($long_rev, 0, 8);
3216                 $age        = time () - $time;
3217                 $age_str    = age_string ($age);
3218                 $age_str    =~ s/ /&nbsp;/g;
3219                 $age_class  = age_class($age);
3220                 $author     = esc_html ($author);
3221                 $author     =~ s/ /&nbsp;/g;
3223                 $data = untabify($data);
3224                 $data = esc_html ($data);
3226                 print <<HTML;
3227   <tr class="$line_class[$line_class_num]">
3228     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
3229     <td class="$age_class">$age_str</td>
3230     <td>$author</td>
3231     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
3232     <td class="pre">$data</td>
3233   </tr>
3234 HTML
3235         } # while (my $line = <$fd>)
3236         print "</table>\n\n";
3237         close $fd
3238                 or print "Reading blob failed.\n";
3239         print "</div>";
3240         git_footer_html();
3243 sub git_tags {
3244         my $head = git_get_head_hash($project);
3245         git_header_html();
3246         git_print_page_nav('','', $head,undef,$head);
3247         git_print_header_div('summary', $project);
3249         my @tagslist = git_get_tags_list();
3250         if (@tagslist) {
3251                 git_tags_body(\@tagslist);
3252         }
3253         git_footer_html();
3256 sub git_heads {
3257         my $head = git_get_head_hash($project);
3258         git_header_html();
3259         git_print_page_nav('','', $head,undef,$head);
3260         git_print_header_div('summary', $project);
3262         my @headslist = git_get_heads_list();
3263         if (@headslist) {
3264                 git_heads_body(\@headslist, $head);
3265         }
3266         git_footer_html();
3269 sub git_blob_plain {
3270         my $expires;
3272         if (!defined $hash) {
3273                 if (defined $file_name) {
3274                         my $base = $hash_base || git_get_head_hash($project);
3275                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3276                                 or die_error(undef, "Error lookup file");
3277                 } else {
3278                         die_error(undef, "No file name defined");
3279                 }
3280         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3281                 # blobs defined by non-textual hash id's can be cached
3282                 $expires = "+1d";
3283         }
3285         my $type = shift;
3286         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3287                 or die_error(undef, "Couldn't cat $file_name, $hash");
3289         $type ||= blob_mimetype($fd, $file_name);
3291         # save as filename, even when no $file_name is given
3292         my $save_as = "$hash";
3293         if (defined $file_name) {
3294                 $save_as = $file_name;
3295         } elsif ($type =~ m/^text\//) {
3296                 $save_as .= '.txt';
3297         }
3299         print $cgi->header(
3300                 -type => "$type",
3301                 -expires=>$expires,
3302                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
3303         undef $/;
3304         binmode STDOUT, ':raw';
3305         print <$fd>;
3306         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3307         $/ = "\n";
3308         close $fd;
3311 sub git_blob {
3312         my $expires;
3314         if (!defined $hash) {
3315                 if (defined $file_name) {
3316                         my $base = $hash_base || git_get_head_hash($project);
3317                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3318                                 or die_error(undef, "Error lookup file");
3319                 } else {
3320                         die_error(undef, "No file name defined");
3321                 }
3322         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3323                 # blobs defined by non-textual hash id's can be cached
3324                 $expires = "+1d";
3325         }
3327         my ($have_blame) = gitweb_check_feature('blame');
3328         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3329                 or die_error(undef, "Couldn't cat $file_name, $hash");
3330         my $mimetype = blob_mimetype($fd, $file_name);
3331         if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
3332                 close $fd;
3333                 return git_blob_plain($mimetype);
3334         }
3335         # we can have blame only for text/* mimetype
3336         $have_blame &&= ($mimetype =~ m!^text/!);
3338         git_header_html(undef, $expires);
3339         my $formats_nav = '';
3340         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3341                 if (defined $file_name) {
3342                         if ($have_blame) {
3343                                 $formats_nav .=
3344                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
3345                                                                hash=>$hash, file_name=>$file_name)},
3346                                                 "blame") .
3347                                         " | ";
3348                         }
3349                         $formats_nav .=
3350                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3351                                                        hash=>$hash, file_name=>$file_name)},
3352                                         "history") .
3353                                 " | " .
3354                                 $cgi->a({-href => href(action=>"blob_plain",
3355                                                        hash=>$hash, file_name=>$file_name)},
3356                                         "raw") .
3357                                 " | " .
3358                                 $cgi->a({-href => href(action=>"blob",
3359                                                        hash_base=>"HEAD", file_name=>$file_name)},
3360                                         "HEAD");
3361                 } else {
3362                         $formats_nav .=
3363                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
3364                 }
3365                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3366                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3367         } else {
3368                 print "<div class=\"page_nav\">\n" .
3369                       "<br/><br/></div>\n" .
3370                       "<div class=\"title\">$hash</div>\n";
3371         }
3372         git_print_page_path($file_name, "blob", $hash_base);
3373         print "<div class=\"page_body\">\n";
3374         if ($mimetype =~ m!^text/!) {
3375                 my $nr;
3376                 while (my $line = <$fd>) {
3377                         chomp $line;
3378                         $nr++;
3379                         $line = untabify($line);
3380                         printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
3381                                $nr, $nr, $nr, esc_html($line, -nbsp=>1);
3382                 }
3383         } elsif ($mimetype =~ m!^image/!) {
3384                 print qq!<img type="$mimetype"!;
3385                 if ($file_name) {
3386                         print qq! alt="$file_name" title="$file_name"!;
3387                 }
3388                 print qq! src="! .
3389                       href(action=>"blob_plain", hash=>$hash,
3390                            hash_base=>$hash_base, file_name=>$file_name) .
3391                       qq!" />\n!;
3392         }
3393         close $fd
3394                 or print "Reading blob failed.\n";
3395         print "</div>";
3396         git_footer_html();
3399 sub git_tree {
3400         my $have_snapshot = gitweb_have_snapshot();
3402         if (!defined $hash_base) {
3403                 $hash_base = "HEAD";
3404         }
3405         if (!defined $hash) {
3406                 if (defined $file_name) {
3407                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
3408                 } else {
3409                         $hash = $hash_base;
3410                 }
3411         }
3412         $/ = "\0";
3413         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
3414                 or die_error(undef, "Open git-ls-tree failed");
3415         my @entries = map { chomp; $_ } <$fd>;
3416         close $fd or die_error(undef, "Reading tree failed");
3417         $/ = "\n";
3419         my $refs = git_get_references();
3420         my $ref = format_ref_marker($refs, $hash_base);
3421         git_header_html();
3422         my $basedir = '';
3423         my ($have_blame) = gitweb_check_feature('blame');
3424         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3425                 my @views_nav = ();
3426                 if (defined $file_name) {
3427                         push @views_nav,
3428                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3429                                                        hash=>$hash, file_name=>$file_name)},
3430                                         "history"),
3431                                 $cgi->a({-href => href(action=>"tree",
3432                                                        hash_base=>"HEAD", file_name=>$file_name)},
3433                                         "HEAD"),
3434                 }
3435                 if ($have_snapshot) {
3436                         # FIXME: Should be available when we have no hash base as well.
3437                         push @views_nav,
3438                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
3439                                         "snapshot");
3440                 }
3441                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
3442                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
3443         } else {
3444                 undef $hash_base;
3445                 print "<div class=\"page_nav\">\n";
3446                 print "<br/><br/></div>\n";
3447                 print "<div class=\"title\">$hash</div>\n";
3448         }
3449         if (defined $file_name) {
3450                 $basedir = $file_name;
3451                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
3452                         $basedir .= '/';
3453                 }
3454         }
3455         git_print_page_path($file_name, 'tree', $hash_base);
3456         print "<div class=\"page_body\">\n";
3457         print "<table cellspacing=\"0\">\n";
3458         my $alternate = 1;
3459         # '..' (top directory) link if possible
3460         if (defined $hash_base &&
3461             defined $file_name && $file_name =~ m![^/]+$!) {
3462                 if ($alternate) {
3463                         print "<tr class=\"dark\">\n";
3464                 } else {
3465                         print "<tr class=\"light\">\n";
3466                 }
3467                 $alternate ^= 1;
3469                 my $up = $file_name;
3470                 $up =~ s!/?[^/]+$!!;
3471                 undef $up unless $up;
3472                 # based on git_print_tree_entry
3473                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
3474                 print '<td class="list">';
3475                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
3476                                              file_name=>$up)},
3477                               "..");
3478                 print "</td>\n";
3479                 print "<td class=\"link\"></td>\n";
3481                 print "</tr>\n";
3482         }
3483         foreach my $line (@entries) {
3484                 my %t = parse_ls_tree_line($line, -z => 1);
3486                 if ($alternate) {
3487                         print "<tr class=\"dark\">\n";
3488                 } else {
3489                         print "<tr class=\"light\">\n";
3490                 }
3491                 $alternate ^= 1;
3493                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
3495                 print "</tr>\n";
3496         }
3497         print "</table>\n" .
3498               "</div>";
3499         git_footer_html();
3502 sub git_snapshot {
3503         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
3504         my $have_snapshot = (defined $ctype && defined $suffix);
3505         if (!$have_snapshot) {
3506                 die_error('403 Permission denied', "Permission denied");
3507         }
3509         if (!defined $hash) {
3510                 $hash = git_get_head_hash($project);
3511         }
3513         my $filename = basename($project) . "-$hash.tar.$suffix";
3515         print $cgi->header(
3516                 -type => "application/$ctype",
3517                 -content_disposition => 'inline; filename="' . "$filename" . '"',
3518                 -status => '200 OK');
3520         my $git = git_cmd_str();
3521         my $name = $project;
3522         $name =~ s/\047/\047\\\047\047/g;
3523         open my $fd, "-|",
3524         "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
3525                 or die_error(undef, "Execute git-tar-tree failed.");
3526         binmode STDOUT, ':raw';
3527         print <$fd>;
3528         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3529         close $fd;
3533 sub git_log {
3534         my $head = git_get_head_hash($project);
3535         if (!defined $hash) {
3536                 $hash = $head;
3537         }
3538         if (!defined $page) {
3539                 $page = 0;
3540         }
3541         my $refs = git_get_references();
3543         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3544         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
3545                 or die_error(undef, "Open git-rev-list failed");
3546         my @revlist = map { chomp; $_ } <$fd>;
3547         close $fd;
3549         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
3551         git_header_html();
3552         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
3554         if (!@revlist) {
3555                 my %co = parse_commit($hash);
3557                 git_print_header_div('summary', $project);
3558                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
3559         }
3560         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
3561                 my $commit = $revlist[$i];
3562                 my $ref = format_ref_marker($refs, $commit);
3563                 my %co = parse_commit($commit);
3564                 next if !%co;
3565                 my %ad = parse_date($co{'author_epoch'});
3566                 git_print_header_div('commit',
3567                                "<span class=\"age\">$co{'age_string'}</span>" .
3568                                esc_html($co{'title'}) . $ref,
3569                                $commit);
3570                 print "<div class=\"title_text\">\n" .
3571                       "<div class=\"log_link\">\n" .
3572                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
3573                       " | " .
3574                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
3575                       " | " .
3576                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
3577                       "<br/>\n" .
3578                       "</div>\n" .
3579                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
3580                       "</div>\n";
3582                 print "<div class=\"log_body\">\n";
3583                 git_print_log($co{'comment'}, -final_empty_line=> 1);
3584                 print "</div>\n";
3585         }
3586         git_footer_html();
3589 sub git_commit {
3590         $hash ||= $hash_base || "HEAD";
3591         my %co = parse_commit($hash);
3592         if (!%co) {
3593                 die_error(undef, "Unknown commit object");
3594         }
3595         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3596         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3598         my $parent  = $co{'parent'};
3599         my $parents = $co{'parents'}; # listref
3601         # we need to prepare $formats_nav before any parameter munging
3602         my $formats_nav;
3603         if (!defined $parent) {
3604                 # --root commitdiff
3605                 $formats_nav .= '(initial)';
3606         } elsif (@$parents == 1) {
3607                 # single parent commit
3608                 $formats_nav .=
3609                         '(parent: ' .
3610                         $cgi->a({-href => href(action=>"commit",
3611                                                hash=>$parent)},
3612                                 esc_html(substr($parent, 0, 7))) .
3613                         ')';
3614         } else {
3615                 # merge commit
3616                 $formats_nav .=
3617                         '(merge: ' .
3618                         join(' ', map {
3619                                 $cgi->a({-href => href(action=>"commitdiff",
3620                                                        hash=>$_)},
3621                                         esc_html(substr($_, 0, 7)));
3622                         } @$parents ) .
3623                         ')';
3624         }
3626         if (!defined $parent) {
3627                 $parent = "--root";
3628         }
3629         my @difftree;
3630         if (@$parents <= 1) {
3631                 # difftree output is not printed for merges
3632                 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
3633                         @diff_opts, $parent, $hash, "--"
3634                                 or die_error(undef, "Open git-diff-tree failed");
3635                 @difftree = map { chomp; $_ } <$fd>;
3636                 close $fd or die_error(undef, "Reading git-diff-tree failed");
3637         }
3639         # non-textual hash id's can be cached
3640         my $expires;
3641         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3642                 $expires = "+1d";
3643         }
3644         my $refs = git_get_references();
3645         my $ref = format_ref_marker($refs, $co{'id'});
3647         my $have_snapshot = gitweb_have_snapshot();
3649         git_header_html(undef, $expires);
3650         git_print_page_nav('commit', '',
3651                            $hash, $co{'tree'}, $hash,
3652                            $formats_nav);
3654         if (defined $co{'parent'}) {
3655                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3656         } else {
3657                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3658         }
3659         print "<div class=\"title_text\">\n" .
3660               "<table cellspacing=\"0\">\n";
3661         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3662               "<tr>" .
3663               "<td></td><td> $ad{'rfc2822'}";
3664         if ($ad{'hour_local'} < 6) {
3665                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3666                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3667         } else {
3668                 printf(" (%02d:%02d %s)",
3669                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3670         }
3671         print "</td>" .
3672               "</tr>\n";
3673         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3674         print "<tr><td></td><td> $cd{'rfc2822'}" .
3675               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3676               "</td></tr>\n";
3677         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3678         print "<tr>" .
3679               "<td>tree</td>" .
3680               "<td class=\"sha1\">" .
3681               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3682                        class => "list"}, $co{'tree'}) .
3683               "</td>" .
3684               "<td class=\"link\">" .
3685               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3686                       "tree");
3687         if ($have_snapshot) {
3688                 print " | " .
3689                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3690         }
3691         print "</td>" .
3692               "</tr>\n";
3694         foreach my $par (@$parents) {
3695                 print "<tr>" .
3696                       "<td>parent</td>" .
3697                       "<td class=\"sha1\">" .
3698                       $cgi->a({-href => href(action=>"commit", hash=>$par),
3699                                class => "list"}, $par) .
3700                       "</td>" .
3701                       "<td class=\"link\">" .
3702                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3703                       " | " .
3704                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3705                       "</td>" .
3706                       "</tr>\n";
3707         }
3708         print "</table>".
3709               "</div>\n";
3711         print "<div class=\"page_body\">\n";
3712         git_print_log($co{'comment'});
3713         print "</div>\n";
3715         if (@$parents <= 1) {
3716                 # do not output difftree/whatchanged for merges
3717                 git_difftree_body(\@difftree, $hash, $parent);
3718         }
3720         git_footer_html();
3723 sub git_object {
3724         # object is defined by:
3725         # - hash or hash_base alone
3726         # - hash_base and file_name
3727         my $type;
3729         # - hash or hash_base alone
3730         if ($hash || ($hash_base && !defined $file_name)) {
3731                 my $object_id = $hash || $hash_base;
3733                 my $git_command = git_cmd_str();
3734                 open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
3735                         or die_error('404 Not Found', "Object does not exist");
3736                 $type = <$fd>;
3737                 chomp $type;
3738                 close $fd
3739                         or die_error('404 Not Found', "Object does not exist");
3741         # - hash_base and file_name
3742         } elsif ($hash_base && defined $file_name) {
3743                 $file_name =~ s,/+$,,;
3745                 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
3746                         or die_error('404 Not Found', "Base object does not exist");
3748                 # here errors should not hapen
3749                 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
3750                         or die_error(undef, "Open git-ls-tree failed");
3751                 my $line = <$fd>;
3752                 close $fd;
3754                 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
3755                 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
3756                         die_error('404 Not Found', "File or directory for given base does not exist");
3757                 }
3758                 $type = $2;
3759                 $hash = $3;
3760         } else {
3761                 die_error('404 Not Found', "Not enough information to find object");
3762         }
3764         print $cgi->redirect(-uri => href(action=>$type, -full=>1,
3765                                           hash=>$hash, hash_base=>$hash_base,
3766                                           file_name=>$file_name),
3767                              -status => '302 Found');
3770 sub git_blobdiff {
3771         my $format = shift || 'html';
3773         my $fd;
3774         my @difftree;
3775         my %diffinfo;
3776         my $expires;
3778         # preparing $fd and %diffinfo for git_patchset_body
3779         # new style URI
3780         if (defined $hash_base && defined $hash_parent_base) {
3781                 if (defined $file_name) {
3782                         # read raw output
3783                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3784                                 $hash_parent_base, $hash_base,
3785                                 "--", $file_name
3786                                 or die_error(undef, "Open git-diff-tree failed");
3787                         @difftree = map { chomp; $_ } <$fd>;
3788                         close $fd
3789                                 or die_error(undef, "Reading git-diff-tree failed");
3790                         @difftree
3791                                 or die_error('404 Not Found', "Blob diff not found");
3793                 } elsif (defined $hash &&
3794                          $hash =~ /[0-9a-fA-F]{40}/) {
3795                         # try to find filename from $hash
3797                         # read filtered raw output
3798                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3799                                 $hash_parent_base, $hash_base, "--"
3800                                 or die_error(undef, "Open git-diff-tree failed");
3801                         @difftree =
3802                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3803                                 # $hash == to_id
3804                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3805                                 map { chomp; $_ } <$fd>;
3806                         close $fd
3807                                 or die_error(undef, "Reading git-diff-tree failed");
3808                         @difftree
3809                                 or die_error('404 Not Found', "Blob diff not found");
3811                 } else {
3812                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3813                 }
3815                 if (@difftree > 1) {
3816                         die_error('404 Not Found', "Ambiguous blob diff specification");
3817                 }
3819                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3820                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3821                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3823                 $hash_parent ||= $diffinfo{'from_id'};
3824                 $hash        ||= $diffinfo{'to_id'};
3826                 # non-textual hash id's can be cached
3827                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3828                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3829                         $expires = '+1d';
3830                 }
3832                 # open patch output
3833                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3834                         '-p', $hash_parent_base, $hash_base,
3835                         "--", $file_name
3836                         or die_error(undef, "Open git-diff-tree failed");
3837         }
3839         # old/legacy style URI
3840         if (!%diffinfo && # if new style URI failed
3841             defined $hash && defined $hash_parent) {
3842                 # fake git-diff-tree raw output
3843                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3844                 $diffinfo{'from_id'} = $hash_parent;
3845                 $diffinfo{'to_id'}   = $hash;
3846                 if (defined $file_name) {
3847                         if (defined $file_parent) {
3848                                 $diffinfo{'status'} = '2';
3849                                 $diffinfo{'from_file'} = $file_parent;
3850                                 $diffinfo{'to_file'}   = $file_name;
3851                         } else { # assume not renamed
3852                                 $diffinfo{'status'} = '1';
3853                                 $diffinfo{'from_file'} = $file_name;
3854                                 $diffinfo{'to_file'}   = $file_name;
3855                         }
3856                 } else { # no filename given
3857                         $diffinfo{'status'} = '2';
3858                         $diffinfo{'from_file'} = $hash_parent;
3859                         $diffinfo{'to_file'}   = $hash;
3860                 }
3862                 # non-textual hash id's can be cached
3863                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3864                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3865                         $expires = '+1d';
3866                 }
3868                 # open patch output
3869                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts,
3870                         $hash_parent, $hash, "--"
3871                         or die_error(undef, "Open git-diff failed");
3872         } else  {
3873                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3874                         unless %diffinfo;
3875         }
3877         # header
3878         if ($format eq 'html') {
3879                 my $formats_nav =
3880                         $cgi->a({-href => href(action=>"blobdiff_plain",
3881                                                hash=>$hash, hash_parent=>$hash_parent,
3882                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3883                                                file_name=>$file_name, file_parent=>$file_parent)},
3884                                 "raw");
3885                 git_header_html(undef, $expires);
3886                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3887                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3888                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3889                 } else {
3890                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3891                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3892                 }
3893                 if (defined $file_name) {
3894                         git_print_page_path($file_name, "blob", $hash_base);
3895                 } else {
3896                         print "<div class=\"page_path\"></div>\n";
3897                 }
3899         } elsif ($format eq 'plain') {
3900                 print $cgi->header(
3901                         -type => 'text/plain',
3902                         -charset => 'utf-8',
3903                         -expires => $expires,
3904                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
3906                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3908         } else {
3909                 die_error(undef, "Unknown blobdiff format");
3910         }
3912         # patch
3913         if ($format eq 'html') {
3914                 print "<div class=\"page_body\">\n";
3916                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3917                 close $fd;
3919                 print "</div>\n"; # class="page_body"
3920                 git_footer_html();
3922         } else {
3923                 while (my $line = <$fd>) {
3924                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
3925                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
3927                         print $line;
3929                         last if $line =~ m!^\+\+\+!;
3930                 }
3931                 local $/ = undef;
3932                 print <$fd>;
3933                 close $fd;
3934         }
3937 sub git_blobdiff_plain {
3938         git_blobdiff('plain');
3941 sub git_commitdiff {
3942         my $format = shift || 'html';
3943         $hash ||= $hash_base || "HEAD";
3944         my %co = parse_commit($hash);
3945         if (!%co) {
3946                 die_error(undef, "Unknown commit object");
3947         }
3949         # we need to prepare $formats_nav before any parameter munging
3950         my $formats_nav;
3951         if ($format eq 'html') {
3952                 $formats_nav =
3953                         $cgi->a({-href => href(action=>"commitdiff_plain",
3954                                                hash=>$hash, hash_parent=>$hash_parent)},
3955                                 "raw");
3957                 if (defined $hash_parent) {
3958                         # commitdiff with two commits given
3959                         my $hash_parent_short = $hash_parent;
3960                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3961                                 $hash_parent_short = substr($hash_parent, 0, 7);
3962                         }
3963                         $formats_nav .=
3964                                 ' (from: ' .
3965                                 $cgi->a({-href => href(action=>"commitdiff",
3966                                                        hash=>$hash_parent)},
3967                                         esc_html($hash_parent_short)) .
3968                                 ')';
3969                 } elsif (!$co{'parent'}) {
3970                         # --root commitdiff
3971                         $formats_nav .= ' (initial)';
3972                 } elsif (scalar @{$co{'parents'}} == 1) {
3973                         # single parent commit
3974                         $formats_nav .=
3975                                 ' (parent: ' .
3976                                 $cgi->a({-href => href(action=>"commitdiff",
3977                                                        hash=>$co{'parent'})},
3978                                         esc_html(substr($co{'parent'}, 0, 7))) .
3979                                 ')';
3980                 } else {
3981                         # merge commit
3982                         $formats_nav .=
3983                                 ' (merge: ' .
3984                                 join(' ', map {
3985                                         $cgi->a({-href => href(action=>"commitdiff",
3986                                                                hash=>$_)},
3987                                                 esc_html(substr($_, 0, 7)));
3988                                 } @{$co{'parents'}} ) .
3989                                 ')';
3990                 }
3991         }
3993         if (!defined $hash_parent) {
3994                 $hash_parent = $co{'parent'} || '--root';
3995         }
3997         # read commitdiff
3998         my $fd;
3999         my @difftree;
4000         if ($format eq 'html') {
4001                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4002                         "--no-commit-id", "--patch-with-raw", "--full-index",
4003                         $hash_parent, $hash, "--"
4004                         or die_error(undef, "Open git-diff-tree failed");
4006                 while (my $line = <$fd>) {
4007                         chomp $line;
4008                         # empty line ends raw part of diff-tree output
4009                         last unless $line;
4010                         push @difftree, $line;
4011                 }
4013         } elsif ($format eq 'plain') {
4014                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4015                         '-p', $hash_parent, $hash, "--"
4016                         or die_error(undef, "Open git-diff-tree failed");
4018         } else {
4019                 die_error(undef, "Unknown commitdiff format");
4020         }
4022         # non-textual hash id's can be cached
4023         my $expires;
4024         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4025                 $expires = "+1d";
4026         }
4028         # write commit message
4029         if ($format eq 'html') {
4030                 my $refs = git_get_references();
4031                 my $ref = format_ref_marker($refs, $co{'id'});
4033                 git_header_html(undef, $expires);
4034                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
4035                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
4036                 git_print_authorship(\%co);
4037                 print "<div class=\"page_body\">\n";
4038                 if (@{$co{'comment'}} > 1) {
4039                         print "<div class=\"log\">\n";
4040                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
4041                         print "</div>\n"; # class="log"
4042                 }
4044         } elsif ($format eq 'plain') {
4045                 my $refs = git_get_references("tags");
4046                 my $tagname = git_get_rev_name_tags($hash);
4047                 my $filename = basename($project) . "-$hash.patch";
4049                 print $cgi->header(
4050                         -type => 'text/plain',
4051                         -charset => 'utf-8',
4052                         -expires => $expires,
4053                         -content_disposition => 'inline; filename="' . "$filename" . '"');
4054                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4055                 print <<TEXT;
4056 From: $co{'author'}
4057 Date: $ad{'rfc2822'} ($ad{'tz_local'})
4058 Subject: $co{'title'}
4059 TEXT
4060                 print "X-Git-Tag: $tagname\n" if $tagname;
4061                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4063                 foreach my $line (@{$co{'comment'}}) {
4064                         print "$line\n";
4065                 }
4066                 print "---\n\n";
4067         }
4069         # write patch
4070         if ($format eq 'html') {
4071                 git_difftree_body(\@difftree, $hash, $hash_parent);
4072                 print "<br/>\n";
4074                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
4075                 close $fd;
4076                 print "</div>\n"; # class="page_body"
4077                 git_footer_html();
4079         } elsif ($format eq 'plain') {
4080                 local $/ = undef;
4081                 print <$fd>;
4082                 close $fd
4083                         or print "Reading git-diff-tree failed\n";
4084         }
4087 sub git_commitdiff_plain {
4088         git_commitdiff('plain');
4091 sub git_history {
4092         if (!defined $hash_base) {
4093                 $hash_base = git_get_head_hash($project);
4094         }
4095         if (!defined $page) {
4096                 $page = 0;
4097         }
4098         my $ftype;
4099         my %co = parse_commit($hash_base);
4100         if (!%co) {
4101                 die_error(undef, "Unknown commit object");
4102         }
4104         my $refs = git_get_references();
4105         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4107         if (!defined $hash && defined $file_name) {
4108                 $hash = git_get_hash_by_path($hash_base, $file_name);
4109         }
4110         if (defined $hash) {
4111                 $ftype = git_get_type($hash);
4112         }
4114         open my $fd, "-|",
4115                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
4116                         or die_error(undef, "Open git-rev-list-failed");
4117         my @revlist = map { chomp; $_ } <$fd>;
4118         close $fd
4119                 or die_error(undef, "Reading git-rev-list failed");
4121         my $paging_nav = '';
4122         if ($page > 0) {
4123                 $paging_nav .=
4124                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4125                                                file_name=>$file_name)},
4126                                 "first");
4127                 $paging_nav .= " &sdot; " .
4128                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4129                                                file_name=>$file_name, page=>$page-1),
4130                                  -accesskey => "p", -title => "Alt-p"}, "prev");
4131         } else {
4132                 $paging_nav .= "first";
4133                 $paging_nav .= " &sdot; prev";
4134         }
4135         if ($#revlist >= (100 * ($page+1)-1)) {
4136                 $paging_nav .= " &sdot; " .
4137                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4138                                                file_name=>$file_name, page=>$page+1),
4139                                  -accesskey => "n", -title => "Alt-n"}, "next");
4140         } else {
4141                 $paging_nav .= " &sdot; next";
4142         }
4143         my $next_link = '';
4144         if ($#revlist >= (100 * ($page+1)-1)) {
4145                 $next_link =
4146                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
4147                                                file_name=>$file_name, page=>$page+1),
4148                                  -title => "Alt-n"}, "next");
4149         }
4151         git_header_html();
4152         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
4153         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4154         git_print_page_path($file_name, $ftype, $hash_base);
4156         git_history_body(\@revlist, ($page * 100), $#revlist,
4157                          $refs, $hash_base, $ftype, $next_link);
4159         git_footer_html();
4162 sub git_search {
4163         my ($have_search) = gitweb_check_feature('search');
4164         if (!$have_search) {
4165                 die_error('403 Permission denied', "Permission denied");
4166         }
4167         if (!defined $searchtext) {
4168                 die_error(undef, "Text field empty");
4169         }
4170         if (!defined $hash) {
4171                 $hash = git_get_head_hash($project);
4172         }
4173         my %co = parse_commit($hash);
4174         if (!%co) {
4175                 die_error(undef, "Unknown commit object");
4176         }
4178         $searchtype ||= 'commit';
4179         if ($searchtype eq 'pickaxe') {
4180                 # pickaxe may take all resources of your box and run for several minutes
4181                 # with every query - so decide by yourself how public you make this feature
4182                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4183                 if (!$have_pickaxe) {
4184                         die_error('403 Permission denied', "Permission denied");
4185                 }
4186         }
4188         git_header_html();
4189         git_print_page_nav('','', $hash,$co{'tree'},$hash);
4190         git_print_header_div('commit', esc_html($co{'title'}), $hash);
4192         print "<table cellspacing=\"0\">\n";
4193         my $alternate = 1;
4194         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
4195                 my $greptype;
4196                 if ($searchtype eq 'commit') {
4197                         $greptype = "--grep=";
4198                 } elsif ($searchtype eq 'author') {
4199                         $greptype = "--author=";
4200                 } elsif ($searchtype eq 'committer') {
4201                         $greptype = "--committer=";
4202                 }
4203                 $/ = "\0";
4204                 open my $fd, "-|", git_cmd(), "rev-list",
4205                         "--header", "--parents", ($greptype . $searchtext),
4206                          $hash, "--"
4207                         or next;
4208                 while (my $commit_text = <$fd>) {
4209                         my @commit_lines = split "\n", $commit_text;
4210                         my %co = parse_commit(undef, \@commit_lines);
4211                         if (!%co) {
4212                                 next;
4213                         }
4214                         if ($alternate) {
4215                                 print "<tr class=\"dark\">\n";
4216                         } else {
4217                                 print "<tr class=\"light\">\n";
4218                         }
4219                         $alternate ^= 1;
4220                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4221                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
4222                               "<td>" .
4223                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
4224                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
4225                         my $comment = $co{'comment'};
4226                         foreach my $line (@$comment) {
4227                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
4228                                         my $lead = esc_html($1) || "";
4229                                         $lead = chop_str($lead, 30, 10);
4230                                         my $match = esc_html($2) || "";
4231                                         my $trail = esc_html($3) || "";
4232                                         $trail = chop_str($trail, 30, 10);
4233                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
4234                                         print chop_str($text, 80, 5) . "<br/>\n";
4235                                 }
4236                         }
4237                         print "</td>\n" .
4238                               "<td class=\"link\">" .
4239                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4240                               " | " .
4241                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4242                         print "</td>\n" .
4243                               "</tr>\n";
4244                 }
4245                 close $fd;
4246         }
4248         if ($searchtype eq 'pickaxe') {
4249                 $/ = "\n";
4250                 my $git_command = git_cmd_str();
4251                 open my $fd, "-|", "$git_command rev-list $hash | " .
4252                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
4253                 undef %co;
4254                 my @files;
4255                 while (my $line = <$fd>) {
4256                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
4257                                 my %set;
4258                                 $set{'file'} = $6;
4259                                 $set{'from_id'} = $3;
4260                                 $set{'to_id'} = $4;
4261                                 $set{'id'} = $set{'to_id'};
4262                                 if ($set{'id'} =~ m/0{40}/) {
4263                                         $set{'id'} = $set{'from_id'};
4264                                 }
4265                                 if ($set{'id'} =~ m/0{40}/) {
4266                                         next;
4267                                 }
4268                                 push @files, \%set;
4269                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
4270                                 if (%co) {
4271                                         if ($alternate) {
4272                                                 print "<tr class=\"dark\">\n";
4273                                         } else {
4274                                                 print "<tr class=\"light\">\n";
4275                                         }
4276                                         $alternate ^= 1;
4277                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4278                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
4279                                               "<td>" .
4280                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4281                                                       -class => "list subject"},
4282                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
4283                                         while (my $setref = shift @files) {
4284                                                 my %set = %$setref;
4285                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
4286                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
4287                                                               -class => "list"},
4288                                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
4289                                                       "<br/>\n";
4290                                         }
4291                                         print "</td>\n" .
4292                                               "<td class=\"link\">" .
4293                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4294                                               " | " .
4295                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4296                                         print "</td>\n" .
4297                                               "</tr>\n";
4298                                 }
4299                                 %co = parse_commit($1);
4300                         }
4301                 }
4302                 close $fd;
4303         }
4304         print "</table>\n";
4305         git_footer_html();
4308 sub git_search_help {
4309         git_header_html();
4310         git_print_page_nav('','', $hash,$hash,$hash);
4311         print <<EOT;
4312 <dl>
4313 <dt><b>commit</b></dt>
4314 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
4315 <dt><b>author</b></dt>
4316 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
4317 <dt><b>committer</b></dt>
4318 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
4319 EOT
4320         my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4321         if ($have_pickaxe) {
4322                 print <<EOT;
4323 <dt><b>pickaxe</b></dt>
4324 <dd>All commits that caused the string to appear or disappear from any file (changes that
4325 added, removed or "modified" the string) will be listed. This search can take a while and
4326 takes a lot of strain on the server, so please use it wisely.</dd>
4327 EOT
4328         }
4329         print "</dl>\n";
4330         git_footer_html();
4333 sub git_shortlog {
4334         my $head = git_get_head_hash($project);
4335         if (!defined $hash) {
4336                 $hash = $head;
4337         }
4338         if (!defined $page) {
4339                 $page = 0;
4340         }
4341         my $refs = git_get_references();
4343         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4344         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
4345                 or die_error(undef, "Open git-rev-list failed");
4346         my @revlist = map { chomp; $_ } <$fd>;
4347         close $fd;
4349         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
4350         my $next_link = '';
4351         if ($#revlist >= (100 * ($page+1)-1)) {
4352                 $next_link =
4353                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
4354                                  -title => "Alt-n"}, "next");
4355         }
4358         git_header_html();
4359         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
4360         git_print_header_div('summary', $project);
4362         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
4364         git_footer_html();
4367 ## ......................................................................
4368 ## feeds (RSS, Atom; OPML)
4370 sub git_feed {
4371         my $format = shift || 'atom';
4372         my ($have_blame) = gitweb_check_feature('blame');
4374         # Atom: http://www.atomenabled.org/developers/syndication/
4375         # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
4376         if ($format ne 'rss' && $format ne 'atom') {
4377                 die_error(undef, "Unknown web feed format");
4378         }
4380         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
4381         my $head = $hash || 'HEAD';
4382         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150",
4383                 $head, "--", (defined $file_name ? $file_name : ())
4384                 or die_error(undef, "Open git-rev-list failed");
4385         my @revlist = map { chomp; $_ } <$fd>;
4386         close $fd or die_error(undef, "Reading git-rev-list failed");
4388         my %latest_commit;
4389         my %latest_date;
4390         my $content_type = "application/$format+xml";
4391         if (defined $cgi->http('HTTP_ACCEPT') &&
4392                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
4393                 # browser (feed reader) prefers text/xml
4394                 $content_type = 'text/xml';
4395         }
4396         if (defined($revlist[0])) {
4397                 %latest_commit = parse_commit($revlist[0]);
4398                 %latest_date   = parse_date($latest_commit{'author_epoch'});
4399                 print $cgi->header(
4400                         -type => $content_type,
4401                         -charset => 'utf-8',
4402                         -last_modified => $latest_date{'rfc2822'});
4403         } else {
4404                 print $cgi->header(
4405                         -type => $content_type,
4406                         -charset => 'utf-8');
4407         }
4409         # Optimization: skip generating the body if client asks only
4410         # for Last-Modified date.
4411         return if ($cgi->request_method() eq 'HEAD');
4413         # header variables
4414         my $title = "$site_name - $project/$action";
4415         my $feed_type = 'log';
4416         if (defined $hash) {
4417                 $title .= " - '$hash'";
4418                 $feed_type = 'branch log';
4419                 if (defined $file_name) {
4420                         $title .= " :: $file_name";
4421                         $feed_type = 'history';
4422                 }
4423         } elsif (defined $file_name) {
4424                 $title .= " - $file_name";
4425                 $feed_type = 'history';
4426         }
4427         $title .= " $feed_type";
4428         my $descr = git_get_project_description($project);
4429         if (defined $descr) {
4430                 $descr = esc_html($descr);
4431         } else {
4432                 $descr = "$project " .
4433                          ($format eq 'rss' ? 'RSS' : 'Atom') .
4434                          " feed";
4435         }
4436         my $owner = git_get_project_owner($project);
4437         $owner = esc_html($owner);
4439         #header
4440         my $alt_url;
4441         if (defined $file_name) {
4442                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
4443         } elsif (defined $hash) {
4444                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
4445         } else {
4446                 $alt_url = href(-full=>1, action=>"summary");
4447         }
4448         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
4449         if ($format eq 'rss') {
4450                 print <<XML;
4451 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
4452 <channel>
4453 XML
4454                 print "<title>$title</title>\n" .
4455                       "<link>$alt_url</link>\n" .
4456                       "<description>$descr</description>\n" .
4457                       "<language>en</language>\n";
4458         } elsif ($format eq 'atom') {
4459                 print <<XML;
4460 <feed xmlns="http://www.w3.org/2005/Atom">
4461 XML
4462                 print "<title>$title</title>\n" .
4463                       "<subtitle>$descr</subtitle>\n" .
4464                       '<link rel="alternate" type="text/html" href="' .
4465                       $alt_url . '" />' . "\n" .
4466                       '<link rel="self" type="' . $content_type . '" href="' .
4467                       $cgi->self_url() . '" />' . "\n" .
4468                       "<id>" . href(-full=>1) . "</id>\n" .
4469                       # use project owner for feed author
4470                       "<author><name>$owner</name></author>\n";
4471                 if (defined $favicon) {
4472                         print "<icon>" . esc_url($favicon) . "</icon>\n";
4473                 }
4474                 if (defined $logo_url) {
4475                         # not twice as wide as tall: 72 x 27 pixels
4476                         print "<logo>" . esc_url($logo) . "</logo>\n";
4477                 }
4478                 if (! %latest_date) {
4479                         # dummy date to keep the feed valid until commits trickle in:
4480                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
4481                 } else {
4482                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
4483                 }
4484         }
4486         # contents
4487         for (my $i = 0; $i <= $#revlist; $i++) {
4488                 my $commit = $revlist[$i];
4489                 my %co = parse_commit($commit);
4490                 # we read 150, we always show 30 and the ones more recent than 48 hours
4491                 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
4492                         last;
4493                 }
4494                 my %cd = parse_date($co{'author_epoch'});
4496                 # get list of changed files
4497                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4498                         $co{'parent'}, $co{'id'}, "--", (defined $file_name ? $file_name : ())
4499                         or next;
4500                 my @difftree = map { chomp; $_ } <$fd>;
4501                 close $fd
4502                         or next;
4504                 # print element (entry, item)
4505                 my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
4506                 if ($format eq 'rss') {
4507                         print "<item>\n" .
4508                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
4509                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
4510                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
4511                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
4512                               "<link>$co_url</link>\n" .
4513                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
4514                               "<content:encoded>" .
4515                               "<![CDATA[\n";
4516                 } elsif ($format eq 'atom') {
4517                         print "<entry>\n" .
4518                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
4519                               "<updated>$cd{'iso-8601'}</updated>\n" .
4520                               "<author>\n" .
4521                               "  <name>" . esc_html($co{'author_name'}) . "</name>\n";
4522                         if ($co{'author_email'}) {
4523                                 print "  <email>" . esc_html($co{'author_email'}) . "</email>\n";
4524                         }
4525                         print "</author>\n" .
4526                               # use committer for contributor
4527                               "<contributor>\n" .
4528                               "  <name>" . esc_html($co{'committer_name'}) . "</name>\n";
4529                         if ($co{'committer_email'}) {
4530                                 print "  <email>" . esc_html($co{'committer_email'}) . "</email>\n";
4531                         }
4532                         print "</contributor>\n" .
4533                               "<published>$cd{'iso-8601'}</published>\n" .
4534                               "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
4535                               "<id>$co_url</id>\n" .
4536                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
4537                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
4538                 }
4539                 my $comment = $co{'comment'};
4540                 print "<pre>\n";
4541                 foreach my $line (@$comment) {
4542                         $line = esc_html($line);
4543                         print "$line\n";
4544                 }
4545                 print "</pre><ul>\n";
4546                 foreach my $difftree_line (@difftree) {
4547                         my %difftree = parse_difftree_raw_line($difftree_line);
4548                         next if !$difftree{'from_id'};
4550                         my $file = $difftree{'file'} || $difftree{'to_file'};
4552                         print "<li>" .
4553                               "[" .
4554                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
4555                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
4556                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
4557                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
4558                                       -title => "diff"}, 'D');
4559                         if ($have_blame) {
4560                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
4561                                                              file_name=>$file, hash_base=>$commit),
4562                                               -title => "blame"}, 'B');
4563                         }
4564                         # if this is not a feed of a file history
4565                         if (!defined $file_name || $file_name ne $file) {
4566                                 print $cgi->a({-href => href(-full=>1, action=>"history",
4567                                                              file_name=>$file, hash=>$commit),
4568                                               -title => "history"}, 'H');
4569                         }
4570                         $file = esc_path($file);
4571                         print "] ".
4572                               "$file</li>\n";
4573                 }
4574                 if ($format eq 'rss') {
4575                         print "</ul>]]>\n" .
4576                               "</content:encoded>\n" .
4577                               "</item>\n";
4578                 } elsif ($format eq 'atom') {
4579                         print "</ul>\n</div>\n" .
4580                               "</content>\n" .
4581                               "</entry>\n";
4582                 }
4583         }
4585         # end of feed
4586         if ($format eq 'rss') {
4587                 print "</channel>\n</rss>\n";
4588         }       elsif ($format eq 'atom') {
4589                 print "</feed>\n";
4590         }
4593 sub git_rss {
4594         git_feed('rss');
4597 sub git_atom {
4598         git_feed('atom');
4601 sub git_opml {
4602         my @list = git_get_projects_list();
4604         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
4605         print <<XML;
4606 <?xml version="1.0" encoding="utf-8"?>
4607 <opml version="1.0">
4608 <head>
4609   <title>$site_name OPML Export</title>
4610 </head>
4611 <body>
4612 <outline text="git RSS feeds">
4613 XML
4615         foreach my $pr (@list) {
4616                 my %proj = %$pr;
4617                 my $head = git_get_head_hash($proj{'path'});
4618                 if (!defined $head) {
4619                         next;
4620                 }
4621                 $git_dir = "$projectroot/$proj{'path'}";
4622                 my %co = parse_commit($head);
4623                 if (!%co) {
4624                         next;
4625                 }
4627                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
4628                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
4629                 my $html = "$my_url?p=$proj{'path'};a=summary";
4630                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
4631         }
4632         print <<XML;
4633 </outline>
4634 </body>
4635 </opml>
4636 XML