Code

a32a6b79c6fd0217e4dce87c3b54f758275f9d9e
[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{'blame'}{'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 the pickaxe search, which will list the commits that modified
132         # a given string in a file. This can be practical and quite faster
133         # alternative to 'blame', but still potentially CPU-intensive.
135         # To enable system wide have in $GITWEB_CONFIG
136         # $feature{'pickaxe'}{'default'} = [1];
137         # To have project specific config enable override in $GITWEB_CONFIG
138         # $feature{'pickaxe'}{'override'} = 1;
139         # and in project config gitweb.pickaxe = 0|1;
140         'pickaxe' => {
141                 'sub' => \&feature_pickaxe,
142                 'override' => 0,
143                 'default' => [1]},
145         # Make gitweb use an alternative format of the URLs which can be
146         # more readable and natural-looking: project name is embedded
147         # directly in the path and the query string contains other
148         # auxiliary information. All gitweb installations recognize
149         # URL in either format; this configures in which formats gitweb
150         # generates links.
152         # To enable system wide have in $GITWEB_CONFIG
153         # $feature{'pathinfo'}{'default'} = [1];
154         # Project specific override is not supported.
156         # Note that you will need to change the default location of CSS,
157         # favicon, logo and possibly other files to an absolute URL. Also,
158         # if gitweb.cgi serves as your indexfile, you will need to force
159         # $my_uri to contain the script name in your $GITWEB_CONFIG.
160         'pathinfo' => {
161                 'override' => 0,
162                 'default' => [0]},
164         # Make gitweb consider projects in project root subdirectories
165         # to be forks of existing projects. Given project $projname.git,
166         # projects matching $projname/*.git will not be shown in the main
167         # projects list, instead a '+' mark will be added to $projname
168         # there and a 'forks' view will be enabled for the project, listing
169         # all the forks. This feature is supported only if project list
170         # is taken from a directory, not file.
172         # To enable system wide have in $GITWEB_CONFIG
173         # $feature{'forks'}{'default'} = [1];
174         # Project specific override is not supported.
175         'forks' => {
176                 'override' => 0,
177                 'default' => [0]},
178 );
180 sub gitweb_check_feature {
181         my ($name) = @_;
182         return unless exists $feature{$name};
183         my ($sub, $override, @defaults) = (
184                 $feature{$name}{'sub'},
185                 $feature{$name}{'override'},
186                 @{$feature{$name}{'default'}});
187         if (!$override) { return @defaults; }
188         if (!defined $sub) {
189                 warn "feature $name is not overrideable";
190                 return @defaults;
191         }
192         return $sub->(@defaults);
195 sub feature_blame {
196         my ($val) = git_get_project_config('blame', '--bool');
198         if ($val eq 'true') {
199                 return 1;
200         } elsif ($val eq 'false') {
201                 return 0;
202         }
204         return $_[0];
207 sub feature_snapshot {
208         my ($ctype, $suffix, $command) = @_;
210         my ($val) = git_get_project_config('snapshot');
212         if ($val eq 'gzip') {
213                 return ('x-gzip', 'gz', 'gzip');
214         } elsif ($val eq 'bzip2') {
215                 return ('x-bzip2', 'bz2', 'bzip2');
216         } elsif ($val eq 'none') {
217                 return ();
218         }
220         return ($ctype, $suffix, $command);
223 sub gitweb_have_snapshot {
224         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
225         my $have_snapshot = (defined $ctype && defined $suffix);
227         return $have_snapshot;
230 sub feature_pickaxe {
231         my ($val) = git_get_project_config('pickaxe', '--bool');
233         if ($val eq 'true') {
234                 return (1);
235         } elsif ($val eq 'false') {
236                 return (0);
237         }
239         return ($_[0]);
242 # checking HEAD file with -e is fragile if the repository was
243 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
244 # and then pruned.
245 sub check_head_link {
246         my ($dir) = @_;
247         my $headfile = "$dir/HEAD";
248         return ((-e $headfile) ||
249                 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
252 sub check_export_ok {
253         my ($dir) = @_;
254         return (check_head_link($dir) &&
255                 (!$export_ok || -e "$dir/$export_ok"));
258 # rename detection options for git-diff and git-diff-tree
259 # - default is '-M', with the cost proportional to
260 #   (number of removed files) * (number of new files).
261 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
262 #   (number of changed files + number of removed files) * (number of new files)
263 # - even more costly is '-C', '--find-copies-harder' with cost
264 #   (number of files in the original tree) * (number of new files)
265 # - one might want to include '-B' option, e.g. '-B', '-M'
266 our @diff_opts = ('-M'); # taken from git_commit
268 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
269 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
271 # version of the core git binary
272 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
274 $projects_list ||= $projectroot;
276 # ======================================================================
277 # input validation and dispatch
278 our $action = $cgi->param('a');
279 if (defined $action) {
280         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
281                 die_error(undef, "Invalid action parameter");
282         }
285 # parameters which are pathnames
286 our $project = $cgi->param('p');
287 if (defined $project) {
288         if (!validate_pathname($project) ||
289             !(-d "$projectroot/$project") ||
290             !check_head_link("$projectroot/$project") ||
291             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
292             ($strict_export && !project_in_list($project))) {
293                 undef $project;
294                 die_error(undef, "No such project");
295         }
298 our $file_name = $cgi->param('f');
299 if (defined $file_name) {
300         if (!validate_pathname($file_name)) {
301                 die_error(undef, "Invalid file parameter");
302         }
305 our $file_parent = $cgi->param('fp');
306 if (defined $file_parent) {
307         if (!validate_pathname($file_parent)) {
308                 die_error(undef, "Invalid file parent parameter");
309         }
312 # parameters which are refnames
313 our $hash = $cgi->param('h');
314 if (defined $hash) {
315         if (!validate_refname($hash)) {
316                 die_error(undef, "Invalid hash parameter");
317         }
320 our $hash_parent = $cgi->param('hp');
321 if (defined $hash_parent) {
322         if (!validate_refname($hash_parent)) {
323                 die_error(undef, "Invalid hash parent parameter");
324         }
327 our $hash_base = $cgi->param('hb');
328 if (defined $hash_base) {
329         if (!validate_refname($hash_base)) {
330                 die_error(undef, "Invalid hash base parameter");
331         }
334 our $hash_parent_base = $cgi->param('hpb');
335 if (defined $hash_parent_base) {
336         if (!validate_refname($hash_parent_base)) {
337                 die_error(undef, "Invalid hash parent base parameter");
338         }
341 # other parameters
342 our $page = $cgi->param('pg');
343 if (defined $page) {
344         if ($page =~ m/[^0-9]/) {
345                 die_error(undef, "Invalid page parameter");
346         }
349 our $searchtext = $cgi->param('s');
350 if (defined $searchtext) {
351         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
352                 die_error(undef, "Invalid search parameter");
353         }
354         $searchtext = quotemeta $searchtext;
357 our $searchtype = $cgi->param('st');
358 if (defined $searchtype) {
359         if ($searchtype =~ m/[^a-z]/) {
360                 die_error(undef, "Invalid searchtype parameter");
361         }
364 # now read PATH_INFO and use it as alternative to parameters
365 sub evaluate_path_info {
366         return if defined $project;
367         my $path_info = $ENV{"PATH_INFO"};
368         return if !$path_info;
369         $path_info =~ s,^/+,,;
370         return if !$path_info;
371         # find which part of PATH_INFO is project
372         $project = $path_info;
373         $project =~ s,/+$,,;
374         while ($project && !check_head_link("$projectroot/$project")) {
375                 $project =~ s,/*[^/]*$,,;
376         }
377         # validate project
378         $project = validate_pathname($project);
379         if (!$project ||
380             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
381             ($strict_export && !project_in_list($project))) {
382                 undef $project;
383                 return;
384         }
385         # do not change any parameters if an action is given using the query string
386         return if $action;
387         $path_info =~ s,^$project/*,,;
388         my ($refname, $pathname) = split(/:/, $path_info, 2);
389         if (defined $pathname) {
390                 # we got "project.git/branch:filename" or "project.git/branch:dir/"
391                 # we could use git_get_type(branch:pathname), but it needs $git_dir
392                 $pathname =~ s,^/+,,;
393                 if (!$pathname || substr($pathname, -1) eq "/") {
394                         $action  ||= "tree";
395                         $pathname =~ s,/$,,;
396                 } else {
397                         $action  ||= "blob_plain";
398                 }
399                 $hash_base ||= validate_refname($refname);
400                 $file_name ||= validate_pathname($pathname);
401         } elsif (defined $refname) {
402                 # we got "project.git/branch"
403                 $action ||= "shortlog";
404                 $hash   ||= validate_refname($refname);
405         }
407 evaluate_path_info();
409 # path to the current git repository
410 our $git_dir;
411 $git_dir = "$projectroot/$project" if $project;
413 # dispatch
414 my %actions = (
415         "blame" => \&git_blame2,
416         "blobdiff" => \&git_blobdiff,
417         "blobdiff_plain" => \&git_blobdiff_plain,
418         "blob" => \&git_blob,
419         "blob_plain" => \&git_blob_plain,
420         "commitdiff" => \&git_commitdiff,
421         "commitdiff_plain" => \&git_commitdiff_plain,
422         "commit" => \&git_commit,
423         "forks" => \&git_forks,
424         "heads" => \&git_heads,
425         "history" => \&git_history,
426         "log" => \&git_log,
427         "rss" => \&git_rss,
428         "atom" => \&git_atom,
429         "search" => \&git_search,
430         "search_help" => \&git_search_help,
431         "shortlog" => \&git_shortlog,
432         "summary" => \&git_summary,
433         "tag" => \&git_tag,
434         "tags" => \&git_tags,
435         "tree" => \&git_tree,
436         "snapshot" => \&git_snapshot,
437         # those below don't need $project
438         "opml" => \&git_opml,
439         "project_list" => \&git_project_list,
440         "project_index" => \&git_project_index,
441 );
443 if (defined $project) {
444         $action ||= 'summary';
445 } else {
446         $action ||= 'project_list';
448 if (!defined($actions{$action})) {
449         die_error(undef, "Unknown action");
451 if ($action !~ m/^(opml|project_list|project_index)$/ &&
452     !$project) {
453         die_error(undef, "Project needed");
455 $actions{$action}->();
456 exit;
458 ## ======================================================================
459 ## action links
461 sub href(%) {
462         my %params = @_;
463         # default is to use -absolute url() i.e. $my_uri
464         my $href = $params{-full} ? $my_url : $my_uri;
466         # XXX: Warning: If you touch this, check the search form for updating,
467         # too.
469         my @mapping = (
470                 project => "p",
471                 action => "a",
472                 file_name => "f",
473                 file_parent => "fp",
474                 hash => "h",
475                 hash_parent => "hp",
476                 hash_base => "hb",
477                 hash_parent_base => "hpb",
478                 page => "pg",
479                 order => "o",
480                 searchtext => "s",
481                 searchtype => "st",
482         );
483         my %mapping = @mapping;
485         $params{'project'} = $project unless exists $params{'project'};
487         my ($use_pathinfo) = gitweb_check_feature('pathinfo');
488         if ($use_pathinfo) {
489                 # use PATH_INFO for project name
490                 $href .= "/$params{'project'}" if defined $params{'project'};
491                 delete $params{'project'};
493                 # Summary just uses the project path URL
494                 if (defined $params{'action'} && $params{'action'} eq 'summary') {
495                         delete $params{'action'};
496                 }
497         }
499         # now encode the parameters explicitly
500         my @result = ();
501         for (my $i = 0; $i < @mapping; $i += 2) {
502                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
503                 if (defined $params{$name}) {
504                         push @result, $symbol . "=" . esc_param($params{$name});
505                 }
506         }
507         $href .= "?" . join(';', @result) if scalar @result;
509         return $href;
513 ## ======================================================================
514 ## validation, quoting/unquoting and escaping
516 sub validate_pathname {
517         my $input = shift || return undef;
519         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
520         # at the beginning, at the end, and between slashes.
521         # also this catches doubled slashes
522         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
523                 return undef;
524         }
525         # no null characters
526         if ($input =~ m!\0!) {
527                 return undef;
528         }
529         return $input;
532 sub validate_refname {
533         my $input = shift || return undef;
535         # textual hashes are O.K.
536         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
537                 return $input;
538         }
539         # it must be correct pathname
540         $input = validate_pathname($input)
541                 or return undef;
542         # restrictions on ref name according to git-check-ref-format
543         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
544                 return undef;
545         }
546         return $input;
549 # very thin wrapper for decode("utf8", $str, Encode::FB_DEFAULT);
550 sub to_utf8 {
551         my $str = shift;
552         return decode("utf8", $str, Encode::FB_DEFAULT);
555 # quote unsafe chars, but keep the slash, even when it's not
556 # correct, but quoted slashes look too horrible in bookmarks
557 sub esc_param {
558         my $str = shift;
559         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
560         $str =~ s/\+/%2B/g;
561         $str =~ s/ /\+/g;
562         return $str;
565 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
566 sub esc_url {
567         my $str = shift;
568         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
569         $str =~ s/\+/%2B/g;
570         $str =~ s/ /\+/g;
571         return $str;
574 # replace invalid utf8 character with SUBSTITUTION sequence
575 sub esc_html ($;%) {
576         my $str = shift;
577         my %opts = @_;
579         $str = to_utf8($str);
580         $str = escapeHTML($str);
581         if ($opts{'-nbsp'}) {
582                 $str =~ s/ /&nbsp;/g;
583         }
584         $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
585         return $str;
588 # Make control characterss "printable".
589 sub quot_cec {
590         my $cntrl = shift;
591         my %es = ( # character escape codes, aka escape sequences
592                    "\t" => '\t',   # tab            (HT)
593                    "\n" => '\n',   # line feed      (LF)
594                    "\r" => '\r',   # carrige return (CR)
595                    "\f" => '\f',   # form feed      (FF)
596                    "\b" => '\b',   # backspace      (BS)
597                    "\a" => '\a',   # alarm (bell)   (BEL)
598                    "\e" => '\e',   # escape         (ESC)
599                    "\013" => '\v', # vertical tab   (VT)
600                    "\000" => '\0', # nul character  (NUL)
601                    );
602         my $chr = ( (exists $es{$cntrl})
603                     ? $es{$cntrl}
604                     : sprintf('\%03o', ord($cntrl)) );
605         return "<span class=\"cntrl\">$chr</span>";
608 # Alternatively use unicode control pictures codepoints.
609 sub quot_upr {
610         my $cntrl = shift;
611         my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
612         return "<span class=\"cntrl\">$chr</span>";
615 # quote control characters and escape filename to HTML
616 sub esc_path {
617         my $str = shift;
619         $str = esc_html($str);
620         $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
621         return $str;
624 # git may return quoted and escaped filenames
625 sub unquote {
626         my $str = shift;
628         sub unq {
629                 my $seq = shift;
630                 my %es = ( # character escape codes, aka escape sequences
631                         't' => "\t",   # tab            (HT, TAB)
632                         'n' => "\n",   # newline        (NL)
633                         'r' => "\r",   # return         (CR)
634                         'f' => "\f",   # form feed      (FF)
635                         'b' => "\b",   # backspace      (BS)
636                         'a' => "\a",   # alarm (bell)   (BEL)
637                         'e' => "\e",   # escape         (ESC)
638                         'v' => "\013", # vertical tab   (VT)
639                 );
641                 if ($seq =~ m/^[0-7]{1,3}$/) {
642                         # octal char sequence
643                         return chr(oct($seq));
644                 } elsif (exists $es{$seq}) {
645                         # C escape sequence, aka character escape code
646                         return $es{$seq}
647                 }
648                 # quoted ordinary character
649                 return $seq;
650         }
652         if ($str =~ m/^"(.*)"$/) {
653                 # needs unquoting
654                 $str = $1;
655                 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
656         }
657         return $str;
660 # escape tabs (convert tabs to spaces)
661 sub untabify {
662         my $line = shift;
664         while ((my $pos = index($line, "\t")) != -1) {
665                 if (my $count = (8 - ($pos % 8))) {
666                         my $spaces = ' ' x $count;
667                         $line =~ s/\t/$spaces/;
668                 }
669         }
671         return $line;
674 sub project_in_list {
675         my $project = shift;
676         my @list = git_get_projects_list();
677         return @list && scalar(grep { $_->{'path'} eq $project } @list);
680 ## ----------------------------------------------------------------------
681 ## HTML aware string manipulation
683 sub chop_str {
684         my $str = shift;
685         my $len = shift;
686         my $add_len = shift || 10;
688         # allow only $len chars, but don't cut a word if it would fit in $add_len
689         # if it doesn't fit, cut it if it's still longer than the dots we would add
690         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
691         my $body = $1;
692         my $tail = $2;
693         if (length($tail) > 4) {
694                 $tail = " ...";
695                 $body =~ s/&[^;]*$//; # remove chopped character entities
696         }
697         return "$body$tail";
700 ## ----------------------------------------------------------------------
701 ## functions returning short strings
703 # CSS class for given age value (in seconds)
704 sub age_class {
705         my $age = shift;
707         if ($age < 60*60*2) {
708                 return "age0";
709         } elsif ($age < 60*60*24*2) {
710                 return "age1";
711         } else {
712                 return "age2";
713         }
716 # convert age in seconds to "nn units ago" string
717 sub age_string {
718         my $age = shift;
719         my $age_str;
721         if ($age > 60*60*24*365*2) {
722                 $age_str = (int $age/60/60/24/365);
723                 $age_str .= " years ago";
724         } elsif ($age > 60*60*24*(365/12)*2) {
725                 $age_str = int $age/60/60/24/(365/12);
726                 $age_str .= " months ago";
727         } elsif ($age > 60*60*24*7*2) {
728                 $age_str = int $age/60/60/24/7;
729                 $age_str .= " weeks ago";
730         } elsif ($age > 60*60*24*2) {
731                 $age_str = int $age/60/60/24;
732                 $age_str .= " days ago";
733         } elsif ($age > 60*60*2) {
734                 $age_str = int $age/60/60;
735                 $age_str .= " hours ago";
736         } elsif ($age > 60*2) {
737                 $age_str = int $age/60;
738                 $age_str .= " min ago";
739         } elsif ($age > 2) {
740                 $age_str = int $age;
741                 $age_str .= " sec ago";
742         } else {
743                 $age_str .= " right now";
744         }
745         return $age_str;
748 # convert file mode in octal to symbolic file mode string
749 sub mode_str {
750         my $mode = oct shift;
752         if (S_ISDIR($mode & S_IFMT)) {
753                 return 'drwxr-xr-x';
754         } elsif (S_ISLNK($mode)) {
755                 return 'lrwxrwxrwx';
756         } elsif (S_ISREG($mode)) {
757                 # git cares only about the executable bit
758                 if ($mode & S_IXUSR) {
759                         return '-rwxr-xr-x';
760                 } else {
761                         return '-rw-r--r--';
762                 };
763         } else {
764                 return '----------';
765         }
768 # convert file mode in octal to file type string
769 sub file_type {
770         my $mode = shift;
772         if ($mode !~ m/^[0-7]+$/) {
773                 return $mode;
774         } else {
775                 $mode = oct $mode;
776         }
778         if (S_ISDIR($mode & S_IFMT)) {
779                 return "directory";
780         } elsif (S_ISLNK($mode)) {
781                 return "symlink";
782         } elsif (S_ISREG($mode)) {
783                 return "file";
784         } else {
785                 return "unknown";
786         }
789 # convert file mode in octal to file type description string
790 sub file_type_long {
791         my $mode = shift;
793         if ($mode !~ m/^[0-7]+$/) {
794                 return $mode;
795         } else {
796                 $mode = oct $mode;
797         }
799         if (S_ISDIR($mode & S_IFMT)) {
800                 return "directory";
801         } elsif (S_ISLNK($mode)) {
802                 return "symlink";
803         } elsif (S_ISREG($mode)) {
804                 if ($mode & S_IXUSR) {
805                         return "executable";
806                 } else {
807                         return "file";
808                 };
809         } else {
810                 return "unknown";
811         }
815 ## ----------------------------------------------------------------------
816 ## functions returning short HTML fragments, or transforming HTML fragments
817 ## which don't beling to other sections
819 # format line of commit message.
820 sub format_log_line_html {
821         my $line = shift;
823         $line = esc_html($line, -nbsp=>1);
824         if ($line =~ m/([0-9a-fA-F]{40})/) {
825                 my $hash_text = $1;
826                 if (git_get_type($hash_text) eq "commit") {
827                         my $link =
828                                 $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
829                                         -class => "text"}, $hash_text);
830                         $line =~ s/$hash_text/$link/;
831                 }
832         }
833         return $line;
836 # format marker of refs pointing to given object
837 sub format_ref_marker {
838         my ($refs, $id) = @_;
839         my $markers = '';
841         if (defined $refs->{$id}) {
842                 foreach my $ref (@{$refs->{$id}}) {
843                         my ($type, $name) = qw();
844                         # e.g. tags/v2.6.11 or heads/next
845                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
846                                 $type = $1;
847                                 $name = $2;
848                         } else {
849                                 $type = "ref";
850                                 $name = $ref;
851                         }
853                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
854                 }
855         }
857         if ($markers) {
858                 return ' <span class="refs">'. $markers . '</span>';
859         } else {
860                 return "";
861         }
864 # format, perhaps shortened and with markers, title line
865 sub format_subject_html {
866         my ($long, $short, $href, $extra) = @_;
867         $extra = '' unless defined($extra);
869         if (length($short) < length($long)) {
870                 return $cgi->a({-href => $href, -class => "list subject",
871                                 -title => to_utf8($long)},
872                        esc_html($short) . $extra);
873         } else {
874                 return $cgi->a({-href => $href, -class => "list subject"},
875                        esc_html($long)  . $extra);
876         }
879 # format patch (diff) line (rather not to be used for diff headers)
880 sub format_diff_line {
881         my $line = shift;
882         my ($from, $to) = @_;
883         my $char = substr($line, 0, 1);
884         my $diff_class = "";
886         chomp $line;
888         if ($char eq '+') {
889                 $diff_class = " add";
890         } elsif ($char eq "-") {
891                 $diff_class = " rem";
892         } elsif ($char eq "@") {
893                 $diff_class = " chunk_header";
894         } elsif ($char eq "\\") {
895                 $diff_class = " incomplete";
896         }
897         $line = untabify($line);
898         if ($from && $to && $line =~ m/^\@{2} /) {
899                 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
900                         $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
902                 $from_lines = 0 unless defined $from_lines;
903                 $to_lines   = 0 unless defined $to_lines;
905                 if ($from->{'href'}) {
906                         $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
907                                              -class=>"list"}, $from_text);
908                 }
909                 if ($to->{'href'}) {
910                         $to_text   = $cgi->a({-href=>"$to->{'href'}#l$to_start",
911                                              -class=>"list"}, $to_text);
912                 }
913                 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
914                         "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
915                 return "<div class=\"diff$diff_class\">$line</div>\n";
916         }
917         return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
920 ## ----------------------------------------------------------------------
921 ## git utility subroutines, invoking git commands
923 # returns path to the core git executable and the --git-dir parameter as list
924 sub git_cmd {
925         return $GIT, '--git-dir='.$git_dir;
928 # returns path to the core git executable and the --git-dir parameter as string
929 sub git_cmd_str {
930         return join(' ', git_cmd());
933 # get HEAD ref of given project as hash
934 sub git_get_head_hash {
935         my $project = shift;
936         my $o_git_dir = $git_dir;
937         my $retval = undef;
938         $git_dir = "$projectroot/$project";
939         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
940                 my $head = <$fd>;
941                 close $fd;
942                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
943                         $retval = $1;
944                 }
945         }
946         if (defined $o_git_dir) {
947                 $git_dir = $o_git_dir;
948         }
949         return $retval;
952 # get type of given object
953 sub git_get_type {
954         my $hash = shift;
956         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
957         my $type = <$fd>;
958         close $fd or return;
959         chomp $type;
960         return $type;
963 sub git_get_project_config {
964         my ($key, $type) = @_;
966         return unless ($key);
967         $key =~ s/^gitweb\.//;
968         return if ($key =~ m/\W/);
970         my @x = (git_cmd(), 'repo-config');
971         if (defined $type) { push @x, $type; }
972         push @x, "--get";
973         push @x, "gitweb.$key";
974         my $val = qx(@x);
975         chomp $val;
976         return ($val);
979 # get hash of given path at given ref
980 sub git_get_hash_by_path {
981         my $base = shift;
982         my $path = shift || return undef;
983         my $type = shift;
985         $path =~ s,/+$,,;
987         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
988                 or die_error(undef, "Open git-ls-tree failed");
989         my $line = <$fd>;
990         close $fd or return undef;
992         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
993         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
994         if (defined $type && $type ne $2) {
995                 # type doesn't match
996                 return undef;
997         }
998         return $3;
1001 ## ......................................................................
1002 ## git utility functions, directly accessing git repository
1004 sub git_get_project_description {
1005         my $path = shift;
1007         open my $fd, "$projectroot/$path/description" or return undef;
1008         my $descr = <$fd>;
1009         close $fd;
1010         chomp $descr;
1011         return $descr;
1014 sub git_get_project_url_list {
1015         my $path = shift;
1017         open my $fd, "$projectroot/$path/cloneurl" or return;
1018         my @git_project_url_list = map { chomp; $_ } <$fd>;
1019         close $fd;
1021         return wantarray ? @git_project_url_list : \@git_project_url_list;
1024 sub git_get_projects_list {
1025         my ($filter) = @_;
1026         my @list;
1028         $filter ||= '';
1029         $filter =~ s/\.git$//;
1031         if (-d $projects_list) {
1032                 # search in directory
1033                 my $dir = $projects_list . ($filter ? "/$filter" : '');
1034                 # remove the trailing "/"
1035                 $dir =~ s!/+$!!;
1036                 my $pfxlen = length("$dir");
1038                 my ($check_forks) = gitweb_check_feature('forks');
1040                 File::Find::find({
1041                         follow_fast => 1, # follow symbolic links
1042                         dangling_symlinks => 0, # ignore dangling symlinks, silently
1043                         wanted => sub {
1044                                 # skip project-list toplevel, if we get it.
1045                                 return if (m!^[/.]$!);
1046                                 # only directories can be git repositories
1047                                 return unless (-d $_);
1049                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
1050                                 # we check related file in $projectroot
1051                                 if ($check_forks and $subdir =~ m#/.#) {
1052                                         $File::Find::prune = 1;
1053                                 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1054                                         push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1055                                         $File::Find::prune = 1;
1056                                 }
1057                         },
1058                 }, "$dir");
1060         } elsif (-f $projects_list) {
1061                 # read from file(url-encoded):
1062                 # 'git%2Fgit.git Linus+Torvalds'
1063                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1064                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1065                 open my ($fd), $projects_list or return;
1066                 while (my $line = <$fd>) {
1067                         chomp $line;
1068                         my ($path, $owner) = split ' ', $line;
1069                         $path = unescape($path);
1070                         $owner = unescape($owner);
1071                         if (!defined $path) {
1072                                 next;
1073                         }
1074                         if ($filter ne '') {
1075                                 # looking for forks;
1076                                 my $pfx = substr($path, 0, length($filter));
1077                                 if ($pfx ne $filter) {
1078                                         next;
1079                                 }
1080                                 my $sfx = substr($path, length($filter));
1081                                 if ($sfx !~ /^\/.*\.git$/) {
1082                                         next;
1083                                 }
1084                         }
1085                         if (check_export_ok("$projectroot/$path")) {
1086                                 my $pr = {
1087                                         path => $path,
1088                                         owner => to_utf8($owner),
1089                                 };
1090                                 push @list, $pr
1091                         }
1092                 }
1093                 close $fd;
1094         }
1095         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
1096         return @list;
1099 sub git_get_project_owner {
1100         my $project = shift;
1101         my $owner;
1103         return undef unless $project;
1105         # read from file (url-encoded):
1106         # 'git%2Fgit.git Linus+Torvalds'
1107         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1108         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1109         if (-f $projects_list) {
1110                 open (my $fd , $projects_list);
1111                 while (my $line = <$fd>) {
1112                         chomp $line;
1113                         my ($pr, $ow) = split ' ', $line;
1114                         $pr = unescape($pr);
1115                         $ow = unescape($ow);
1116                         if ($pr eq $project) {
1117                                 $owner = to_utf8($ow);
1118                                 last;
1119                         }
1120                 }
1121                 close $fd;
1122         }
1123         if (!defined $owner) {
1124                 $owner = get_file_owner("$projectroot/$project");
1125         }
1127         return $owner;
1130 sub git_get_last_activity {
1131         my ($path) = @_;
1132         my $fd;
1134         $git_dir = "$projectroot/$path";
1135         open($fd, "-|", git_cmd(), 'for-each-ref',
1136              '--format=%(refname) %(committer)',
1137              '--sort=-committerdate',
1138              'refs/heads') or return;
1139         my $most_recent = <$fd>;
1140         close $fd or return;
1141         if ($most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1142                 my $timestamp = $1;
1143                 my $age = time - $timestamp;
1144                 return ($age, age_string($age));
1145         }
1148 sub git_get_references {
1149         my $type = shift || "";
1150         my %refs;
1151         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
1152         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
1153         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1154                 or return;
1156         while (my $line = <$fd>) {
1157                 chomp $line;
1158                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
1159                         if (defined $refs{$1}) {
1160                                 push @{$refs{$1}}, $2;
1161                         } else {
1162                                 $refs{$1} = [ $2 ];
1163                         }
1164                 }
1165         }
1166         close $fd or return;
1167         return \%refs;
1170 sub git_get_rev_name_tags {
1171         my $hash = shift || return undef;
1173         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1174                 or return;
1175         my $name_rev = <$fd>;
1176         close $fd;
1178         if ($name_rev =~ m|^$hash tags/(.*)$|) {
1179                 return $1;
1180         } else {
1181                 # catches also '$hash undefined' output
1182                 return undef;
1183         }
1186 ## ----------------------------------------------------------------------
1187 ## parse to hash functions
1189 sub parse_date {
1190         my $epoch = shift;
1191         my $tz = shift || "-0000";
1193         my %date;
1194         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1195         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1196         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1197         $date{'hour'} = $hour;
1198         $date{'minute'} = $min;
1199         $date{'mday'} = $mday;
1200         $date{'day'} = $days[$wday];
1201         $date{'month'} = $months[$mon];
1202         $date{'rfc2822'}   = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1203                              $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1204         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1205                              $mday, $months[$mon], $hour ,$min;
1206         $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1207                              1900+$year, $mon, $mday, $hour ,$min, $sec;
1209         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1210         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1211         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1212         $date{'hour_local'} = $hour;
1213         $date{'minute_local'} = $min;
1214         $date{'tz_local'} = $tz;
1215         $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1216                                   1900+$year, $mon+1, $mday,
1217                                   $hour, $min, $sec, $tz);
1218         return %date;
1221 sub parse_tag {
1222         my $tag_id = shift;
1223         my %tag;
1224         my @comment;
1226         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1227         $tag{'id'} = $tag_id;
1228         while (my $line = <$fd>) {
1229                 chomp $line;
1230                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1231                         $tag{'object'} = $1;
1232                 } elsif ($line =~ m/^type (.+)$/) {
1233                         $tag{'type'} = $1;
1234                 } elsif ($line =~ m/^tag (.+)$/) {
1235                         $tag{'name'} = $1;
1236                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1237                         $tag{'author'} = $1;
1238                         $tag{'epoch'} = $2;
1239                         $tag{'tz'} = $3;
1240                 } elsif ($line =~ m/--BEGIN/) {
1241                         push @comment, $line;
1242                         last;
1243                 } elsif ($line eq "") {
1244                         last;
1245                 }
1246         }
1247         push @comment, <$fd>;
1248         $tag{'comment'} = \@comment;
1249         close $fd or return;
1250         if (!defined $tag{'name'}) {
1251                 return
1252         };
1253         return %tag
1256 sub parse_commit {
1257         my $commit_id = shift;
1258         my $commit_text = shift;
1260         my @commit_lines;
1261         my %co;
1263         if (defined $commit_text) {
1264                 @commit_lines = @$commit_text;
1265         } else {
1266                 local $/ = "\0";
1267                 open my $fd, "-|", git_cmd(), "rev-list",
1268                         "--header", "--parents", "--max-count=1",
1269                         $commit_id, "--"
1270                         or return;
1271                 @commit_lines = split '\n', <$fd>;
1272                 close $fd or return;
1273                 pop @commit_lines;
1274         }
1275         my $header = shift @commit_lines;
1276         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1277                 return;
1278         }
1279         ($co{'id'}, my @parents) = split ' ', $header;
1280         $co{'parents'} = \@parents;
1281         $co{'parent'} = $parents[0];
1282         while (my $line = shift @commit_lines) {
1283                 last if $line eq "\n";
1284                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1285                         $co{'tree'} = $1;
1286                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1287                         $co{'author'} = $1;
1288                         $co{'author_epoch'} = $2;
1289                         $co{'author_tz'} = $3;
1290                         if ($co{'author'} =~ m/^([^<]+) </) {
1291                                 $co{'author_name'} = $1;
1292                         } else {
1293                                 $co{'author_name'} = $co{'author'};
1294                         }
1295                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1296                         $co{'committer'} = $1;
1297                         $co{'committer_epoch'} = $2;
1298                         $co{'committer_tz'} = $3;
1299                         $co{'committer_name'} = $co{'committer'};
1300                         $co{'committer_name'} =~ s/ <.*//;
1301                 }
1302         }
1303         if (!defined $co{'tree'}) {
1304                 return;
1305         };
1307         foreach my $title (@commit_lines) {
1308                 $title =~ s/^    //;
1309                 if ($title ne "") {
1310                         $co{'title'} = chop_str($title, 80, 5);
1311                         # remove leading stuff of merges to make the interesting part visible
1312                         if (length($title) > 50) {
1313                                 $title =~ s/^Automatic //;
1314                                 $title =~ s/^merge (of|with) /Merge ... /i;
1315                                 if (length($title) > 50) {
1316                                         $title =~ s/(http|rsync):\/\///;
1317                                 }
1318                                 if (length($title) > 50) {
1319                                         $title =~ s/(master|www|rsync)\.//;
1320                                 }
1321                                 if (length($title) > 50) {
1322                                         $title =~ s/kernel.org:?//;
1323                                 }
1324                                 if (length($title) > 50) {
1325                                         $title =~ s/\/pub\/scm//;
1326                                 }
1327                         }
1328                         $co{'title_short'} = chop_str($title, 50, 5);
1329                         last;
1330                 }
1331         }
1332         if ($co{'title'} eq "") {
1333                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1334         }
1335         # remove added spaces
1336         foreach my $line (@commit_lines) {
1337                 $line =~ s/^    //;
1338         }
1339         $co{'comment'} = \@commit_lines;
1341         my $age = time - $co{'committer_epoch'};
1342         $co{'age'} = $age;
1343         $co{'age_string'} = age_string($age);
1344         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1345         if ($age > 60*60*24*7*2) {
1346                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1347                 $co{'age_string_age'} = $co{'age_string'};
1348         } else {
1349                 $co{'age_string_date'} = $co{'age_string'};
1350                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1351         }
1352         return %co;
1355 # parse ref from ref_file, given by ref_id, with given type
1356 sub parse_ref {
1357         my $ref_file = shift;
1358         my $ref_id = shift;
1359         my $type = shift || git_get_type($ref_id);
1360         my %ref_item;
1362         $ref_item{'type'} = $type;
1363         $ref_item{'id'} = $ref_id;
1364         $ref_item{'epoch'} = 0;
1365         $ref_item{'age'} = "unknown";
1366         if ($type eq "tag") {
1367                 my %tag = parse_tag($ref_id);
1368                 $ref_item{'comment'} = $tag{'comment'};
1369                 if ($tag{'type'} eq "commit") {
1370                         my %co = parse_commit($tag{'object'});
1371                         $ref_item{'epoch'} = $co{'committer_epoch'};
1372                         $ref_item{'age'} = $co{'age_string'};
1373                 } elsif (defined($tag{'epoch'})) {
1374                         my $age = time - $tag{'epoch'};
1375                         $ref_item{'epoch'} = $tag{'epoch'};
1376                         $ref_item{'age'} = age_string($age);
1377                 }
1378                 $ref_item{'reftype'} = $tag{'type'};
1379                 $ref_item{'name'} = $tag{'name'};
1380                 $ref_item{'refid'} = $tag{'object'};
1381         } elsif ($type eq "commit"){
1382                 my %co = parse_commit($ref_id);
1383                 $ref_item{'reftype'} = "commit";
1384                 $ref_item{'name'} = $ref_file;
1385                 $ref_item{'title'} = $co{'title'};
1386                 $ref_item{'refid'} = $ref_id;
1387                 $ref_item{'epoch'} = $co{'committer_epoch'};
1388                 $ref_item{'age'} = $co{'age_string'};
1389         } else {
1390                 $ref_item{'reftype'} = $type;
1391                 $ref_item{'name'} = $ref_file;
1392                 $ref_item{'refid'} = $ref_id;
1393         }
1395         return %ref_item;
1398 # parse line of git-diff-tree "raw" output
1399 sub parse_difftree_raw_line {
1400         my $line = shift;
1401         my %res;
1403         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1404         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1405         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1406                 $res{'from_mode'} = $1;
1407                 $res{'to_mode'} = $2;
1408                 $res{'from_id'} = $3;
1409                 $res{'to_id'} = $4;
1410                 $res{'status'} = $5;
1411                 $res{'similarity'} = $6;
1412                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1413                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1414                 } else {
1415                         $res{'file'} = unquote($7);
1416                 }
1417         }
1418         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1419         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1420                 $res{'commit'} = $1;
1421         }
1423         return wantarray ? %res : \%res;
1426 # parse line of git-ls-tree output
1427 sub parse_ls_tree_line ($;%) {
1428         my $line = shift;
1429         my %opts = @_;
1430         my %res;
1432         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1433         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
1435         $res{'mode'} = $1;
1436         $res{'type'} = $2;
1437         $res{'hash'} = $3;
1438         if ($opts{'-z'}) {
1439                 $res{'name'} = $4;
1440         } else {
1441                 $res{'name'} = unquote($4);
1442         }
1444         return wantarray ? %res : \%res;
1447 ## ......................................................................
1448 ## parse to array of hashes functions
1450 sub git_get_heads_list {
1451         my $limit = shift;
1452         my @headslist;
1454         open my $fd, '-|', git_cmd(), 'for-each-ref',
1455                 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
1456                 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
1457                 'refs/heads'
1458                 or return;
1459         while (my $line = <$fd>) {
1460                 my %ref_item;
1462                 chomp $line;
1463                 my ($refinfo, $committerinfo) = split(/\0/, $line);
1464                 my ($hash, $name, $title) = split(' ', $refinfo, 3);
1465                 my ($committer, $epoch, $tz) =
1466                         ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
1467                 $name =~ s!^refs/heads/!!;
1469                 $ref_item{'name'}  = $name;
1470                 $ref_item{'id'}    = $hash;
1471                 $ref_item{'title'} = $title || '(no commit message)';
1472                 $ref_item{'epoch'} = $epoch;
1473                 if ($epoch) {
1474                         $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1475                 } else {
1476                         $ref_item{'age'} = "unknown";
1477                 }
1479                 push @headslist, \%ref_item;
1480         }
1481         close $fd;
1483         return wantarray ? @headslist : \@headslist;
1486 sub git_get_tags_list {
1487         my $limit = shift;
1488         my @tagslist;
1490         open my $fd, '-|', git_cmd(), 'for-each-ref',
1491                 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
1492                 '--format=%(objectname) %(objecttype) %(refname) '.
1493                 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
1494                 'refs/tags'
1495                 or return;
1496         while (my $line = <$fd>) {
1497                 my %ref_item;
1499                 chomp $line;
1500                 my ($refinfo, $creatorinfo) = split(/\0/, $line);
1501                 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
1502                 my ($creator, $epoch, $tz) =
1503                         ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
1504                 $name =~ s!^refs/tags/!!;
1506                 $ref_item{'type'} = $type;
1507                 $ref_item{'id'} = $id;
1508                 $ref_item{'name'} = $name;
1509                 if ($type eq "tag") {
1510                         $ref_item{'subject'} = $title;
1511                         $ref_item{'reftype'} = $reftype;
1512                         $ref_item{'refid'}   = $refid;
1513                 } else {
1514                         $ref_item{'reftype'} = $type;
1515                         $ref_item{'refid'}   = $id;
1516                 }
1518                 if ($type eq "tag" || $type eq "commit") {
1519                         $ref_item{'epoch'} = $epoch;
1520                         if ($epoch) {
1521                                 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
1522                         } else {
1523                                 $ref_item{'age'} = "unknown";
1524                         }
1525                 }
1527                 push @tagslist, \%ref_item;
1528         }
1529         close $fd;
1531         return wantarray ? @tagslist : \@tagslist;
1534 ## ----------------------------------------------------------------------
1535 ## filesystem-related functions
1537 sub get_file_owner {
1538         my $path = shift;
1540         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1541         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1542         if (!defined $gcos) {
1543                 return undef;
1544         }
1545         my $owner = $gcos;
1546         $owner =~ s/[,;].*$//;
1547         return to_utf8($owner);
1550 ## ......................................................................
1551 ## mimetype related functions
1553 sub mimetype_guess_file {
1554         my $filename = shift;
1555         my $mimemap = shift;
1556         -r $mimemap or return undef;
1558         my %mimemap;
1559         open(MIME, $mimemap) or return undef;
1560         while (<MIME>) {
1561                 next if m/^#/; # skip comments
1562                 my ($mime, $exts) = split(/\t+/);
1563                 if (defined $exts) {
1564                         my @exts = split(/\s+/, $exts);
1565                         foreach my $ext (@exts) {
1566                                 $mimemap{$ext} = $mime;
1567                         }
1568                 }
1569         }
1570         close(MIME);
1572         $filename =~ /\.([^.]*)$/;
1573         return $mimemap{$1};
1576 sub mimetype_guess {
1577         my $filename = shift;
1578         my $mime;
1579         $filename =~ /\./ or return undef;
1581         if ($mimetypes_file) {
1582                 my $file = $mimetypes_file;
1583                 if ($file !~ m!^/!) { # if it is relative path
1584                         # it is relative to project
1585                         $file = "$projectroot/$project/$file";
1586                 }
1587                 $mime = mimetype_guess_file($filename, $file);
1588         }
1589         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1590         return $mime;
1593 sub blob_mimetype {
1594         my $fd = shift;
1595         my $filename = shift;
1597         if ($filename) {
1598                 my $mime = mimetype_guess($filename);
1599                 $mime and return $mime;
1600         }
1602         # just in case
1603         return $default_blob_plain_mimetype unless $fd;
1605         if (-T $fd) {
1606                 return 'text/plain' .
1607                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1608         } elsif (! $filename) {
1609                 return 'application/octet-stream';
1610         } elsif ($filename =~ m/\.png$/i) {
1611                 return 'image/png';
1612         } elsif ($filename =~ m/\.gif$/i) {
1613                 return 'image/gif';
1614         } elsif ($filename =~ m/\.jpe?g$/i) {
1615                 return 'image/jpeg';
1616         } else {
1617                 return 'application/octet-stream';
1618         }
1621 ## ======================================================================
1622 ## functions printing HTML: header, footer, error page
1624 sub git_header_html {
1625         my $status = shift || "200 OK";
1626         my $expires = shift;
1628         my $title = "$site_name";
1629         if (defined $project) {
1630                 $title .= " - $project";
1631                 if (defined $action) {
1632                         $title .= "/$action";
1633                         if (defined $file_name) {
1634                                 $title .= " - " . esc_path($file_name);
1635                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1636                                         $title .= "/";
1637                                 }
1638                         }
1639                 }
1640         }
1641         my $content_type;
1642         # require explicit support from the UA if we are to send the page as
1643         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1644         # we have to do this because MSIE sometimes globs '*/*', pretending to
1645         # support xhtml+xml but choking when it gets what it asked for.
1646         if (defined $cgi->http('HTTP_ACCEPT') &&
1647             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1648             $cgi->Accept('application/xhtml+xml') != 0) {
1649                 $content_type = 'application/xhtml+xml';
1650         } else {
1651                 $content_type = 'text/html';
1652         }
1653         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1654                            -status=> $status, -expires => $expires);
1655         print <<EOF;
1656 <?xml version="1.0" encoding="utf-8"?>
1657 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1658 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1659 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1660 <!-- git core binaries version $git_version -->
1661 <head>
1662 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1663 <meta name="generator" content="gitweb/$version git/$git_version"/>
1664 <meta name="robots" content="index, nofollow"/>
1665 <title>$title</title>
1666 EOF
1667 # print out each stylesheet that exist
1668         if (defined $stylesheet) {
1669 #provides backwards capability for those people who define style sheet in a config file
1670                 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1671         } else {
1672                 foreach my $stylesheet (@stylesheets) {
1673                         next unless $stylesheet;
1674                         print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
1675                 }
1676         }
1677         if (defined $project) {
1678                 printf('<link rel="alternate" title="%s log RSS feed" '.
1679                        'href="%s" type="application/rss+xml" />'."\n",
1680                        esc_param($project), href(action=>"rss"));
1681                 printf('<link rel="alternate" title="%s log Atom feed" '.
1682                        'href="%s" type="application/atom+xml" />'."\n",
1683                        esc_param($project), href(action=>"atom"));
1684         } else {
1685                 printf('<link rel="alternate" title="%s projects list" '.
1686                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1687                        $site_name, href(project=>undef, action=>"project_index"));
1688                 printf('<link rel="alternate" title="%s projects feeds" '.
1689                        'href="%s" type="text/x-opml"/>'."\n",
1690                        $site_name, href(project=>undef, action=>"opml"));
1691         }
1692         if (defined $favicon) {
1693                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1694         }
1696         print "</head>\n" .
1697               "<body>\n";
1699         if (-f $site_header) {
1700                 open (my $fd, $site_header);
1701                 print <$fd>;
1702                 close $fd;
1703         }
1705         print "<div class=\"page_header\">\n" .
1706               $cgi->a({-href => esc_url($logo_url),
1707                        -title => $logo_label},
1708                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1709         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1710         if (defined $project) {
1711                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1712                 if (defined $action) {
1713                         print " / $action";
1714                 }
1715                 print "\n";
1716                 if (!defined $searchtext) {
1717                         $searchtext = "";
1718                 }
1719                 my $search_hash;
1720                 if (defined $hash_base) {
1721                         $search_hash = $hash_base;
1722                 } elsif (defined $hash) {
1723                         $search_hash = $hash;
1724                 } else {
1725                         $search_hash = "HEAD";
1726                 }
1727                 $cgi->param("a", "search");
1728                 $cgi->param("h", $search_hash);
1729                 $cgi->param("p", $project);
1730                 print $cgi->startform(-method => "get", -action => $my_uri) .
1731                       "<div class=\"search\">\n" .
1732                       $cgi->hidden(-name => "p") . "\n" .
1733                       $cgi->hidden(-name => "a") . "\n" .
1734                       $cgi->hidden(-name => "h") . "\n" .
1735                       $cgi->popup_menu(-name => 'st', -default => 'commit',
1736                                        -values => ['commit', 'author', 'committer', 'pickaxe']) .
1737                       $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
1738                       " search:\n",
1739                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1740                       "</div>" .
1741                       $cgi->end_form() . "\n";
1742         }
1743         print "</div>\n";
1746 sub git_footer_html {
1747         print "<div class=\"page_footer\">\n";
1748         if (defined $project) {
1749                 my $descr = git_get_project_description($project);
1750                 if (defined $descr) {
1751                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1752                 }
1753                 print $cgi->a({-href => href(action=>"rss"),
1754                               -class => "rss_logo"}, "RSS") . " ";
1755                 print $cgi->a({-href => href(action=>"atom"),
1756                               -class => "rss_logo"}, "Atom") . "\n";
1757         } else {
1758                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1759                               -class => "rss_logo"}, "OPML") . " ";
1760                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1761                               -class => "rss_logo"}, "TXT") . "\n";
1762         }
1763         print "</div>\n" ;
1765         if (-f $site_footer) {
1766                 open (my $fd, $site_footer);
1767                 print <$fd>;
1768                 close $fd;
1769         }
1771         print "</body>\n" .
1772               "</html>";
1775 sub die_error {
1776         my $status = shift || "403 Forbidden";
1777         my $error = shift || "Malformed query, file missing or permission denied";
1779         git_header_html($status);
1780         print <<EOF;
1781 <div class="page_body">
1782 <br /><br />
1783 $status - $error
1784 <br />
1785 </div>
1786 EOF
1787         git_footer_html();
1788         exit;
1791 ## ----------------------------------------------------------------------
1792 ## functions printing or outputting HTML: navigation
1794 sub git_print_page_nav {
1795         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1796         $extra = '' if !defined $extra; # pager or formats
1798         my @navs = qw(summary shortlog log commit commitdiff tree);
1799         if ($suppress) {
1800                 @navs = grep { $_ ne $suppress } @navs;
1801         }
1803         my %arg = map { $_ => {action=>$_} } @navs;
1804         if (defined $head) {
1805                 for (qw(commit commitdiff)) {
1806                         $arg{$_}{hash} = $head;
1807                 }
1808                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1809                         for (qw(shortlog log)) {
1810                                 $arg{$_}{hash} = $head;
1811                         }
1812                 }
1813         }
1814         $arg{tree}{hash} = $treehead if defined $treehead;
1815         $arg{tree}{hash_base} = $treebase if defined $treebase;
1817         print "<div class=\"page_nav\">\n" .
1818                 (join " | ",
1819                  map { $_ eq $current ?
1820                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1821                  } @navs);
1822         print "<br/>\n$extra<br/>\n" .
1823               "</div>\n";
1826 sub format_paging_nav {
1827         my ($action, $hash, $head, $page, $nrevs) = @_;
1828         my $paging_nav;
1831         if ($hash ne $head || $page) {
1832                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1833         } else {
1834                 $paging_nav .= "HEAD";
1835         }
1837         if ($page > 0) {
1838                 $paging_nav .= " &sdot; " .
1839                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1840                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1841         } else {
1842                 $paging_nav .= " &sdot; prev";
1843         }
1845         if ($nrevs >= (100 * ($page+1)-1)) {
1846                 $paging_nav .= " &sdot; " .
1847                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1848                                  -accesskey => "n", -title => "Alt-n"}, "next");
1849         } else {
1850                 $paging_nav .= " &sdot; next";
1851         }
1853         return $paging_nav;
1856 ## ......................................................................
1857 ## functions printing or outputting HTML: div
1859 sub git_print_header_div {
1860         my ($action, $title, $hash, $hash_base) = @_;
1861         my %args = ();
1863         $args{action} = $action;
1864         $args{hash} = $hash if $hash;
1865         $args{hash_base} = $hash_base if $hash_base;
1867         print "<div class=\"header\">\n" .
1868               $cgi->a({-href => href(%args), -class => "title"},
1869               $title ? $title : $action) .
1870               "\n</div>\n";
1873 #sub git_print_authorship (\%) {
1874 sub git_print_authorship {
1875         my $co = shift;
1877         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1878         print "<div class=\"author_date\">" .
1879               esc_html($co->{'author_name'}) .
1880               " [$ad{'rfc2822'}";
1881         if ($ad{'hour_local'} < 6) {
1882                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1883                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1884         } else {
1885                 printf(" (%02d:%02d %s)",
1886                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1887         }
1888         print "]</div>\n";
1891 sub git_print_page_path {
1892         my $name = shift;
1893         my $type = shift;
1894         my $hb = shift;
1897         print "<div class=\"page_path\">";
1898         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1899                       -title => 'tree root'}, "[$project]");
1900         print " / ";
1901         if (defined $name) {
1902                 my @dirname = split '/', $name;
1903                 my $basename = pop @dirname;
1904                 my $fullname = '';
1906                 foreach my $dir (@dirname) {
1907                         $fullname .= ($fullname ? '/' : '') . $dir;
1908                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1909                                                      hash_base=>$hb),
1910                                       -title => esc_html($fullname)}, esc_path($dir));
1911                         print " / ";
1912                 }
1913                 if (defined $type && $type eq 'blob') {
1914                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1915                                                      hash_base=>$hb),
1916                                       -title => esc_html($name)}, esc_path($basename));
1917                 } elsif (defined $type && $type eq 'tree') {
1918                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1919                                                      hash_base=>$hb),
1920                                       -title => esc_html($name)}, esc_path($basename));
1921                         print " / ";
1922                 } else {
1923                         print esc_path($basename);
1924                 }
1925         }
1926         print "<br/></div>\n";
1929 # sub git_print_log (\@;%) {
1930 sub git_print_log ($;%) {
1931         my $log = shift;
1932         my %opts = @_;
1934         if ($opts{'-remove_title'}) {
1935                 # remove title, i.e. first line of log
1936                 shift @$log;
1937         }
1938         # remove leading empty lines
1939         while (defined $log->[0] && $log->[0] eq "") {
1940                 shift @$log;
1941         }
1943         # print log
1944         my $signoff = 0;
1945         my $empty = 0;
1946         foreach my $line (@$log) {
1947                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1948                         $signoff = 1;
1949                         $empty = 0;
1950                         if (! $opts{'-remove_signoff'}) {
1951                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1952                                 next;
1953                         } else {
1954                                 # remove signoff lines
1955                                 next;
1956                         }
1957                 } else {
1958                         $signoff = 0;
1959                 }
1961                 # print only one empty line
1962                 # do not print empty line after signoff
1963                 if ($line eq "") {
1964                         next if ($empty || $signoff);
1965                         $empty = 1;
1966                 } else {
1967                         $empty = 0;
1968                 }
1970                 print format_log_line_html($line) . "<br/>\n";
1971         }
1973         if ($opts{'-final_empty_line'}) {
1974                 # end with single empty line
1975                 print "<br/>\n" unless $empty;
1976         }
1979 # print tree entry (row of git_tree), but without encompassing <tr> element
1980 sub git_print_tree_entry {
1981         my ($t, $basedir, $hash_base, $have_blame) = @_;
1983         my %base_key = ();
1984         $base_key{hash_base} = $hash_base if defined $hash_base;
1986         # The format of a table row is: mode list link.  Where mode is
1987         # the mode of the entry, list is the name of the entry, an href,
1988         # and link is the action links of the entry.
1990         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1991         if ($t->{'type'} eq "blob") {
1992                 print "<td class=\"list\">" .
1993                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1994                                                file_name=>"$basedir$t->{'name'}", %base_key),
1995                                 -class => "list"}, esc_path($t->{'name'})) . "</td>\n";
1996                 print "<td class=\"link\">";
1997                 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1998                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1999                               "blob");
2000                 if ($have_blame) {
2001                         print " | " .
2002                               $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2003                                                            file_name=>"$basedir$t->{'name'}", %base_key)},
2004                                             "blame");
2005                 }
2006                 if (defined $hash_base) {
2007                         print " | " .
2008                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2009                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
2010                                       "history");
2011                 }
2012                 print " | " .
2013                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
2014                                                file_name=>"$basedir$t->{'name'}")},
2015                                 "raw");
2016                 print "</td>\n";
2018         } elsif ($t->{'type'} eq "tree") {
2019                 print "<td class=\"list\">";
2020                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2021                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2022                               esc_path($t->{'name'}));
2023                 print "</td>\n";
2024                 print "<td class=\"link\">";
2025                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
2026                                              file_name=>"$basedir$t->{'name'}", %base_key)},
2027                               "tree");
2028                 if (defined $hash_base) {
2029                         print " | " .
2030                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2031                                                      file_name=>"$basedir$t->{'name'}")},
2032                                       "history");
2033                 }
2034                 print "</td>\n";
2035         }
2038 ## ......................................................................
2039 ## functions printing large fragments of HTML
2041 sub git_difftree_body {
2042         my ($difftree, $hash, $parent) = @_;
2043         my ($have_blame) = gitweb_check_feature('blame');
2044         print "<div class=\"list_head\">\n";
2045         if ($#{$difftree} > 10) {
2046                 print(($#{$difftree} + 1) . " files changed:\n");
2047         }
2048         print "</div>\n";
2050         print "<table class=\"diff_tree\">\n";
2051         my $alternate = 1;
2052         my $patchno = 0;
2053         foreach my $line (@{$difftree}) {
2054                 my %diff = parse_difftree_raw_line($line);
2056                 if ($alternate) {
2057                         print "<tr class=\"dark\">\n";
2058                 } else {
2059                         print "<tr class=\"light\">\n";
2060                 }
2061                 $alternate ^= 1;
2063                 my ($to_mode_oct, $to_mode_str, $to_file_type);
2064                 my ($from_mode_oct, $from_mode_str, $from_file_type);
2065                 if ($diff{'to_mode'} ne ('0' x 6)) {
2066                         $to_mode_oct = oct $diff{'to_mode'};
2067                         if (S_ISREG($to_mode_oct)) { # only for regular file
2068                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
2069                         }
2070                         $to_file_type = file_type($diff{'to_mode'});
2071                 }
2072                 if ($diff{'from_mode'} ne ('0' x 6)) {
2073                         $from_mode_oct = oct $diff{'from_mode'};
2074                         if (S_ISREG($to_mode_oct)) { # only for regular file
2075                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
2076                         }
2077                         $from_file_type = file_type($diff{'from_mode'});
2078                 }
2080                 if ($diff{'status'} eq "A") { # created
2081                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
2082                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
2083                         $mode_chng   .= "]</span>";
2084                         print "<td>";
2085                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2086                                                      hash_base=>$hash, file_name=>$diff{'file'}),
2087                                       -class => "list"}, esc_path($diff{'file'}));
2088                         print "</td>\n";
2089                         print "<td>$mode_chng</td>\n";
2090                         print "<td class=\"link\">";
2091                         if ($action eq 'commitdiff') {
2092                                 # link to patch
2093                                 $patchno++;
2094                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2095                         }
2096                         print "</td>\n";
2098                 } elsif ($diff{'status'} eq "D") { # deleted
2099                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
2100                         print "<td>";
2101                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2102                                                      hash_base=>$parent, file_name=>$diff{'file'}),
2103                                        -class => "list"}, esc_path($diff{'file'}));
2104                         print "</td>\n";
2105                         print "<td>$mode_chng</td>\n";
2106                         print "<td class=\"link\">";
2107                         if ($action eq 'commitdiff') {
2108                                 # link to patch
2109                                 $patchno++;
2110                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
2111                                 print " | ";
2112                         }
2113                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2114                                                      hash_base=>$parent, file_name=>$diff{'file'})},
2115                                       "blob") . " | ";
2116                         if ($have_blame) {
2117                                 print $cgi->a({-href =>
2118                                                    href(action=>"blame",
2119                                                         hash_base=>$parent,
2120                                                         file_name=>$diff{'file'})},
2121                                               "blame") . " | ";
2122                         }
2123                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2124                                                      file_name=>$diff{'file'})},
2125                                       "history");
2126                         print "</td>\n";
2128                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
2129                         my $mode_chnge = "";
2130                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
2131                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
2132                                 if ($from_file_type != $to_file_type) {
2133                                         $mode_chnge .= " from $from_file_type to $to_file_type";
2134                                 }
2135                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
2136                                         if ($from_mode_str && $to_mode_str) {
2137                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
2138                                         } elsif ($to_mode_str) {
2139                                                 $mode_chnge .= " mode: $to_mode_str";
2140                                         }
2141                                 }
2142                                 $mode_chnge .= "]</span>\n";
2143                         }
2144                         print "<td>";
2145                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2146                                                      hash_base=>$hash, file_name=>$diff{'file'}),
2147                                       -class => "list"}, esc_path($diff{'file'}));
2148                         print "</td>\n";
2149                         print "<td>$mode_chnge</td>\n";
2150                         print "<td class=\"link\">";
2151                         if ($action eq 'commitdiff') {
2152                                 # link to patch
2153                                 $patchno++;
2154                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2155                                       " | ";
2156                         } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2157                                 # "commit" view and modified file (not onlu mode changed)
2158                                 print $cgi->a({-href => href(action=>"blobdiff",
2159                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2160                                                              hash_base=>$hash, hash_parent_base=>$parent,
2161                                                              file_name=>$diff{'file'})},
2162                                               "diff") .
2163                                       " | ";
2164                         }
2165                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
2166                                                      hash_base=>$hash, file_name=>$diff{'file'})},
2167                                       "blob") . " | ";
2168                         if ($have_blame) {
2169                                 print $cgi->a({-href => href(action=>"blame",
2170                                                              hash_base=>$hash,
2171                                                              file_name=>$diff{'file'})},
2172                                               "blame") . " | ";
2173                         }
2174                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
2175                                                      file_name=>$diff{'file'})},
2176                                       "history");
2177                         print "</td>\n";
2179                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
2180                         my %status_name = ('R' => 'moved', 'C' => 'copied');
2181                         my $nstatus = $status_name{$diff{'status'}};
2182                         my $mode_chng = "";
2183                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
2184                                 # mode also for directories, so we cannot use $to_mode_str
2185                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
2186                         }
2187                         print "<td>" .
2188                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2189                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
2190                                       -class => "list"}, esc_path($diff{'to_file'})) . "</td>\n" .
2191                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
2192                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
2193                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
2194                                       -class => "list"}, esc_path($diff{'from_file'})) .
2195                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
2196                               "<td class=\"link\">";
2197                         if ($action eq 'commitdiff') {
2198                                 # link to patch
2199                                 $patchno++;
2200                                 print $cgi->a({-href => "#patch$patchno"}, "patch") .
2201                                       " | ";
2202                         } elsif ($diff{'to_id'} ne $diff{'from_id'}) {
2203                                 # "commit" view and modified file (not only pure rename or copy)
2204                                 print $cgi->a({-href => href(action=>"blobdiff",
2205                                                              hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
2206                                                              hash_base=>$hash, hash_parent_base=>$parent,
2207                                                              file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
2208                                               "diff") .
2209                                       " | ";
2210                         }
2211                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
2212                                                      hash_base=>$parent, file_name=>$diff{'from_file'})},
2213                                       "blob") . " | ";
2214                         if ($have_blame) {
2215                                 print $cgi->a({-href => href(action=>"blame",
2216                                                              hash_base=>$hash,
2217                                                              file_name=>$diff{'to_file'})},
2218                                               "blame") . " | ";
2219                         }
2220                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
2221                                                     file_name=>$diff{'from_file'})},
2222                                       "history");
2223                         print "</td>\n";
2225                 } # we should not encounter Unmerged (U) or Unknown (X) status
2226                 print "</tr>\n";
2227         }
2228         print "</table>\n";
2231 sub git_patchset_body {
2232         my ($fd, $difftree, $hash, $hash_parent) = @_;
2234         my $patch_idx = 0;
2235         my $patch_line;
2236         my $diffinfo;
2237         my (%from, %to);
2238         my ($from_id, $to_id);
2240         print "<div class=\"patchset\">\n";
2242         # skip to first patch
2243         while ($patch_line = <$fd>) {
2244                 chomp $patch_line;
2246                 last if ($patch_line =~ m/^diff /);
2247         }
2249  PATCH:
2250         while ($patch_line) {
2251                 my @diff_header;
2253                 # git diff header
2254                 #assert($patch_line =~ m/^diff /) if DEBUG;
2255                 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
2256                 push @diff_header, $patch_line;
2258                 # extended diff header
2259         EXTENDED_HEADER:
2260                 while ($patch_line = <$fd>) {
2261                         chomp $patch_line;
2263                         last EXTENDED_HEADER if ($patch_line =~ m/^--- /);
2265                         if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
2266                                 $from_id = $1;
2267                                 $to_id   = $2;
2268                         }
2270                         push @diff_header, $patch_line;
2271                 }
2272                 #last PATCH unless $patch_line;
2273                 my $last_patch_line = $patch_line;
2275                 # check if current patch belong to current raw line
2276                 # and parse raw git-diff line if needed
2277                 if (defined $diffinfo &&
2278                     $diffinfo->{'from_id'} eq $from_id &&
2279                     $diffinfo->{'to_id'}   eq $to_id) {
2280                         # this is split patch
2281                         print "<div class=\"patch cont\">\n";
2282                 } else {
2283                         # advance raw git-diff output if needed
2284                         $patch_idx++ if defined $diffinfo;
2286                         # read and prepare patch information
2287                         if (ref($difftree->[$patch_idx]) eq "HASH") {
2288                                 # pre-parsed (or generated by hand)
2289                                 $diffinfo = $difftree->[$patch_idx];
2290                         } else {
2291                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
2292                         }
2293                         $from{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
2294                         $to{'file'}   = $diffinfo->{'to_file'}   || $diffinfo->{'file'};
2295                         if ($diffinfo->{'status'} ne "A") { # not new (added) file
2296                                 $from{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2297                                                      hash=>$diffinfo->{'from_id'},
2298                                                      file_name=>$from{'file'});
2299                         }
2300                         if ($diffinfo->{'status'} ne "D") { # not deleted file
2301                                 $to{'href'} = href(action=>"blob", hash_base=>$hash,
2302                                                    hash=>$diffinfo->{'to_id'},
2303                                                    file_name=>$to{'file'});
2304                         }
2305                         # this is first patch for raw difftree line with $patch_idx index
2306                         # we index @$difftree array from 0, but number patches from 1
2307                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
2308                 }
2310                 # print "git diff" header
2311                 $patch_line = shift @diff_header;
2312                 $patch_line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2313                 if ($from{'href'}) {
2314                         $patch_line .= $cgi->a({-href => $from{'href'}, -class => "path"},
2315                                                'a/' . esc_path($from{'file'}));
2316                 } else { # file was added
2317                         $patch_line .= 'a/' . esc_path($from{'file'});
2318                 }
2319                 $patch_line .= ' ';
2320                 if ($to{'href'}) {
2321                         $patch_line .= $cgi->a({-href => $to{'href'}, -class => "path"},
2322                                                'b/' . esc_path($to{'file'}));
2323                 } else { # file was deleted
2324                         $patch_line .= 'b/' . esc_path($to{'file'});
2325                 }
2326                 print "<div class=\"diff header\">$patch_line</div>\n";
2328                 # print extended diff header
2329                 print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
2330         EXTENDED_HEADER:
2331                 foreach $patch_line (@diff_header) {
2332                         # match <path>
2333                         if ($patch_line =~ s!^((copy|rename) from ).*$!$1! && $from{'href'}) {
2334                                 $patch_line .= $cgi->a({-href=>$from{'href'}, -class=>"path"},
2335                                                         esc_path($from{'file'}));
2336                         }
2337                         if ($patch_line =~ s!^((copy|rename) to ).*$!$1! && $to{'href'}) {
2338                                 $patch_line = $cgi->a({-href=>$to{'href'}, -class=>"path"},
2339                                                       esc_path($to{'file'}));
2340                         }
2341                         # match <mode>
2342                         if ($patch_line =~ m/\s(\d{6})$/) {
2343                                 $patch_line .= '<span class="info"> (' .
2344                                                file_type_long($1) .
2345                                                ')</span>';
2346                         }
2347                         # match <hash>
2348                         if ($patch_line =~ m/^index/) {
2349                                 my ($from_link, $to_link);
2350                                 if ($from{'href'}) {
2351                                         $from_link = $cgi->a({-href=>$from{'href'}, -class=>"hash"},
2352                                                              substr($diffinfo->{'from_id'},0,7));
2353                                 } else {
2354                                         $from_link = '0' x 7;
2355                                 }
2356                                 if ($to{'href'}) {
2357                                         $to_link = $cgi->a({-href=>$to{'href'}, -class=>"hash"},
2358                                                            substr($diffinfo->{'to_id'},0,7));
2359                                 } else {
2360                                         $to_link = '0' x 7;
2361                                 }
2362                                 #affirm {
2363                                 #       my ($from_hash, $to_hash) =
2364                                 #               ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/);
2365                                 #       my ($from_id, $to_id) =
2366                                 #               ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2367                                 #       ($from_hash eq $from_id) && ($to_hash eq $to_id);
2368                                 #} if DEBUG;
2369                                 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2370                                 $patch_line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2371                         }
2372                         print $patch_line . "<br/>\n";
2373                 }
2374                 print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
2376                 # from-file/to-file diff header
2377                 $patch_line = $last_patch_line;
2378                 #assert($patch_line =~ m/^---/) if DEBUG;
2379                 if ($from{'href'}) {
2380                         $patch_line = '--- a/' .
2381                                       $cgi->a({-href=>$from{'href'}, -class=>"path"},
2382                                               esc_path($from{'file'}));
2383                 }
2384                 print "<div class=\"diff from_file\">$patch_line</div>\n";
2386                 $patch_line = <$fd>;
2387                 #last PATCH unless $patch_line;
2388                 chomp $patch_line;
2390                 #assert($patch_line =~ m/^+++/) if DEBUG;
2391                 if ($to{'href'}) {
2392                         $patch_line = '+++ b/' .
2393                                       $cgi->a({-href=>$to{'href'}, -class=>"path"},
2394                                               esc_path($to{'file'}));
2395                 }
2396                 print "<div class=\"diff to_file\">$patch_line</div>\n";
2398                 # the patch itself
2399         LINE:
2400                 while ($patch_line = <$fd>) {
2401                         chomp $patch_line;
2403                         next PATCH if ($patch_line =~ m/^diff /);
2405                         print format_diff_line($patch_line, \%from, \%to);
2406                 }
2408         } continue {
2409                 print "</div>\n"; # class="patch"
2410         }
2412         print "</div>\n"; # class="patchset"
2415 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2417 sub git_project_list_body {
2418         my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
2420         my ($check_forks) = gitweb_check_feature('forks');
2422         my @projects;
2423         foreach my $pr (@$projlist) {
2424                 my (@aa) = git_get_last_activity($pr->{'path'});
2425                 unless (@aa) {
2426                         next;
2427                 }
2428                 ($pr->{'age'}, $pr->{'age_string'}) = @aa;
2429                 if (!defined $pr->{'descr'}) {
2430                         my $descr = git_get_project_description($pr->{'path'}) || "";
2431                         $pr->{'descr'} = chop_str($descr, 25, 5);
2432                 }
2433                 if (!defined $pr->{'owner'}) {
2434                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2435                 }
2436                 if ($check_forks) {
2437                         my $pname = $pr->{'path'};
2438                         if (($pname =~ s/\.git$//) &&
2439                             ($pname !~ /\/$/) &&
2440                             (-d "$projectroot/$pname")) {
2441                                 $pr->{'forks'} = "-d $projectroot/$pname";
2442                         }
2443                         else {
2444                                 $pr->{'forks'} = 0;
2445                         }
2446                 }
2447                 push @projects, $pr;
2448         }
2450         $order ||= "project";
2451         $from = 0 unless defined $from;
2452         $to = $#projects if (!defined $to || $#projects < $to);
2454         print "<table class=\"project_list\">\n";
2455         unless ($no_header) {
2456                 print "<tr>\n";
2457                 if ($check_forks) {
2458                         print "<th></th>\n";
2459                 }
2460                 if ($order eq "project") {
2461                         @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2462                         print "<th>Project</th>\n";
2463                 } else {
2464                         print "<th>" .
2465                               $cgi->a({-href => href(project=>undef, order=>'project'),
2466                                        -class => "header"}, "Project") .
2467                               "</th>\n";
2468                 }
2469                 if ($order eq "descr") {
2470                         @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2471                         print "<th>Description</th>\n";
2472                 } else {
2473                         print "<th>" .
2474                               $cgi->a({-href => href(project=>undef, order=>'descr'),
2475                                        -class => "header"}, "Description") .
2476                               "</th>\n";
2477                 }
2478                 if ($order eq "owner") {
2479                         @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2480                         print "<th>Owner</th>\n";
2481                 } else {
2482                         print "<th>" .
2483                               $cgi->a({-href => href(project=>undef, order=>'owner'),
2484                                        -class => "header"}, "Owner") .
2485                               "</th>\n";
2486                 }
2487                 if ($order eq "age") {
2488                         @projects = sort {$a->{'age'} <=> $b->{'age'}} @projects;
2489                         print "<th>Last Change</th>\n";
2490                 } else {
2491                         print "<th>" .
2492                               $cgi->a({-href => href(project=>undef, order=>'age'),
2493                                        -class => "header"}, "Last Change") .
2494                               "</th>\n";
2495                 }
2496                 print "<th></th>\n" .
2497                       "</tr>\n";
2498         }
2499         my $alternate = 1;
2500         for (my $i = $from; $i <= $to; $i++) {
2501                 my $pr = $projects[$i];
2502                 if ($alternate) {
2503                         print "<tr class=\"dark\">\n";
2504                 } else {
2505                         print "<tr class=\"light\">\n";
2506                 }
2507                 $alternate ^= 1;
2508                 if ($check_forks) {
2509                         print "<td>";
2510                         if ($pr->{'forks'}) {
2511                                 print "<!-- $pr->{'forks'} -->\n";
2512                                 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
2513                         }
2514                         print "</td>\n";
2515                 }
2516                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2517                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2518                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2519                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2520                 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
2521                       $pr->{'age_string'} . "</td>\n" .
2522                       "<td class=\"link\">" .
2523                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2524                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2525                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2526                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2527                       ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
2528                       "</td>\n" .
2529                       "</tr>\n";
2530         }
2531         if (defined $extra) {
2532                 print "<tr>\n";
2533                 if ($check_forks) {
2534                         print "<td></td>\n";
2535                 }
2536                 print "<td colspan=\"5\">$extra</td>\n" .
2537                       "</tr>\n";
2538         }
2539         print "</table>\n";
2542 sub git_shortlog_body {
2543         # uses global variable $project
2544         my ($revlist, $from, $to, $refs, $extra) = @_;
2546         $from = 0 unless defined $from;
2547         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2549         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2550         my $alternate = 1;
2551         for (my $i = $from; $i <= $to; $i++) {
2552                 my $commit = $revlist->[$i];
2553                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2554                 my $ref = format_ref_marker($refs, $commit);
2555                 my %co = parse_commit($commit);
2556                 if ($alternate) {
2557                         print "<tr class=\"dark\">\n";
2558                 } else {
2559                         print "<tr class=\"light\">\n";
2560                 }
2561                 $alternate ^= 1;
2562                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2563                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2564                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2565                       "<td>";
2566                 print format_subject_html($co{'title'}, $co{'title_short'},
2567                                           href(action=>"commit", hash=>$commit), $ref);
2568                 print "</td>\n" .
2569                       "<td class=\"link\">" .
2570                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
2571                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2572                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2573                 if (gitweb_have_snapshot()) {
2574                         print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2575                 }
2576                 print "</td>\n" .
2577                       "</tr>\n";
2578         }
2579         if (defined $extra) {
2580                 print "<tr>\n" .
2581                       "<td colspan=\"4\">$extra</td>\n" .
2582                       "</tr>\n";
2583         }
2584         print "</table>\n";
2587 sub git_history_body {
2588         # Warning: assumes constant type (blob or tree) during history
2589         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2591         $from = 0 unless defined $from;
2592         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2594         print "<table class=\"history\" cellspacing=\"0\">\n";
2595         my $alternate = 1;
2596         for (my $i = $from; $i <= $to; $i++) {
2597                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2598                         next;
2599                 }
2601                 my $commit = $1;
2602                 my %co = parse_commit($commit);
2603                 if (!%co) {
2604                         next;
2605                 }
2607                 my $ref = format_ref_marker($refs, $commit);
2609                 if ($alternate) {
2610                         print "<tr class=\"dark\">\n";
2611                 } else {
2612                         print "<tr class=\"light\">\n";
2613                 }
2614                 $alternate ^= 1;
2615                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2616                       # shortlog uses      chop_str($co{'author_name'}, 10)
2617                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2618                       "<td>";
2619                 # originally git_history used chop_str($co{'title'}, 50)
2620                 print format_subject_html($co{'title'}, $co{'title_short'},
2621                                           href(action=>"commit", hash=>$commit), $ref);
2622                 print "</td>\n" .
2623                       "<td class=\"link\">" .
2624                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2625                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2627                 if ($ftype eq 'blob') {
2628                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2629                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2630                         if (defined $blob_current && defined $blob_parent &&
2631                                         $blob_current ne $blob_parent) {
2632                                 print " | " .
2633                                         $cgi->a({-href => href(action=>"blobdiff",
2634                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2635                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2636                                                                file_name=>$file_name)},
2637                                                 "diff to current");
2638                         }
2639                 }
2640                 print "</td>\n" .
2641                       "</tr>\n";
2642         }
2643         if (defined $extra) {
2644                 print "<tr>\n" .
2645                       "<td colspan=\"4\">$extra</td>\n" .
2646                       "</tr>\n";
2647         }
2648         print "</table>\n";
2651 sub git_tags_body {
2652         # uses global variable $project
2653         my ($taglist, $from, $to, $extra) = @_;
2654         $from = 0 unless defined $from;
2655         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2657         print "<table class=\"tags\" cellspacing=\"0\">\n";
2658         my $alternate = 1;
2659         for (my $i = $from; $i <= $to; $i++) {
2660                 my $entry = $taglist->[$i];
2661                 my %tag = %$entry;
2662                 my $comment = $tag{'subject'};
2663                 my $comment_short;
2664                 if (defined $comment) {
2665                         $comment_short = chop_str($comment, 30, 5);
2666                 }
2667                 if ($alternate) {
2668                         print "<tr class=\"dark\">\n";
2669                 } else {
2670                         print "<tr class=\"light\">\n";
2671                 }
2672                 $alternate ^= 1;
2673                 print "<td><i>$tag{'age'}</i></td>\n" .
2674                       "<td>" .
2675                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2676                                -class => "list name"}, esc_html($tag{'name'})) .
2677                       "</td>\n" .
2678                       "<td>";
2679                 if (defined $comment) {
2680                         print format_subject_html($comment, $comment_short,
2681                                                   href(action=>"tag", hash=>$tag{'id'}));
2682                 }
2683                 print "</td>\n" .
2684                       "<td class=\"selflink\">";
2685                 if ($tag{'type'} eq "tag") {
2686                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2687                 } else {
2688                         print "&nbsp;";
2689                 }
2690                 print "</td>\n" .
2691                       "<td class=\"link\">" . " | " .
2692                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2693                 if ($tag{'reftype'} eq "commit") {
2694                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2695                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
2696                 } elsif ($tag{'reftype'} eq "blob") {
2697                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2698                 }
2699                 print "</td>\n" .
2700                       "</tr>";
2701         }
2702         if (defined $extra) {
2703                 print "<tr>\n" .
2704                       "<td colspan=\"5\">$extra</td>\n" .
2705                       "</tr>\n";
2706         }
2707         print "</table>\n";
2710 sub git_heads_body {
2711         # uses global variable $project
2712         my ($headlist, $head, $from, $to, $extra) = @_;
2713         $from = 0 unless defined $from;
2714         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2716         print "<table class=\"heads\" cellspacing=\"0\">\n";
2717         my $alternate = 1;
2718         for (my $i = $from; $i <= $to; $i++) {
2719                 my $entry = $headlist->[$i];
2720                 my %ref = %$entry;
2721                 my $curr = $ref{'id'} eq $head;
2722                 if ($alternate) {
2723                         print "<tr class=\"dark\">\n";
2724                 } else {
2725                         print "<tr class=\"light\">\n";
2726                 }
2727                 $alternate ^= 1;
2728                 print "<td><i>$ref{'age'}</i></td>\n" .
2729                       ($curr ? "<td class=\"current_head\">" : "<td>") .
2730                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
2731                                -class => "list name"},esc_html($ref{'name'})) .
2732                       "</td>\n" .
2733                       "<td class=\"link\">" .
2734                       $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
2735                       $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
2736                       $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
2737                       "</td>\n" .
2738                       "</tr>";
2739         }
2740         if (defined $extra) {
2741                 print "<tr>\n" .
2742                       "<td colspan=\"3\">$extra</td>\n" .
2743                       "</tr>\n";
2744         }
2745         print "</table>\n";
2748 ## ======================================================================
2749 ## ======================================================================
2750 ## actions
2752 sub git_project_list {
2753         my $order = $cgi->param('o');
2754         if (defined $order && $order !~ m/project|descr|owner|age/) {
2755                 die_error(undef, "Unknown order parameter");
2756         }
2758         my @list = git_get_projects_list();
2759         if (!@list) {
2760                 die_error(undef, "No projects found");
2761         }
2763         git_header_html();
2764         if (-f $home_text) {
2765                 print "<div class=\"index_include\">\n";
2766                 open (my $fd, $home_text);
2767                 print <$fd>;
2768                 close $fd;
2769                 print "</div>\n";
2770         }
2771         git_project_list_body(\@list, $order);
2772         git_footer_html();
2775 sub git_forks {
2776         my $order = $cgi->param('o');
2777         if (defined $order && $order !~ m/project|descr|owner|age/) {
2778                 die_error(undef, "Unknown order parameter");
2779         }
2781         my @list = git_get_projects_list($project);
2782         if (!@list) {
2783                 die_error(undef, "No forks found");
2784         }
2786         git_header_html();
2787         git_print_page_nav('','');
2788         git_print_header_div('summary', "$project forks");
2789         git_project_list_body(\@list, $order);
2790         git_footer_html();
2793 sub git_project_index {
2794         my @projects = git_get_projects_list($project);
2796         print $cgi->header(
2797                 -type => 'text/plain',
2798                 -charset => 'utf-8',
2799                 -content_disposition => 'inline; filename="index.aux"');
2801         foreach my $pr (@projects) {
2802                 if (!exists $pr->{'owner'}) {
2803                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2804                 }
2806                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2807                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2808                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2809                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2810                 $path  =~ s/ /\+/g;
2811                 $owner =~ s/ /\+/g;
2813                 print "$path $owner\n";
2814         }
2817 sub git_summary {
2818         my $descr = git_get_project_description($project) || "none";
2819         my $head = git_get_head_hash($project);
2820         my %co = parse_commit($head);
2821         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2823         my $owner = git_get_project_owner($project);
2825         my $refs = git_get_references();
2826         my @taglist  = git_get_tags_list(15);
2827         my @headlist = git_get_heads_list(15);
2828         my @forklist;
2829         my ($check_forks) = gitweb_check_feature('forks');
2831         if ($check_forks) {
2832                 @forklist = git_get_projects_list($project);
2833         }
2835         git_header_html();
2836         git_print_page_nav('summary','', $head);
2838         print "<div class=\"title\">&nbsp;</div>\n";
2839         print "<table cellspacing=\"0\">\n" .
2840               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2841               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2842               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2843         # use per project git URL list in $projectroot/$project/cloneurl
2844         # or make project git URL from git base URL and project name
2845         my $url_tag = "URL";
2846         my @url_list = git_get_project_url_list($project);
2847         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2848         foreach my $git_url (@url_list) {
2849                 next unless $git_url;
2850                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2851                 $url_tag = "";
2852         }
2853         print "</table>\n";
2855         if (-s "$projectroot/$project/README.html") {
2856                 if (open my $fd, "$projectroot/$project/README.html") {
2857                         print "<div class=\"title\">readme</div>\n";
2858                         print $_ while (<$fd>);
2859                         close $fd;
2860                 }
2861         }
2863         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2864                 git_get_head_hash($project), "--"
2865                 or die_error(undef, "Open git-rev-list failed");
2866         my @revlist = map { chomp; $_ } <$fd>;
2867         close $fd;
2868         git_print_header_div('shortlog');
2869         git_shortlog_body(\@revlist, 0, 15, $refs,
2870                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2872         if (@taglist) {
2873                 git_print_header_div('tags');
2874                 git_tags_body(\@taglist, 0, 15,
2875                               $cgi->a({-href => href(action=>"tags")}, "..."));
2876         }
2878         if (@headlist) {
2879                 git_print_header_div('heads');
2880                 git_heads_body(\@headlist, $head, 0, 15,
2881                                $cgi->a({-href => href(action=>"heads")}, "..."));
2882         }
2884         if (@forklist) {
2885                 git_print_header_div('forks');
2886                 git_project_list_body(\@forklist, undef, 0, 15,
2887                                       $cgi->a({-href => href(action=>"forks")}, "..."),
2888                                       'noheader');
2889         }
2891         git_footer_html();
2894 sub git_tag {
2895         my $head = git_get_head_hash($project);
2896         git_header_html();
2897         git_print_page_nav('','', $head,undef,$head);
2898         my %tag = parse_tag($hash);
2899         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2900         print "<div class=\"title_text\">\n" .
2901               "<table cellspacing=\"0\">\n" .
2902               "<tr>\n" .
2903               "<td>object</td>\n" .
2904               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2905                                $tag{'object'}) . "</td>\n" .
2906               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2907                                               $tag{'type'}) . "</td>\n" .
2908               "</tr>\n";
2909         if (defined($tag{'author'})) {
2910                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2911                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2912                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2913                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2914                         "</td></tr>\n";
2915         }
2916         print "</table>\n\n" .
2917               "</div>\n";
2918         print "<div class=\"page_body\">";
2919         my $comment = $tag{'comment'};
2920         foreach my $line (@$comment) {
2921                 chomp($line);
2922                 print esc_html($line) . "<br/>\n";
2923         }
2924         print "</div>\n";
2925         git_footer_html();
2928 sub git_blame2 {
2929         my $fd;
2930         my $ftype;
2932         my ($have_blame) = gitweb_check_feature('blame');
2933         if (!$have_blame) {
2934                 die_error('403 Permission denied', "Permission denied");
2935         }
2936         die_error('404 Not Found', "File name not defined") if (!$file_name);
2937         $hash_base ||= git_get_head_hash($project);
2938         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2939         my %co = parse_commit($hash_base)
2940                 or die_error(undef, "Reading commit failed");
2941         if (!defined $hash) {
2942                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2943                         or die_error(undef, "Error looking up file");
2944         }
2945         $ftype = git_get_type($hash);
2946         if ($ftype !~ "blob") {
2947                 die_error("400 Bad Request", "Object is not a blob");
2948         }
2949         open ($fd, "-|", git_cmd(), "blame", '-p', '--',
2950               $file_name, $hash_base)
2951                 or die_error(undef, "Open git-blame failed");
2952         git_header_html();
2953         my $formats_nav =
2954                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2955                         "blob") .
2956                 " | " .
2957                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2958                         "history") .
2959                 " | " .
2960                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2961                         "HEAD");
2962         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2963         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2964         git_print_page_path($file_name, $ftype, $hash_base);
2965         my @rev_color = (qw(light2 dark2));
2966         my $num_colors = scalar(@rev_color);
2967         my $current_color = 0;
2968         my $last_rev;
2969         print <<HTML;
2970 <div class="page_body">
2971 <table class="blame">
2972 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2973 HTML
2974         my %metainfo = ();
2975         while (1) {
2976                 $_ = <$fd>;
2977                 last unless defined $_;
2978                 my ($full_rev, $orig_lineno, $lineno, $group_size) =
2979                     /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
2980                 if (!exists $metainfo{$full_rev}) {
2981                         $metainfo{$full_rev} = {};
2982                 }
2983                 my $meta = $metainfo{$full_rev};
2984                 while (<$fd>) {
2985                         last if (s/^\t//);
2986                         if (/^(\S+) (.*)$/) {
2987                                 $meta->{$1} = $2;
2988                         }
2989                 }
2990                 my $data = $_;
2991                 chomp($data);
2992                 my $rev = substr($full_rev, 0, 8);
2993                 my $author = $meta->{'author'};
2994                 my %date = parse_date($meta->{'author-time'},
2995                                       $meta->{'author-tz'});
2996                 my $date = $date{'iso-tz'};
2997                 if ($group_size) {
2998                         $current_color = ++$current_color % $num_colors;
2999                 }
3000                 print "<tr class=\"$rev_color[$current_color]\">\n";
3001                 if ($group_size) {
3002                         print "<td class=\"sha1\"";
3003                         print " title=\"". esc_html($author) . ", $date\"";
3004                         print " rowspan=\"$group_size\"" if ($group_size > 1);
3005                         print ">";
3006                         print $cgi->a({-href => href(action=>"commit",
3007                                                      hash=>$full_rev,
3008                                                      file_name=>$file_name)},
3009                                       esc_html($rev));
3010                         print "</td>\n";
3011                 }
3012                 my $blamed = href(action => 'blame',
3013                                   file_name => $meta->{'filename'},
3014                                   hash_base => $full_rev);
3015                 print "<td class=\"linenr\">";
3016                 print $cgi->a({ -href => "$blamed#l$orig_lineno",
3017                                 -id => "l$lineno",
3018                                 -class => "linenr" },
3019                               esc_html($lineno));
3020                 print "</td>";
3021                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
3022                 print "</tr>\n";
3023         }
3024         print "</table>\n";
3025         print "</div>";
3026         close $fd
3027                 or print "Reading blob failed\n";
3028         git_footer_html();
3031 sub git_blame {
3032         my $fd;
3034         my ($have_blame) = gitweb_check_feature('blame');
3035         if (!$have_blame) {
3036                 die_error('403 Permission denied', "Permission denied");
3037         }
3038         die_error('404 Not Found', "File name not defined") if (!$file_name);
3039         $hash_base ||= git_get_head_hash($project);
3040         die_error(undef, "Couldn't find base commit") unless ($hash_base);
3041         my %co = parse_commit($hash_base)
3042                 or die_error(undef, "Reading commit failed");
3043         if (!defined $hash) {
3044                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
3045                         or die_error(undef, "Error lookup file");
3046         }
3047         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
3048                 or die_error(undef, "Open git-annotate failed");
3049         git_header_html();
3050         my $formats_nav =
3051                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3052                         "blob") .
3053                 " | " .
3054                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
3055                         "history") .
3056                 " | " .
3057                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
3058                         "HEAD");
3059         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3060         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3061         git_print_page_path($file_name, 'blob', $hash_base);
3062         print "<div class=\"page_body\">\n";
3063         print <<HTML;
3064 <table class="blame">
3065   <tr>
3066     <th>Commit</th>
3067     <th>Age</th>
3068     <th>Author</th>
3069     <th>Line</th>
3070     <th>Data</th>
3071   </tr>
3072 HTML
3073         my @line_class = (qw(light dark));
3074         my $line_class_len = scalar (@line_class);
3075         my $line_class_num = $#line_class;
3076         while (my $line = <$fd>) {
3077                 my $long_rev;
3078                 my $short_rev;
3079                 my $author;
3080                 my $time;
3081                 my $lineno;
3082                 my $data;
3083                 my $age;
3084                 my $age_str;
3085                 my $age_class;
3087                 chomp $line;
3088                 $line_class_num = ($line_class_num + 1) % $line_class_len;
3090                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
3091                         $long_rev = $1;
3092                         $author   = $2;
3093                         $time     = $3;
3094                         $lineno   = $4;
3095                         $data     = $5;
3096                 } else {
3097                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
3098                         next;
3099                 }
3100                 $short_rev  = substr ($long_rev, 0, 8);
3101                 $age        = time () - $time;
3102                 $age_str    = age_string ($age);
3103                 $age_str    =~ s/ /&nbsp;/g;
3104                 $age_class  = age_class($age);
3105                 $author     = esc_html ($author);
3106                 $author     =~ s/ /&nbsp;/g;
3108                 $data = untabify($data);
3109                 $data = esc_html ($data);
3111                 print <<HTML;
3112   <tr class="$line_class[$line_class_num]">
3113     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
3114     <td class="$age_class">$age_str</td>
3115     <td>$author</td>
3116     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
3117     <td class="pre">$data</td>
3118   </tr>
3119 HTML
3120         } # while (my $line = <$fd>)
3121         print "</table>\n\n";
3122         close $fd
3123                 or print "Reading blob failed.\n";
3124         print "</div>";
3125         git_footer_html();
3128 sub git_tags {
3129         my $head = git_get_head_hash($project);
3130         git_header_html();
3131         git_print_page_nav('','', $head,undef,$head);
3132         git_print_header_div('summary', $project);
3134         my @tagslist = git_get_tags_list();
3135         if (@tagslist) {
3136                 git_tags_body(\@tagslist);
3137         }
3138         git_footer_html();
3141 sub git_heads {
3142         my $head = git_get_head_hash($project);
3143         git_header_html();
3144         git_print_page_nav('','', $head,undef,$head);
3145         git_print_header_div('summary', $project);
3147         my @headslist = git_get_heads_list();
3148         if (@headslist) {
3149                 git_heads_body(\@headslist, $head);
3150         }
3151         git_footer_html();
3154 sub git_blob_plain {
3155         my $expires;
3157         if (!defined $hash) {
3158                 if (defined $file_name) {
3159                         my $base = $hash_base || git_get_head_hash($project);
3160                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3161                                 or die_error(undef, "Error lookup file");
3162                 } else {
3163                         die_error(undef, "No file name defined");
3164                 }
3165         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3166                 # blobs defined by non-textual hash id's can be cached
3167                 $expires = "+1d";
3168         }
3170         my $type = shift;
3171         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3172                 or die_error(undef, "Couldn't cat $file_name, $hash");
3174         $type ||= blob_mimetype($fd, $file_name);
3176         # save as filename, even when no $file_name is given
3177         my $save_as = "$hash";
3178         if (defined $file_name) {
3179                 $save_as = $file_name;
3180         } elsif ($type =~ m/^text\//) {
3181                 $save_as .= '.txt';
3182         }
3184         print $cgi->header(
3185                 -type => "$type",
3186                 -expires=>$expires,
3187                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
3188         undef $/;
3189         binmode STDOUT, ':raw';
3190         print <$fd>;
3191         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3192         $/ = "\n";
3193         close $fd;
3196 sub git_blob {
3197         my $expires;
3199         if (!defined $hash) {
3200                 if (defined $file_name) {
3201                         my $base = $hash_base || git_get_head_hash($project);
3202                         $hash = git_get_hash_by_path($base, $file_name, "blob")
3203                                 or die_error(undef, "Error lookup file");
3204                 } else {
3205                         die_error(undef, "No file name defined");
3206                 }
3207         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3208                 # blobs defined by non-textual hash id's can be cached
3209                 $expires = "+1d";
3210         }
3212         my ($have_blame) = gitweb_check_feature('blame');
3213         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3214                 or die_error(undef, "Couldn't cat $file_name, $hash");
3215         my $mimetype = blob_mimetype($fd, $file_name);
3216         if ($mimetype !~ m/^text\//) {
3217                 close $fd;
3218                 return git_blob_plain($mimetype);
3219         }
3220         git_header_html(undef, $expires);
3221         my $formats_nav = '';
3222         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3223                 if (defined $file_name) {
3224                         if ($have_blame) {
3225                                 $formats_nav .=
3226                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
3227                                                                hash=>$hash, file_name=>$file_name)},
3228                                                 "blame") .
3229                                         " | ";
3230                         }
3231                         $formats_nav .=
3232                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3233                                                        hash=>$hash, file_name=>$file_name)},
3234                                         "history") .
3235                                 " | " .
3236                                 $cgi->a({-href => href(action=>"blob_plain",
3237                                                        hash=>$hash, file_name=>$file_name)},
3238                                         "raw") .
3239                                 " | " .
3240                                 $cgi->a({-href => href(action=>"blob",
3241                                                        hash_base=>"HEAD", file_name=>$file_name)},
3242                                         "HEAD");
3243                 } else {
3244                         $formats_nav .=
3245                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
3246                 }
3247                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3248                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3249         } else {
3250                 print "<div class=\"page_nav\">\n" .
3251                       "<br/><br/></div>\n" .
3252                       "<div class=\"title\">$hash</div>\n";
3253         }
3254         git_print_page_path($file_name, "blob", $hash_base);
3255         print "<div class=\"page_body\">\n";
3256         my $nr;
3257         while (my $line = <$fd>) {
3258                 chomp $line;
3259                 $nr++;
3260                 $line = untabify($line);
3261                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
3262                        $nr, $nr, $nr, esc_html($line, -nbsp=>1);
3263         }
3264         close $fd
3265                 or print "Reading blob failed.\n";
3266         print "</div>";
3267         git_footer_html();
3270 sub git_tree {
3271         my $have_snapshot = gitweb_have_snapshot();
3273         if (!defined $hash_base) {
3274                 $hash_base = "HEAD";
3275         }
3276         if (!defined $hash) {
3277                 if (defined $file_name) {
3278                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
3279                 } else {
3280                         $hash = $hash_base;
3281                 }
3282         }
3283         $/ = "\0";
3284         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
3285                 or die_error(undef, "Open git-ls-tree failed");
3286         my @entries = map { chomp; $_ } <$fd>;
3287         close $fd or die_error(undef, "Reading tree failed");
3288         $/ = "\n";
3290         my $refs = git_get_references();
3291         my $ref = format_ref_marker($refs, $hash_base);
3292         git_header_html();
3293         my $basedir = '';
3294         my ($have_blame) = gitweb_check_feature('blame');
3295         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3296                 my @views_nav = ();
3297                 if (defined $file_name) {
3298                         push @views_nav,
3299                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3300                                                        hash=>$hash, file_name=>$file_name)},
3301                                         "history"),
3302                                 $cgi->a({-href => href(action=>"tree",
3303                                                        hash_base=>"HEAD", file_name=>$file_name)},
3304                                         "HEAD"),
3305                 }
3306                 if ($have_snapshot) {
3307                         # FIXME: Should be available when we have no hash base as well.
3308                         push @views_nav,
3309                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
3310                                         "snapshot");
3311                 }
3312                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
3313                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
3314         } else {
3315                 undef $hash_base;
3316                 print "<div class=\"page_nav\">\n";
3317                 print "<br/><br/></div>\n";
3318                 print "<div class=\"title\">$hash</div>\n";
3319         }
3320         if (defined $file_name) {
3321                 $basedir = $file_name;
3322                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
3323                         $basedir .= '/';
3324                 }
3325         }
3326         git_print_page_path($file_name, 'tree', $hash_base);
3327         print "<div class=\"page_body\">\n";
3328         print "<table cellspacing=\"0\">\n";
3329         my $alternate = 1;
3330         # '..' (top directory) link if possible
3331         if (defined $hash_base &&
3332             defined $file_name && $file_name =~ m![^/]+$!) {
3333                 if ($alternate) {
3334                         print "<tr class=\"dark\">\n";
3335                 } else {
3336                         print "<tr class=\"light\">\n";
3337                 }
3338                 $alternate ^= 1;
3340                 my $up = $file_name;
3341                 $up =~ s!/?[^/]+$!!;
3342                 undef $up unless $up;
3343                 # based on git_print_tree_entry
3344                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
3345                 print '<td class="list">';
3346                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
3347                                              file_name=>$up)},
3348                               "..");
3349                 print "</td>\n";
3350                 print "<td class=\"link\"></td>\n";
3352                 print "</tr>\n";
3353         }
3354         foreach my $line (@entries) {
3355                 my %t = parse_ls_tree_line($line, -z => 1);
3357                 if ($alternate) {
3358                         print "<tr class=\"dark\">\n";
3359                 } else {
3360                         print "<tr class=\"light\">\n";
3361                 }
3362                 $alternate ^= 1;
3364                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
3366                 print "</tr>\n";
3367         }
3368         print "</table>\n" .
3369               "</div>";
3370         git_footer_html();
3373 sub git_snapshot {
3374         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
3375         my $have_snapshot = (defined $ctype && defined $suffix);
3376         if (!$have_snapshot) {
3377                 die_error('403 Permission denied', "Permission denied");
3378         }
3380         if (!defined $hash) {
3381                 $hash = git_get_head_hash($project);
3382         }
3384         my $filename = basename($project) . "-$hash.tar.$suffix";
3386         print $cgi->header(
3387                 -type => 'application/x-tar',
3388                 -content_encoding => $ctype,
3389                 -content_disposition => 'inline; filename="' . "$filename" . '"',
3390                 -status => '200 OK');
3392         my $git = git_cmd_str();
3393         my $name = $project;
3394         $name =~ s/\047/\047\\\047\047/g;
3395         open my $fd, "-|",
3396         "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
3397                 or die_error(undef, "Execute git-tar-tree failed.");
3398         binmode STDOUT, ':raw';
3399         print <$fd>;
3400         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
3401         close $fd;
3405 sub git_log {
3406         my $head = git_get_head_hash($project);
3407         if (!defined $hash) {
3408                 $hash = $head;
3409         }
3410         if (!defined $page) {
3411                 $page = 0;
3412         }
3413         my $refs = git_get_references();
3415         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3416         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
3417                 or die_error(undef, "Open git-rev-list failed");
3418         my @revlist = map { chomp; $_ } <$fd>;
3419         close $fd;
3421         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
3423         git_header_html();
3424         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
3426         if (!@revlist) {
3427                 my %co = parse_commit($hash);
3429                 git_print_header_div('summary', $project);
3430                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
3431         }
3432         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
3433                 my $commit = $revlist[$i];
3434                 my $ref = format_ref_marker($refs, $commit);
3435                 my %co = parse_commit($commit);
3436                 next if !%co;
3437                 my %ad = parse_date($co{'author_epoch'});
3438                 git_print_header_div('commit',
3439                                "<span class=\"age\">$co{'age_string'}</span>" .
3440                                esc_html($co{'title'}) . $ref,
3441                                $commit);
3442                 print "<div class=\"title_text\">\n" .
3443                       "<div class=\"log_link\">\n" .
3444                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
3445                       " | " .
3446                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
3447                       " | " .
3448                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
3449                       "<br/>\n" .
3450                       "</div>\n" .
3451                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
3452                       "</div>\n";
3454                 print "<div class=\"log_body\">\n";
3455                 git_print_log($co{'comment'}, -final_empty_line=> 1);
3456                 print "</div>\n";
3457         }
3458         git_footer_html();
3461 sub git_commit {
3462         $hash ||= $hash_base || "HEAD";
3463         my %co = parse_commit($hash);
3464         if (!%co) {
3465                 die_error(undef, "Unknown commit object");
3466         }
3467         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3468         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3470         my $parent = $co{'parent'};
3471         if (!defined $parent) {
3472                 $parent = "--root";
3473         }
3474         open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
3475                 @diff_opts, $parent, $hash, "--"
3476                 or die_error(undef, "Open git-diff-tree failed");
3477         my @difftree = map { chomp; $_ } <$fd>;
3478         close $fd or die_error(undef, "Reading git-diff-tree failed");
3480         # non-textual hash id's can be cached
3481         my $expires;
3482         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3483                 $expires = "+1d";
3484         }
3485         my $refs = git_get_references();
3486         my $ref = format_ref_marker($refs, $co{'id'});
3488         my $have_snapshot = gitweb_have_snapshot();
3490         my @views_nav = ();
3491         if (defined $file_name && defined $co{'parent'}) {
3492                 push @views_nav,
3493                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
3494                                 "blame");
3495         }
3496         git_header_html(undef, $expires);
3497         git_print_page_nav('commit', '',
3498                            $hash, $co{'tree'}, $hash,
3499                            join (' | ', @views_nav));
3501         if (defined $co{'parent'}) {
3502                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3503         } else {
3504                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3505         }
3506         print "<div class=\"title_text\">\n" .
3507               "<table cellspacing=\"0\">\n";
3508         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3509               "<tr>" .
3510               "<td></td><td> $ad{'rfc2822'}";
3511         if ($ad{'hour_local'} < 6) {
3512                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3513                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3514         } else {
3515                 printf(" (%02d:%02d %s)",
3516                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3517         }
3518         print "</td>" .
3519               "</tr>\n";
3520         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3521         print "<tr><td></td><td> $cd{'rfc2822'}" .
3522               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3523               "</td></tr>\n";
3524         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3525         print "<tr>" .
3526               "<td>tree</td>" .
3527               "<td class=\"sha1\">" .
3528               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3529                        class => "list"}, $co{'tree'}) .
3530               "</td>" .
3531               "<td class=\"link\">" .
3532               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3533                       "tree");
3534         if ($have_snapshot) {
3535                 print " | " .
3536                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3537         }
3538         print "</td>" .
3539               "</tr>\n";
3540         my $parents = $co{'parents'};
3541         foreach my $par (@$parents) {
3542                 print "<tr>" .
3543                       "<td>parent</td>" .
3544                       "<td class=\"sha1\">" .
3545                       $cgi->a({-href => href(action=>"commit", hash=>$par),
3546                                class => "list"}, $par) .
3547                       "</td>" .
3548                       "<td class=\"link\">" .
3549                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3550                       " | " .
3551                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3552                       "</td>" .
3553                       "</tr>\n";
3554         }
3555         print "</table>".
3556               "</div>\n";
3558         print "<div class=\"page_body\">\n";
3559         git_print_log($co{'comment'});
3560         print "</div>\n";
3562         git_difftree_body(\@difftree, $hash, $parent);
3564         git_footer_html();
3567 sub git_blobdiff {
3568         my $format = shift || 'html';
3570         my $fd;
3571         my @difftree;
3572         my %diffinfo;
3573         my $expires;
3575         # preparing $fd and %diffinfo for git_patchset_body
3576         # new style URI
3577         if (defined $hash_base && defined $hash_parent_base) {
3578                 if (defined $file_name) {
3579                         # read raw output
3580                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3581                                 $hash_parent_base, $hash_base,
3582                                 "--", $file_name
3583                                 or die_error(undef, "Open git-diff-tree failed");
3584                         @difftree = map { chomp; $_ } <$fd>;
3585                         close $fd
3586                                 or die_error(undef, "Reading git-diff-tree failed");
3587                         @difftree
3588                                 or die_error('404 Not Found', "Blob diff not found");
3590                 } elsif (defined $hash &&
3591                          $hash =~ /[0-9a-fA-F]{40}/) {
3592                         # try to find filename from $hash
3594                         # read filtered raw output
3595                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3596                                 $hash_parent_base, $hash_base, "--"
3597                                 or die_error(undef, "Open git-diff-tree failed");
3598                         @difftree =
3599                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3600                                 # $hash == to_id
3601                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3602                                 map { chomp; $_ } <$fd>;
3603                         close $fd
3604                                 or die_error(undef, "Reading git-diff-tree failed");
3605                         @difftree
3606                                 or die_error('404 Not Found', "Blob diff not found");
3608                 } else {
3609                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3610                 }
3612                 if (@difftree > 1) {
3613                         die_error('404 Not Found', "Ambiguous blob diff specification");
3614                 }
3616                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3617                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3618                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3620                 $hash_parent ||= $diffinfo{'from_id'};
3621                 $hash        ||= $diffinfo{'to_id'};
3623                 # non-textual hash id's can be cached
3624                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3625                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3626                         $expires = '+1d';
3627                 }
3629                 # open patch output
3630                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3631                         '-p', $hash_parent_base, $hash_base,
3632                         "--", $file_name
3633                         or die_error(undef, "Open git-diff-tree failed");
3634         }
3636         # old/legacy style URI
3637         if (!%diffinfo && # if new style URI failed
3638             defined $hash && defined $hash_parent) {
3639                 # fake git-diff-tree raw output
3640                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3641                 $diffinfo{'from_id'} = $hash_parent;
3642                 $diffinfo{'to_id'}   = $hash;
3643                 if (defined $file_name) {
3644                         if (defined $file_parent) {
3645                                 $diffinfo{'status'} = '2';
3646                                 $diffinfo{'from_file'} = $file_parent;
3647                                 $diffinfo{'to_file'}   = $file_name;
3648                         } else { # assume not renamed
3649                                 $diffinfo{'status'} = '1';
3650                                 $diffinfo{'from_file'} = $file_name;
3651                                 $diffinfo{'to_file'}   = $file_name;
3652                         }
3653                 } else { # no filename given
3654                         $diffinfo{'status'} = '2';
3655                         $diffinfo{'from_file'} = $hash_parent;
3656                         $diffinfo{'to_file'}   = $hash;
3657                 }
3659                 # non-textual hash id's can be cached
3660                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3661                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3662                         $expires = '+1d';
3663                 }
3665                 # open patch output
3666                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts,
3667                         $hash_parent, $hash, "--"
3668                         or die_error(undef, "Open git-diff failed");
3669         } else  {
3670                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3671                         unless %diffinfo;
3672         }
3674         # header
3675         if ($format eq 'html') {
3676                 my $formats_nav =
3677                         $cgi->a({-href => href(action=>"blobdiff_plain",
3678                                                hash=>$hash, hash_parent=>$hash_parent,
3679                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3680                                                file_name=>$file_name, file_parent=>$file_parent)},
3681                                 "raw");
3682                 git_header_html(undef, $expires);
3683                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3684                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3685                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3686                 } else {
3687                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3688                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3689                 }
3690                 if (defined $file_name) {
3691                         git_print_page_path($file_name, "blob", $hash_base);
3692                 } else {
3693                         print "<div class=\"page_path\"></div>\n";
3694                 }
3696         } elsif ($format eq 'plain') {
3697                 print $cgi->header(
3698                         -type => 'text/plain',
3699                         -charset => 'utf-8',
3700                         -expires => $expires,
3701                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
3703                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3705         } else {
3706                 die_error(undef, "Unknown blobdiff format");
3707         }
3709         # patch
3710         if ($format eq 'html') {
3711                 print "<div class=\"page_body\">\n";
3713                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3714                 close $fd;
3716                 print "</div>\n"; # class="page_body"
3717                 git_footer_html();
3719         } else {
3720                 while (my $line = <$fd>) {
3721                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
3722                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
3724                         print $line;
3726                         last if $line =~ m!^\+\+\+!;
3727                 }
3728                 local $/ = undef;
3729                 print <$fd>;
3730                 close $fd;
3731         }
3734 sub git_blobdiff_plain {
3735         git_blobdiff('plain');
3738 sub git_commitdiff {
3739         my $format = shift || 'html';
3740         $hash ||= $hash_base || "HEAD";
3741         my %co = parse_commit($hash);
3742         if (!%co) {
3743                 die_error(undef, "Unknown commit object");
3744         }
3746         # we need to prepare $formats_nav before any parameter munging
3747         my $formats_nav;
3748         if ($format eq 'html') {
3749                 $formats_nav =
3750                         $cgi->a({-href => href(action=>"commitdiff_plain",
3751                                                hash=>$hash, hash_parent=>$hash_parent)},
3752                                 "raw");
3754                 if (defined $hash_parent) {
3755                         # commitdiff with two commits given
3756                         my $hash_parent_short = $hash_parent;
3757                         if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3758                                 $hash_parent_short = substr($hash_parent, 0, 7);
3759                         }
3760                         $formats_nav .=
3761                                 ' (from: ' .
3762                                 $cgi->a({-href => href(action=>"commitdiff",
3763                                                        hash=>$hash_parent)},
3764                                         esc_html($hash_parent_short)) .
3765                                 ')';
3766                 } elsif (!$co{'parent'}) {
3767                         # --root commitdiff
3768                         $formats_nav .= ' (initial)';
3769                 } elsif (scalar @{$co{'parents'}} == 1) {
3770                         # single parent commit
3771                         $formats_nav .=
3772                                 ' (parent: ' .
3773                                 $cgi->a({-href => href(action=>"commitdiff",
3774                                                        hash=>$co{'parent'})},
3775                                         esc_html(substr($co{'parent'}, 0, 7))) .
3776                                 ')';
3777                 } else {
3778                         # merge commit
3779                         $formats_nav .=
3780                                 ' (merge: ' .
3781                                 join(' ', map {
3782                                         $cgi->a({-href => href(action=>"commitdiff",
3783                                                                hash=>$_)},
3784                                                 esc_html(substr($_, 0, 7)));
3785                                 } @{$co{'parents'}} ) .
3786                                 ')';
3787                 }
3788         }
3790         if (!defined $hash_parent) {
3791                 $hash_parent = $co{'parent'} || '--root';
3792         }
3794         # read commitdiff
3795         my $fd;
3796         my @difftree;
3797         if ($format eq 'html') {
3798                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3799                         "--no-commit-id", "--patch-with-raw", "--full-index",
3800                         $hash_parent, $hash, "--"
3801                         or die_error(undef, "Open git-diff-tree failed");
3803                 while (my $line = <$fd>) {
3804                         chomp $line;
3805                         # empty line ends raw part of diff-tree output
3806                         last unless $line;
3807                         push @difftree, $line;
3808                 }
3810         } elsif ($format eq 'plain') {
3811                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3812                         '-p', $hash_parent, $hash, "--"
3813                         or die_error(undef, "Open git-diff-tree failed");
3815         } else {
3816                 die_error(undef, "Unknown commitdiff format");
3817         }
3819         # non-textual hash id's can be cached
3820         my $expires;
3821         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3822                 $expires = "+1d";
3823         }
3825         # write commit message
3826         if ($format eq 'html') {
3827                 my $refs = git_get_references();
3828                 my $ref = format_ref_marker($refs, $co{'id'});
3830                 git_header_html(undef, $expires);
3831                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3832                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3833                 git_print_authorship(\%co);
3834                 print "<div class=\"page_body\">\n";
3835                 if (@{$co{'comment'}} > 1) {
3836                         print "<div class=\"log\">\n";
3837                         git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
3838                         print "</div>\n"; # class="log"
3839                 }
3841         } elsif ($format eq 'plain') {
3842                 my $refs = git_get_references("tags");
3843                 my $tagname = git_get_rev_name_tags($hash);
3844                 my $filename = basename($project) . "-$hash.patch";
3846                 print $cgi->header(
3847                         -type => 'text/plain',
3848                         -charset => 'utf-8',
3849                         -expires => $expires,
3850                         -content_disposition => 'inline; filename="' . "$filename" . '"');
3851                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3852                 print <<TEXT;
3853 From: $co{'author'}
3854 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3855 Subject: $co{'title'}
3856 TEXT
3857                 print "X-Git-Tag: $tagname\n" if $tagname;
3858                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3860                 foreach my $line (@{$co{'comment'}}) {
3861                         print "$line\n";
3862                 }
3863                 print "---\n\n";
3864         }
3866         # write patch
3867         if ($format eq 'html') {
3868                 git_difftree_body(\@difftree, $hash, $hash_parent);
3869                 print "<br/>\n";
3871                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3872                 close $fd;
3873                 print "</div>\n"; # class="page_body"
3874                 git_footer_html();
3876         } elsif ($format eq 'plain') {
3877                 local $/ = undef;
3878                 print <$fd>;
3879                 close $fd
3880                         or print "Reading git-diff-tree failed\n";
3881         }
3884 sub git_commitdiff_plain {
3885         git_commitdiff('plain');
3888 sub git_history {
3889         if (!defined $hash_base) {
3890                 $hash_base = git_get_head_hash($project);
3891         }
3892         if (!defined $page) {
3893                 $page = 0;
3894         }
3895         my $ftype;
3896         my %co = parse_commit($hash_base);
3897         if (!%co) {
3898                 die_error(undef, "Unknown commit object");
3899         }
3901         my $refs = git_get_references();
3902         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3904         if (!defined $hash && defined $file_name) {
3905                 $hash = git_get_hash_by_path($hash_base, $file_name);
3906         }
3907         if (defined $hash) {
3908                 $ftype = git_get_type($hash);
3909         }
3911         open my $fd, "-|",
3912                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3913                         or die_error(undef, "Open git-rev-list-failed");
3914         my @revlist = map { chomp; $_ } <$fd>;
3915         close $fd
3916                 or die_error(undef, "Reading git-rev-list failed");
3918         my $paging_nav = '';
3919         if ($page > 0) {
3920                 $paging_nav .=
3921                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3922                                                file_name=>$file_name)},
3923                                 "first");
3924                 $paging_nav .= " &sdot; " .
3925                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3926                                                file_name=>$file_name, page=>$page-1),
3927                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3928         } else {
3929                 $paging_nav .= "first";
3930                 $paging_nav .= " &sdot; prev";
3931         }
3932         if ($#revlist >= (100 * ($page+1)-1)) {
3933                 $paging_nav .= " &sdot; " .
3934                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3935                                                file_name=>$file_name, page=>$page+1),
3936                                  -accesskey => "n", -title => "Alt-n"}, "next");
3937         } else {
3938                 $paging_nav .= " &sdot; next";
3939         }
3940         my $next_link = '';
3941         if ($#revlist >= (100 * ($page+1)-1)) {
3942                 $next_link =
3943                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3944                                                file_name=>$file_name, page=>$page+1),
3945                                  -title => "Alt-n"}, "next");
3946         }
3948         git_header_html();
3949         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3950         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3951         git_print_page_path($file_name, $ftype, $hash_base);
3953         git_history_body(\@revlist, ($page * 100), $#revlist,
3954                          $refs, $hash_base, $ftype, $next_link);
3956         git_footer_html();
3959 sub git_search {
3960         if (!defined $searchtext) {
3961                 die_error(undef, "Text field empty");
3962         }
3963         if (!defined $hash) {
3964                 $hash = git_get_head_hash($project);
3965         }
3966         my %co = parse_commit($hash);
3967         if (!%co) {
3968                 die_error(undef, "Unknown commit object");
3969         }
3971         $searchtype ||= 'commit';
3972         if ($searchtype eq 'pickaxe') {
3973                 # pickaxe may take all resources of your box and run for several minutes
3974                 # with every query - so decide by yourself how public you make this feature
3975                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3976                 if (!$have_pickaxe) {
3977                         die_error('403 Permission denied', "Permission denied");
3978                 }
3979         }
3981         git_header_html();
3982         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3983         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3985         print "<table cellspacing=\"0\">\n";
3986         my $alternate = 1;
3987         if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
3988                 $/ = "\0";
3989                 open my $fd, "-|", git_cmd(), "rev-list",
3990                         "--header", "--parents", $hash, "--"
3991                         or next;
3992                 while (my $commit_text = <$fd>) {
3993                         if (!grep m/$searchtext/i, $commit_text) {
3994                                 next;
3995                         }
3996                         if ($searchtype eq 'author' && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3997                                 next;
3998                         }
3999                         if ($searchtype eq 'committer' && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
4000                                 next;
4001                         }
4002                         my @commit_lines = split "\n", $commit_text;
4003                         my %co = parse_commit(undef, \@commit_lines);
4004                         if (!%co) {
4005                                 next;
4006                         }
4007                         if ($alternate) {
4008                                 print "<tr class=\"dark\">\n";
4009                         } else {
4010                                 print "<tr class=\"light\">\n";
4011                         }
4012                         $alternate ^= 1;
4013                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4014                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
4015                               "<td>" .
4016                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
4017                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
4018                         my $comment = $co{'comment'};
4019                         foreach my $line (@$comment) {
4020                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
4021                                         my $lead = esc_html($1) || "";
4022                                         $lead = chop_str($lead, 30, 10);
4023                                         my $match = esc_html($2) || "";
4024                                         my $trail = esc_html($3) || "";
4025                                         $trail = chop_str($trail, 30, 10);
4026                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
4027                                         print chop_str($text, 80, 5) . "<br/>\n";
4028                                 }
4029                         }
4030                         print "</td>\n" .
4031                               "<td class=\"link\">" .
4032                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4033                               " | " .
4034                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4035                         print "</td>\n" .
4036                               "</tr>\n";
4037                 }
4038                 close $fd;
4039         }
4041         if ($searchtype eq 'pickaxe') {
4042                 $/ = "\n";
4043                 my $git_command = git_cmd_str();
4044                 open my $fd, "-|", "$git_command rev-list $hash | " .
4045                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
4046                 undef %co;
4047                 my @files;
4048                 while (my $line = <$fd>) {
4049                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
4050                                 my %set;
4051                                 $set{'file'} = $6;
4052                                 $set{'from_id'} = $3;
4053                                 $set{'to_id'} = $4;
4054                                 $set{'id'} = $set{'to_id'};
4055                                 if ($set{'id'} =~ m/0{40}/) {
4056                                         $set{'id'} = $set{'from_id'};
4057                                 }
4058                                 if ($set{'id'} =~ m/0{40}/) {
4059                                         next;
4060                                 }
4061                                 push @files, \%set;
4062                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
4063                                 if (%co) {
4064                                         if ($alternate) {
4065                                                 print "<tr class=\"dark\">\n";
4066                                         } else {
4067                                                 print "<tr class=\"light\">\n";
4068                                         }
4069                                         $alternate ^= 1;
4070                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4071                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
4072                                               "<td>" .
4073                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4074                                                       -class => "list subject"},
4075                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
4076                                         while (my $setref = shift @files) {
4077                                                 my %set = %$setref;
4078                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
4079                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
4080                                                               -class => "list"},
4081                                                               "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
4082                                                       "<br/>\n";
4083                                         }
4084                                         print "</td>\n" .
4085                                               "<td class=\"link\">" .
4086                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4087                                               " | " .
4088                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4089                                         print "</td>\n" .
4090                                               "</tr>\n";
4091                                 }
4092                                 %co = parse_commit($1);
4093                         }
4094                 }
4095                 close $fd;
4096         }
4097         print "</table>\n";
4098         git_footer_html();
4101 sub git_search_help {
4102         git_header_html();
4103         git_print_page_nav('','', $hash,$hash,$hash);
4104         print <<EOT;
4105 <dl>
4106 <dt><b>commit</b></dt>
4107 <dd>The commit messages and authorship information will be scanned for the given string.</dd>
4108 <dt><b>author</b></dt>
4109 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
4110 <dt><b>committer</b></dt>
4111 <dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
4112 EOT
4113         my ($have_pickaxe) = gitweb_check_feature('pickaxe');
4114         if ($have_pickaxe) {
4115                 print <<EOT;
4116 <dt><b>pickaxe</b></dt>
4117 <dd>All commits that caused the string to appear or disappear from any file (changes that
4118 added, removed or "modified" the string) will be listed. This search can take a while and
4119 takes a lot of strain on the server, so please use it wisely.</dd>
4120 EOT
4121         }
4122         print "</dl>\n";
4123         git_footer_html();
4126 sub git_shortlog {
4127         my $head = git_get_head_hash($project);
4128         if (!defined $hash) {
4129                 $hash = $head;
4130         }
4131         if (!defined $page) {
4132                 $page = 0;
4133         }
4134         my $refs = git_get_references();
4136         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
4137         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash, "--"
4138                 or die_error(undef, "Open git-rev-list failed");
4139         my @revlist = map { chomp; $_ } <$fd>;
4140         close $fd;
4142         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
4143         my $next_link = '';
4144         if ($#revlist >= (100 * ($page+1)-1)) {
4145                 $next_link =
4146                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
4147                                  -title => "Alt-n"}, "next");
4148         }
4151         git_header_html();
4152         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
4153         git_print_header_div('summary', $project);
4155         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
4157         git_footer_html();
4160 ## ......................................................................
4161 ## feeds (RSS, Atom; OPML)
4163 sub git_feed {
4164         my $format = shift || 'atom';
4165         my ($have_blame) = gitweb_check_feature('blame');
4167         # Atom: http://www.atomenabled.org/developers/syndication/
4168         # RSS:  http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
4169         if ($format ne 'rss' && $format ne 'atom') {
4170                 die_error(undef, "Unknown web feed format");
4171         }
4173         # log/feed of current (HEAD) branch, log of given branch, history of file/directory
4174         my $head = $hash || 'HEAD';
4175         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150",
4176                 $head, "--", (defined $file_name ? $file_name : ())
4177                 or die_error(undef, "Open git-rev-list failed");
4178         my @revlist = map { chomp; $_ } <$fd>;
4179         close $fd or die_error(undef, "Reading git-rev-list failed");
4181         my %latest_commit;
4182         my %latest_date;
4183         my $content_type = "application/$format+xml";
4184         if (defined $cgi->http('HTTP_ACCEPT') &&
4185                  $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
4186                 # browser (feed reader) prefers text/xml
4187                 $content_type = 'text/xml';
4188         }
4189         if (defined($revlist[0])) {
4190                 %latest_commit = parse_commit($revlist[0]);
4191                 %latest_date   = parse_date($latest_commit{'committer_epoch'});
4192                 print $cgi->header(
4193                         -type => $content_type,
4194                         -charset => 'utf-8',
4195                         -last_modified => $latest_date{'rfc2822'});
4196         } else {
4197                 print $cgi->header(
4198                         -type => $content_type,
4199                         -charset => 'utf-8');
4200         }
4202         # Optimization: skip generating the body if client asks only
4203         # for Last-Modified date.
4204         return if ($cgi->request_method() eq 'HEAD');
4206         # header variables
4207         my $title = "$site_name - $project/$action";
4208         my $feed_type = 'log';
4209         if (defined $hash) {
4210                 $title .= " - '$hash'";
4211                 $feed_type = 'branch log';
4212                 if (defined $file_name) {
4213                         $title .= " :: $file_name";
4214                         $feed_type = 'history';
4215                 }
4216         } elsif (defined $file_name) {
4217                 $title .= " - $file_name";
4218                 $feed_type = 'history';
4219         }
4220         $title .= " $feed_type";
4221         my $descr = git_get_project_description($project);
4222         if (defined $descr) {
4223                 $descr = esc_html($descr);
4224         } else {
4225                 $descr = "$project " .
4226                          ($format eq 'rss' ? 'RSS' : 'Atom') .
4227                          " feed";
4228         }
4229         my $owner = git_get_project_owner($project);
4230         $owner = esc_html($owner);
4232         #header
4233         my $alt_url;
4234         if (defined $file_name) {
4235                 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
4236         } elsif (defined $hash) {
4237                 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
4238         } else {
4239                 $alt_url = href(-full=>1, action=>"summary");
4240         }
4241         print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
4242         if ($format eq 'rss') {
4243                 print <<XML;
4244 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
4245 <channel>
4246 XML
4247                 print "<title>$title</title>\n" .
4248                       "<link>$alt_url</link>\n" .
4249                       "<description>$descr</description>\n" .
4250                       "<language>en</language>\n";
4251         } elsif ($format eq 'atom') {
4252                 print <<XML;
4253 <feed xmlns="http://www.w3.org/2005/Atom">
4254 XML
4255                 print "<title>$title</title>\n" .
4256                       "<subtitle>$descr</subtitle>\n" .
4257                       '<link rel="alternate" type="text/html" href="' .
4258                       $alt_url . '" />' . "\n" .
4259                       '<link rel="self" type="' . $content_type . '" href="' .
4260                       $cgi->self_url() . '" />' . "\n" .
4261                       "<id>" . href(-full=>1) . "</id>\n" .
4262                       # use project owner for feed author
4263                       "<author><name>$owner</name></author>\n";
4264                 if (defined $favicon) {
4265                         print "<icon>" . esc_url($favicon) . "</icon>\n";
4266                 }
4267                 if (defined $logo_url) {
4268                         # not twice as wide as tall: 72 x 27 pixels
4269                         print "<logo>" . esc_url($logo_url) . "</logo>\n";
4270                 }
4271                 if (! %latest_date) {
4272                         # dummy date to keep the feed valid until commits trickle in:
4273                         print "<updated>1970-01-01T00:00:00Z</updated>\n";
4274                 } else {
4275                         print "<updated>$latest_date{'iso-8601'}</updated>\n";
4276                 }
4277         }
4279         # contents
4280         for (my $i = 0; $i <= $#revlist; $i++) {
4281                 my $commit = $revlist[$i];
4282                 my %co = parse_commit($commit);
4283                 # we read 150, we always show 30 and the ones more recent than 48 hours
4284                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
4285                         last;
4286                 }
4287                 my %cd = parse_date($co{'committer_epoch'});
4289                 # get list of changed files
4290                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4291                         $co{'parent'}, $co{'id'}, "--", (defined $file_name ? $file_name : ())
4292                         or next;
4293                 my @difftree = map { chomp; $_ } <$fd>;
4294                 close $fd
4295                         or next;
4297                 # print element (entry, item)
4298                 my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
4299                 if ($format eq 'rss') {
4300                         print "<item>\n" .
4301                               "<title>" . esc_html($co{'title'}) . "</title>\n" .
4302                               "<author>" . esc_html($co{'author'}) . "</author>\n" .
4303                               "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
4304                               "<guid isPermaLink=\"true\">$co_url</guid>\n" .
4305                               "<link>$co_url</link>\n" .
4306                               "<description>" . esc_html($co{'title'}) . "</description>\n" .
4307                               "<content:encoded>" .
4308                               "<![CDATA[\n";
4309                 } elsif ($format eq 'atom') {
4310                         print "<entry>\n" .
4311                               "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
4312                               "<updated>$cd{'iso-8601'}</updated>\n" .
4313                               "<author><name>" . esc_html($co{'author_name'}) . "</name></author>\n" .
4314                               # use committer for contributor
4315                               "<contributor><name>" . esc_html($co{'committer_name'}) . "</name></contributor>\n" .
4316                               "<published>$cd{'iso-8601'}</published>\n" .
4317                               "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
4318                               "<id>$co_url</id>\n" .
4319                               "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
4320                               "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
4321                 }
4322                 my $comment = $co{'comment'};
4323                 print "<pre>\n";
4324                 foreach my $line (@$comment) {
4325                         $line = esc_html($line);
4326                         print "$line\n";
4327                 }
4328                 print "</pre><ul>\n";
4329                 foreach my $difftree_line (@difftree) {
4330                         my %difftree = parse_difftree_raw_line($difftree_line);
4331                         next if !$difftree{'from_id'};
4333                         my $file = $difftree{'file'} || $difftree{'to_file'};
4335                         print "<li>" .
4336                               "[" .
4337                               $cgi->a({-href => href(-full=>1, action=>"blobdiff",
4338                                                      hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
4339                                                      hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
4340                                                      file_name=>$file, file_parent=>$difftree{'from_file'}),
4341                                       -title => "diff"}, 'D');
4342                         if ($have_blame) {
4343                                 print $cgi->a({-href => href(-full=>1, action=>"blame",
4344                                                              file_name=>$file, hash_base=>$commit),
4345                                               -title => "blame"}, 'B');
4346                         }
4347                         # if this is not a feed of a file history
4348                         if (!defined $file_name || $file_name ne $file) {
4349                                 print $cgi->a({-href => href(-full=>1, action=>"history",
4350                                                              file_name=>$file, hash=>$commit),
4351                                               -title => "history"}, 'H');
4352                         }
4353                         $file = esc_path($file);
4354                         print "] ".
4355                               "$file</li>\n";
4356                 }
4357                 if ($format eq 'rss') {
4358                         print "</ul>]]>\n" .
4359                               "</content:encoded>\n" .
4360                               "</item>\n";
4361                 } elsif ($format eq 'atom') {
4362                         print "</ul>\n</div>\n" .
4363                               "</content>\n" .
4364                               "</entry>\n";
4365                 }
4366         }
4368         # end of feed
4369         if ($format eq 'rss') {
4370                 print "</channel>\n</rss>\n";
4371         }       elsif ($format eq 'atom') {
4372                 print "</feed>\n";
4373         }
4376 sub git_rss {
4377         git_feed('rss');
4380 sub git_atom {
4381         git_feed('atom');
4384 sub git_opml {
4385         my @list = git_get_projects_list();
4387         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
4388         print <<XML;
4389 <?xml version="1.0" encoding="utf-8"?>
4390 <opml version="1.0">
4391 <head>
4392   <title>$site_name OPML Export</title>
4393 </head>
4394 <body>
4395 <outline text="git RSS feeds">
4396 XML
4398         foreach my $pr (@list) {
4399                 my %proj = %$pr;
4400                 my $head = git_get_head_hash($proj{'path'});
4401                 if (!defined $head) {
4402                         next;
4403                 }
4404                 $git_dir = "$projectroot/$proj{'path'}";
4405                 my %co = parse_commit($head);
4406                 if (!%co) {
4407                         next;
4408                 }
4410                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
4411                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
4412                 my $html = "$my_url?p=$proj{'path'};a=summary";
4413                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
4414         }
4415         print <<XML;
4416 </outline>
4417 </body>
4418 </opml>
4419 XML