Code

gitweb: Make the Git logo link target to point to the homepage
[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++" || $ENV{'SERVER_NAME'} || "Untitled";
44 # html text to include at home page
45 our $home_text = "++GITWEB_HOMETEXT++";
47 # URI of default stylesheet
48 our $stylesheet = "++GITWEB_CSS++";
49 # URI of GIT logo
50 our $logo = "++GITWEB_LOGO++";
51 # URI of GIT favicon, assumed to be image/png type
52 our $favicon = "++GITWEB_FAVICON++";
54 our $githelp_url = "http://git.or.cz/";
55 our $githelp_label = "git homepage";
57 # source of projects list
58 our $projects_list = "++GITWEB_LIST++";
60 # show repository only if this file exists
61 # (only effective if this variable evaluates to true)
62 our $export_ok = "++GITWEB_EXPORT_OK++";
64 # only allow viewing of repositories also shown on the overview page
65 our $strict_export = "++GITWEB_STRICT_EXPORT++";
67 # list of git base URLs used for URL to where fetch project from,
68 # i.e. full URL is "$git_base_url/$project"
69 our @git_base_url_list = ("++GITWEB_BASE_URL++");
71 # default blob_plain mimetype and default charset for text/plain blob
72 our $default_blob_plain_mimetype = 'text/plain';
73 our $default_text_plain_charset  = undef;
75 # file to use for guessing MIME types before trying /etc/mime.types
76 # (relative to the current git repository)
77 our $mimetypes_file = undef;
79 # You define site-wide feature defaults here; override them with
80 # $GITWEB_CONFIG as necessary.
81 our %feature = (
82         # feature => {
83         #       'sub' => feature-sub (subroutine),
84         #       'override' => allow-override (boolean),
85         #       'default' => [ default options...] (array reference)}
86         #
87         # if feature is overridable (it means that allow-override has true value,
88         # then feature-sub will be called with default options as parameters;
89         # return value of feature-sub indicates if to enable specified feature
90         #
91         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
93         'blame' => {
94                 'sub' => \&feature_blame,
95                 'override' => 0,
96                 'default' => [0]},
98         'snapshot' => {
99                 'sub' => \&feature_snapshot,
100                 'override' => 0,
101                 #         => [content-encoding, suffix, program]
102                 'default' => ['x-gzip', 'gz', 'gzip']},
104         'pickaxe' => {
105                 'sub' => \&feature_pickaxe,
106                 'override' => 0,
107                 'default' => [1]},
108 );
110 sub gitweb_check_feature {
111         my ($name) = @_;
112         return unless exists $feature{$name};
113         my ($sub, $override, @defaults) = (
114                 $feature{$name}{'sub'},
115                 $feature{$name}{'override'},
116                 @{$feature{$name}{'default'}});
117         if (!$override) { return @defaults; }
118         return $sub->(@defaults);
121 # To enable system wide have in $GITWEB_CONFIG
122 # $feature{'blame'}{'default'} = [1];
123 # To have project specific config enable override in $GITWEB_CONFIG
124 # $feature{'blame'}{'override'} = 1;
125 # and in project config gitweb.blame = 0|1;
127 sub feature_blame {
128         my ($val) = git_get_project_config('blame', '--bool');
130         if ($val eq 'true') {
131                 return 1;
132         } elsif ($val eq 'false') {
133                 return 0;
134         }
136         return $_[0];
139 # To disable system wide have in $GITWEB_CONFIG
140 # $feature{'snapshot'}{'default'} = [undef];
141 # To have project specific config enable override in $GITWEB_CONFIG
142 # $feature{'blame'}{'override'} = 1;
143 # and in project config  gitweb.snapshot = none|gzip|bzip2
145 sub feature_snapshot {
146         my ($ctype, $suffix, $command) = @_;
148         my ($val) = git_get_project_config('snapshot');
150         if ($val eq 'gzip') {
151                 return ('x-gzip', 'gz', 'gzip');
152         } elsif ($val eq 'bzip2') {
153                 return ('x-bzip2', 'bz2', 'bzip2');
154         } elsif ($val eq 'none') {
155                 return ();
156         }
158         return ($ctype, $suffix, $command);
161 sub gitweb_have_snapshot {
162         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
163         my $have_snapshot = (defined $ctype && defined $suffix);
165         return $have_snapshot;
168 # To enable system wide have in $GITWEB_CONFIG
169 # $feature{'pickaxe'}{'default'} = [1];
170 # To have project specific config enable override in $GITWEB_CONFIG
171 # $feature{'pickaxe'}{'override'} = 1;
172 # and in project config gitweb.pickaxe = 0|1;
174 sub feature_pickaxe {
175         my ($val) = git_get_project_config('pickaxe', '--bool');
177         if ($val eq 'true') {
178                 return (1);
179         } elsif ($val eq 'false') {
180                 return (0);
181         }
183         return ($_[0]);
186 # rename detection options for git-diff and git-diff-tree
187 # - default is '-M', with the cost proportional to
188 #   (number of removed files) * (number of new files).
189 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
190 #   (number of changed files + number of removed files) * (number of new files)
191 # - even more costly is '-C', '--find-copies-harder' with cost
192 #   (number of files in the original tree) * (number of new files)
193 # - one might want to include '-B' option, e.g. '-B', '-M'
194 our @diff_opts = ('-M'); # taken from git_commit
196 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
197 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
199 # version of the core git binary
200 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
202 $projects_list ||= $projectroot;
204 # ======================================================================
205 # input validation and dispatch
206 our $action = $cgi->param('a');
207 if (defined $action) {
208         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
209                 die_error(undef, "Invalid action parameter");
210         }
213 # parameters which are pathnames
214 our $project = $cgi->param('p');
215 if (defined $project) {
216         if (!validate_pathname($project) ||
217             !(-d "$projectroot/$project") ||
218             !(-e "$projectroot/$project/HEAD") ||
219             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
220             ($strict_export && !project_in_list($project))) {
221                 undef $project;
222                 die_error(undef, "No such project");
223         }
226 our $file_name = $cgi->param('f');
227 if (defined $file_name) {
228         if (!validate_pathname($file_name)) {
229                 die_error(undef, "Invalid file parameter");
230         }
233 our $file_parent = $cgi->param('fp');
234 if (defined $file_parent) {
235         if (!validate_pathname($file_parent)) {
236                 die_error(undef, "Invalid file parent parameter");
237         }
240 # parameters which are refnames
241 our $hash = $cgi->param('h');
242 if (defined $hash) {
243         if (!validate_refname($hash)) {
244                 die_error(undef, "Invalid hash parameter");
245         }
248 our $hash_parent = $cgi->param('hp');
249 if (defined $hash_parent) {
250         if (!validate_refname($hash_parent)) {
251                 die_error(undef, "Invalid hash parent parameter");
252         }
255 our $hash_base = $cgi->param('hb');
256 if (defined $hash_base) {
257         if (!validate_refname($hash_base)) {
258                 die_error(undef, "Invalid hash base parameter");
259         }
262 our $hash_parent_base = $cgi->param('hpb');
263 if (defined $hash_parent_base) {
264         if (!validate_refname($hash_parent_base)) {
265                 die_error(undef, "Invalid hash parent base parameter");
266         }
269 # other parameters
270 our $page = $cgi->param('pg');
271 if (defined $page) {
272         if ($page =~ m/[^0-9]/) {
273                 die_error(undef, "Invalid page parameter");
274         }
277 our $searchtext = $cgi->param('s');
278 if (defined $searchtext) {
279         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
280                 die_error(undef, "Invalid search parameter");
281         }
282         $searchtext = quotemeta $searchtext;
285 # now read PATH_INFO and use it as alternative to parameters
286 sub evaluate_path_info {
287         return if defined $project;
288         my $path_info = $ENV{"PATH_INFO"};
289         return if !$path_info;
290         $path_info =~ s,^/+,,;
291         return if !$path_info;
292         # find which part of PATH_INFO is project
293         $project = $path_info;
294         $project =~ s,/+$,,;
295         while ($project && !-e "$projectroot/$project/HEAD") {
296                 $project =~ s,/*[^/]*$,,;
297         }
298         # validate project
299         $project = validate_pathname($project);
300         if (!$project ||
301             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
302             ($strict_export && !project_in_list($project))) {
303                 undef $project;
304                 return;
305         }
306         # do not change any parameters if an action is given using the query string
307         return if $action;
308         $path_info =~ s,^$project/*,,;
309         my ($refname, $pathname) = split(/:/, $path_info, 2);
310         if (defined $pathname) {
311                 # we got "project.git/branch:filename" or "project.git/branch:dir/"
312                 # we could use git_get_type(branch:pathname), but it needs $git_dir
313                 $pathname =~ s,^/+,,;
314                 if (!$pathname || substr($pathname, -1) eq "/") {
315                         $action  ||= "tree";
316                         $pathname =~ s,/$,,;
317                 } else {
318                         $action  ||= "blob_plain";
319                 }
320                 $hash_base ||= validate_refname($refname);
321                 $file_name ||= validate_pathname($pathname);
322         } elsif (defined $refname) {
323                 # we got "project.git/branch"
324                 $action ||= "shortlog";
325                 $hash   ||= validate_refname($refname);
326         }
328 evaluate_path_info();
330 # path to the current git repository
331 our $git_dir;
332 $git_dir = "$projectroot/$project" if $project;
334 # dispatch
335 my %actions = (
336         "blame" => \&git_blame2,
337         "blobdiff" => \&git_blobdiff,
338         "blobdiff_plain" => \&git_blobdiff_plain,
339         "blob" => \&git_blob,
340         "blob_plain" => \&git_blob_plain,
341         "commitdiff" => \&git_commitdiff,
342         "commitdiff_plain" => \&git_commitdiff_plain,
343         "commit" => \&git_commit,
344         "heads" => \&git_heads,
345         "history" => \&git_history,
346         "log" => \&git_log,
347         "rss" => \&git_rss,
348         "search" => \&git_search,
349         "shortlog" => \&git_shortlog,
350         "summary" => \&git_summary,
351         "tag" => \&git_tag,
352         "tags" => \&git_tags,
353         "tree" => \&git_tree,
354         "snapshot" => \&git_snapshot,
355         # those below don't need $project
356         "opml" => \&git_opml,
357         "project_list" => \&git_project_list,
358         "project_index" => \&git_project_index,
359 );
361 if (defined $project) {
362         $action ||= 'summary';
363 } else {
364         $action ||= 'project_list';
366 if (!defined($actions{$action})) {
367         die_error(undef, "Unknown action");
369 if ($action !~ m/^(opml|project_list|project_index)$/ &&
370     !$project) {
371         die_error(undef, "Project needed");
373 $actions{$action}->();
374 exit;
376 ## ======================================================================
377 ## action links
379 sub href(%) {
380         my %params = @_;
382         my @mapping = (
383                 project => "p",
384                 action => "a",
385                 file_name => "f",
386                 file_parent => "fp",
387                 hash => "h",
388                 hash_parent => "hp",
389                 hash_base => "hb",
390                 hash_parent_base => "hpb",
391                 page => "pg",
392                 order => "o",
393                 searchtext => "s",
394         );
395         my %mapping = @mapping;
397         $params{'project'} = $project unless exists $params{'project'};
399         my @result = ();
400         for (my $i = 0; $i < @mapping; $i += 2) {
401                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
402                 if (defined $params{$name}) {
403                         push @result, $symbol . "=" . esc_param($params{$name});
404                 }
405         }
406         return "$my_uri?" . join(';', @result);
410 ## ======================================================================
411 ## validation, quoting/unquoting and escaping
413 sub validate_pathname {
414         my $input = shift || return undef;
416         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
417         # at the beginning, at the end, and between slashes.
418         # also this catches doubled slashes
419         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
420                 return undef;
421         }
422         # no null characters
423         if ($input =~ m!\0!) {
424                 return undef;
425         }
426         return $input;
429 sub validate_refname {
430         my $input = shift || return undef;
432         # textual hashes are O.K.
433         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
434                 return $input;
435         }
436         # it must be correct pathname
437         $input = validate_pathname($input)
438                 or return undef;
439         # restrictions on ref name according to git-check-ref-format
440         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
441                 return undef;
442         }
443         return $input;
446 # quote unsafe chars, but keep the slash, even when it's not
447 # correct, but quoted slashes look too horrible in bookmarks
448 sub esc_param {
449         my $str = shift;
450         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
451         $str =~ s/\+/%2B/g;
452         $str =~ s/ /\+/g;
453         return $str;
456 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
457 sub esc_url {
458         my $str = shift;
459         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
460         $str =~ s/\+/%2B/g;
461         $str =~ s/ /\+/g;
462         return $str;
465 # replace invalid utf8 character with SUBSTITUTION sequence
466 sub esc_html {
467         my $str = shift;
468         $str = decode("utf8", $str, Encode::FB_DEFAULT);
469         $str = escapeHTML($str);
470         $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
471         $str =~ s/\033/^[/g; # "escape" ESCAPE (\e) character (e.g. commit 20a3847d8a5032ce41f90dcc68abfb36e6fee9b1)
472         return $str;
475 # git may return quoted and escaped filenames
476 sub unquote {
477         my $str = shift;
478         if ($str =~ m/^"(.*)"$/) {
479                 $str = $1;
480                 $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
481         }
482         return $str;
485 # escape tabs (convert tabs to spaces)
486 sub untabify {
487         my $line = shift;
489         while ((my $pos = index($line, "\t")) != -1) {
490                 if (my $count = (8 - ($pos % 8))) {
491                         my $spaces = ' ' x $count;
492                         $line =~ s/\t/$spaces/;
493                 }
494         }
496         return $line;
499 sub project_in_list {
500         my $project = shift;
501         my @list = git_get_projects_list();
502         return @list && scalar(grep { $_->{'path'} eq $project } @list);
505 ## ----------------------------------------------------------------------
506 ## HTML aware string manipulation
508 sub chop_str {
509         my $str = shift;
510         my $len = shift;
511         my $add_len = shift || 10;
513         # allow only $len chars, but don't cut a word if it would fit in $add_len
514         # if it doesn't fit, cut it if it's still longer than the dots we would add
515         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
516         my $body = $1;
517         my $tail = $2;
518         if (length($tail) > 4) {
519                 $tail = " ...";
520                 $body =~ s/&[^;]*$//; # remove chopped character entities
521         }
522         return "$body$tail";
525 ## ----------------------------------------------------------------------
526 ## functions returning short strings
528 # CSS class for given age value (in seconds)
529 sub age_class {
530         my $age = shift;
532         if ($age < 60*60*2) {
533                 return "age0";
534         } elsif ($age < 60*60*24*2) {
535                 return "age1";
536         } else {
537                 return "age2";
538         }
541 # convert age in seconds to "nn units ago" string
542 sub age_string {
543         my $age = shift;
544         my $age_str;
546         if ($age > 60*60*24*365*2) {
547                 $age_str = (int $age/60/60/24/365);
548                 $age_str .= " years ago";
549         } elsif ($age > 60*60*24*(365/12)*2) {
550                 $age_str = int $age/60/60/24/(365/12);
551                 $age_str .= " months ago";
552         } elsif ($age > 60*60*24*7*2) {
553                 $age_str = int $age/60/60/24/7;
554                 $age_str .= " weeks ago";
555         } elsif ($age > 60*60*24*2) {
556                 $age_str = int $age/60/60/24;
557                 $age_str .= " days ago";
558         } elsif ($age > 60*60*2) {
559                 $age_str = int $age/60/60;
560                 $age_str .= " hours ago";
561         } elsif ($age > 60*2) {
562                 $age_str = int $age/60;
563                 $age_str .= " min ago";
564         } elsif ($age > 2) {
565                 $age_str = int $age;
566                 $age_str .= " sec ago";
567         } else {
568                 $age_str .= " right now";
569         }
570         return $age_str;
573 # convert file mode in octal to symbolic file mode string
574 sub mode_str {
575         my $mode = oct shift;
577         if (S_ISDIR($mode & S_IFMT)) {
578                 return 'drwxr-xr-x';
579         } elsif (S_ISLNK($mode)) {
580                 return 'lrwxrwxrwx';
581         } elsif (S_ISREG($mode)) {
582                 # git cares only about the executable bit
583                 if ($mode & S_IXUSR) {
584                         return '-rwxr-xr-x';
585                 } else {
586                         return '-rw-r--r--';
587                 };
588         } else {
589                 return '----------';
590         }
593 # convert file mode in octal to file type string
594 sub file_type {
595         my $mode = shift;
597         if ($mode !~ m/^[0-7]+$/) {
598                 return $mode;
599         } else {
600                 $mode = oct $mode;
601         }
603         if (S_ISDIR($mode & S_IFMT)) {
604                 return "directory";
605         } elsif (S_ISLNK($mode)) {
606                 return "symlink";
607         } elsif (S_ISREG($mode)) {
608                 return "file";
609         } else {
610                 return "unknown";
611         }
614 ## ----------------------------------------------------------------------
615 ## functions returning short HTML fragments, or transforming HTML fragments
616 ## which don't beling to other sections
618 # format line of commit message or tag comment
619 sub format_log_line_html {
620         my $line = shift;
622         $line = esc_html($line);
623         $line =~ s/ /&nbsp;/g;
624         if ($line =~ m/([0-9a-fA-F]{40})/) {
625                 my $hash_text = $1;
626                 if (git_get_type($hash_text) eq "commit") {
627                         my $link =
628                                 $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
629                                         -class => "text"}, $hash_text);
630                         $line =~ s/$hash_text/$link/;
631                 }
632         }
633         return $line;
636 # format marker of refs pointing to given object
637 sub format_ref_marker {
638         my ($refs, $id) = @_;
639         my $markers = '';
641         if (defined $refs->{$id}) {
642                 foreach my $ref (@{$refs->{$id}}) {
643                         my ($type, $name) = qw();
644                         # e.g. tags/v2.6.11 or heads/next
645                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
646                                 $type = $1;
647                                 $name = $2;
648                         } else {
649                                 $type = "ref";
650                                 $name = $ref;
651                         }
653                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
654                 }
655         }
657         if ($markers) {
658                 return ' <span class="refs">'. $markers . '</span>';
659         } else {
660                 return "";
661         }
664 # format, perhaps shortened and with markers, title line
665 sub format_subject_html {
666         my ($long, $short, $href, $extra) = @_;
667         $extra = '' unless defined($extra);
669         if (length($short) < length($long)) {
670                 return $cgi->a({-href => $href, -class => "list subject",
671                                 -title => decode("utf8", $long, Encode::FB_DEFAULT)},
672                        esc_html($short) . $extra);
673         } else {
674                 return $cgi->a({-href => $href, -class => "list subject"},
675                        esc_html($long)  . $extra);
676         }
679 sub format_diff_line {
680         my $line = shift;
681         my $char = substr($line, 0, 1);
682         my $diff_class = "";
684         chomp $line;
686         if ($char eq '+') {
687                 $diff_class = " add";
688         } elsif ($char eq "-") {
689                 $diff_class = " rem";
690         } elsif ($char eq "@") {
691                 $diff_class = " chunk_header";
692         } elsif ($char eq "\\") {
693                 $diff_class = " incomplete";
694         }
695         $line = untabify($line);
696         return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
699 ## ----------------------------------------------------------------------
700 ## git utility subroutines, invoking git commands
702 # returns path to the core git executable and the --git-dir parameter as list
703 sub git_cmd {
704         return $GIT, '--git-dir='.$git_dir;
707 # returns path to the core git executable and the --git-dir parameter as string
708 sub git_cmd_str {
709         return join(' ', git_cmd());
712 # get HEAD ref of given project as hash
713 sub git_get_head_hash {
714         my $project = shift;
715         my $o_git_dir = $git_dir;
716         my $retval = undef;
717         $git_dir = "$projectroot/$project";
718         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
719                 my $head = <$fd>;
720                 close $fd;
721                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
722                         $retval = $1;
723                 }
724         }
725         if (defined $o_git_dir) {
726                 $git_dir = $o_git_dir;
727         }
728         return $retval;
731 # get type of given object
732 sub git_get_type {
733         my $hash = shift;
735         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
736         my $type = <$fd>;
737         close $fd or return;
738         chomp $type;
739         return $type;
742 sub git_get_project_config {
743         my ($key, $type) = @_;
745         return unless ($key);
746         $key =~ s/^gitweb\.//;
747         return if ($key =~ m/\W/);
749         my @x = (git_cmd(), 'repo-config');
750         if (defined $type) { push @x, $type; }
751         push @x, "--get";
752         push @x, "gitweb.$key";
753         my $val = qx(@x);
754         chomp $val;
755         return ($val);
758 # get hash of given path at given ref
759 sub git_get_hash_by_path {
760         my $base = shift;
761         my $path = shift || return undef;
762         my $type = shift;
764         $path =~ s,/+$,,;
766         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
767                 or die_error(undef, "Open git-ls-tree failed");
768         my $line = <$fd>;
769         close $fd or return undef;
771         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
772         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
773         if (defined $type && $type ne $2) {
774                 # type doesn't match
775                 return undef;
776         }
777         return $3;
780 ## ......................................................................
781 ## git utility functions, directly accessing git repository
783 sub git_get_project_description {
784         my $path = shift;
786         open my $fd, "$projectroot/$path/description" or return undef;
787         my $descr = <$fd>;
788         close $fd;
789         chomp $descr;
790         return $descr;
793 sub git_get_project_url_list {
794         my $path = shift;
796         open my $fd, "$projectroot/$path/cloneurl" or return;
797         my @git_project_url_list = map { chomp; $_ } <$fd>;
798         close $fd;
800         return wantarray ? @git_project_url_list : \@git_project_url_list;
803 sub git_get_projects_list {
804         my @list;
806         if (-d $projects_list) {
807                 # search in directory
808                 my $dir = $projects_list;
809                 my $pfxlen = length("$dir");
811                 File::Find::find({
812                         follow_fast => 1, # follow symbolic links
813                         dangling_symlinks => 0, # ignore dangling symlinks, silently
814                         wanted => sub {
815                                 # skip project-list toplevel, if we get it.
816                                 return if (m!^[/.]$!);
817                                 # only directories can be git repositories
818                                 return unless (-d $_);
820                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
821                                 # we check related file in $projectroot
822                                 if (-e "$projectroot/$subdir/HEAD" && (!$export_ok ||
823                                     -e "$projectroot/$subdir/$export_ok")) {
824                                         push @list, { path => $subdir };
825                                         $File::Find::prune = 1;
826                                 }
827                         },
828                 }, "$dir");
830         } elsif (-f $projects_list) {
831                 # read from file(url-encoded):
832                 # 'git%2Fgit.git Linus+Torvalds'
833                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
834                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
835                 open my ($fd), $projects_list or return;
836                 while (my $line = <$fd>) {
837                         chomp $line;
838                         my ($path, $owner) = split ' ', $line;
839                         $path = unescape($path);
840                         $owner = unescape($owner);
841                         if (!defined $path) {
842                                 next;
843                         }
844                         if (-e "$projectroot/$path/HEAD" && (!$export_ok ||
845                             -e "$projectroot/$path/$export_ok")) {
846                                 my $pr = {
847                                         path => $path,
848                                         owner => decode("utf8", $owner, Encode::FB_DEFAULT),
849                                 };
850                                 push @list, $pr
851                         }
852                 }
853                 close $fd;
854         }
855         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
856         return @list;
859 sub git_get_project_owner {
860         my $project = shift;
861         my $owner;
863         return undef unless $project;
865         # read from file (url-encoded):
866         # 'git%2Fgit.git Linus+Torvalds'
867         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
868         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
869         if (-f $projects_list) {
870                 open (my $fd , $projects_list);
871                 while (my $line = <$fd>) {
872                         chomp $line;
873                         my ($pr, $ow) = split ' ', $line;
874                         $pr = unescape($pr);
875                         $ow = unescape($ow);
876                         if ($pr eq $project) {
877                                 $owner = decode("utf8", $ow, Encode::FB_DEFAULT);
878                                 last;
879                         }
880                 }
881                 close $fd;
882         }
883         if (!defined $owner) {
884                 $owner = get_file_owner("$projectroot/$project");
885         }
887         return $owner;
890 sub git_get_references {
891         my $type = shift || "";
892         my %refs;
893         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
894         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
895         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
896                 or return;
898         while (my $line = <$fd>) {
899                 chomp $line;
900                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
901                         if (defined $refs{$1}) {
902                                 push @{$refs{$1}}, $2;
903                         } else {
904                                 $refs{$1} = [ $2 ];
905                         }
906                 }
907         }
908         close $fd or return;
909         return \%refs;
912 sub git_get_rev_name_tags {
913         my $hash = shift || return undef;
915         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
916                 or return;
917         my $name_rev = <$fd>;
918         close $fd;
920         if ($name_rev =~ m|^$hash tags/(.*)$|) {
921                 return $1;
922         } else {
923                 # catches also '$hash undefined' output
924                 return undef;
925         }
928 ## ----------------------------------------------------------------------
929 ## parse to hash functions
931 sub parse_date {
932         my $epoch = shift;
933         my $tz = shift || "-0000";
935         my %date;
936         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
937         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
938         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
939         $date{'hour'} = $hour;
940         $date{'minute'} = $min;
941         $date{'mday'} = $mday;
942         $date{'day'} = $days[$wday];
943         $date{'month'} = $months[$mon];
944         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
945                            $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
946         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
947                              $mday, $months[$mon], $hour ,$min;
949         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
950         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
951         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
952         $date{'hour_local'} = $hour;
953         $date{'minute_local'} = $min;
954         $date{'tz_local'} = $tz;
955         return %date;
958 sub parse_tag {
959         my $tag_id = shift;
960         my %tag;
961         my @comment;
963         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
964         $tag{'id'} = $tag_id;
965         while (my $line = <$fd>) {
966                 chomp $line;
967                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
968                         $tag{'object'} = $1;
969                 } elsif ($line =~ m/^type (.+)$/) {
970                         $tag{'type'} = $1;
971                 } elsif ($line =~ m/^tag (.+)$/) {
972                         $tag{'name'} = $1;
973                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
974                         $tag{'author'} = $1;
975                         $tag{'epoch'} = $2;
976                         $tag{'tz'} = $3;
977                 } elsif ($line =~ m/--BEGIN/) {
978                         push @comment, $line;
979                         last;
980                 } elsif ($line eq "") {
981                         last;
982                 }
983         }
984         push @comment, <$fd>;
985         $tag{'comment'} = \@comment;
986         close $fd or return;
987         if (!defined $tag{'name'}) {
988                 return
989         };
990         return %tag
993 sub parse_commit {
994         my $commit_id = shift;
995         my $commit_text = shift;
997         my @commit_lines;
998         my %co;
1000         if (defined $commit_text) {
1001                 @commit_lines = @$commit_text;
1002         } else {
1003                 $/ = "\0";
1004                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
1005                         or return;
1006                 @commit_lines = split '\n', <$fd>;
1007                 close $fd or return;
1008                 $/ = "\n";
1009                 pop @commit_lines;
1010         }
1011         my $header = shift @commit_lines;
1012         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1013                 return;
1014         }
1015         ($co{'id'}, my @parents) = split ' ', $header;
1016         $co{'parents'} = \@parents;
1017         $co{'parent'} = $parents[0];
1018         while (my $line = shift @commit_lines) {
1019                 last if $line eq "\n";
1020                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1021                         $co{'tree'} = $1;
1022                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1023                         $co{'author'} = $1;
1024                         $co{'author_epoch'} = $2;
1025                         $co{'author_tz'} = $3;
1026                         if ($co{'author'} =~ m/^([^<]+) </) {
1027                                 $co{'author_name'} = $1;
1028                         } else {
1029                                 $co{'author_name'} = $co{'author'};
1030                         }
1031                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1032                         $co{'committer'} = $1;
1033                         $co{'committer_epoch'} = $2;
1034                         $co{'committer_tz'} = $3;
1035                         $co{'committer_name'} = $co{'committer'};
1036                         $co{'committer_name'} =~ s/ <.*//;
1037                 }
1038         }
1039         if (!defined $co{'tree'}) {
1040                 return;
1041         };
1043         foreach my $title (@commit_lines) {
1044                 $title =~ s/^    //;
1045                 if ($title ne "") {
1046                         $co{'title'} = chop_str($title, 80, 5);
1047                         # remove leading stuff of merges to make the interesting part visible
1048                         if (length($title) > 50) {
1049                                 $title =~ s/^Automatic //;
1050                                 $title =~ s/^merge (of|with) /Merge ... /i;
1051                                 if (length($title) > 50) {
1052                                         $title =~ s/(http|rsync):\/\///;
1053                                 }
1054                                 if (length($title) > 50) {
1055                                         $title =~ s/(master|www|rsync)\.//;
1056                                 }
1057                                 if (length($title) > 50) {
1058                                         $title =~ s/kernel.org:?//;
1059                                 }
1060                                 if (length($title) > 50) {
1061                                         $title =~ s/\/pub\/scm//;
1062                                 }
1063                         }
1064                         $co{'title_short'} = chop_str($title, 50, 5);
1065                         last;
1066                 }
1067         }
1068         # remove added spaces
1069         foreach my $line (@commit_lines) {
1070                 $line =~ s/^    //;
1071         }
1072         $co{'comment'} = \@commit_lines;
1074         my $age = time - $co{'committer_epoch'};
1075         $co{'age'} = $age;
1076         $co{'age_string'} = age_string($age);
1077         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1078         if ($age > 60*60*24*7*2) {
1079                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1080                 $co{'age_string_age'} = $co{'age_string'};
1081         } else {
1082                 $co{'age_string_date'} = $co{'age_string'};
1083                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1084         }
1085         return %co;
1088 # parse ref from ref_file, given by ref_id, with given type
1089 sub parse_ref {
1090         my $ref_file = shift;
1091         my $ref_id = shift;
1092         my $type = shift || git_get_type($ref_id);
1093         my %ref_item;
1095         $ref_item{'type'} = $type;
1096         $ref_item{'id'} = $ref_id;
1097         $ref_item{'epoch'} = 0;
1098         $ref_item{'age'} = "unknown";
1099         if ($type eq "tag") {
1100                 my %tag = parse_tag($ref_id);
1101                 $ref_item{'comment'} = $tag{'comment'};
1102                 if ($tag{'type'} eq "commit") {
1103                         my %co = parse_commit($tag{'object'});
1104                         $ref_item{'epoch'} = $co{'committer_epoch'};
1105                         $ref_item{'age'} = $co{'age_string'};
1106                 } elsif (defined($tag{'epoch'})) {
1107                         my $age = time - $tag{'epoch'};
1108                         $ref_item{'epoch'} = $tag{'epoch'};
1109                         $ref_item{'age'} = age_string($age);
1110                 }
1111                 $ref_item{'reftype'} = $tag{'type'};
1112                 $ref_item{'name'} = $tag{'name'};
1113                 $ref_item{'refid'} = $tag{'object'};
1114         } elsif ($type eq "commit"){
1115                 my %co = parse_commit($ref_id);
1116                 $ref_item{'reftype'} = "commit";
1117                 $ref_item{'name'} = $ref_file;
1118                 $ref_item{'title'} = $co{'title'};
1119                 $ref_item{'refid'} = $ref_id;
1120                 $ref_item{'epoch'} = $co{'committer_epoch'};
1121                 $ref_item{'age'} = $co{'age_string'};
1122         } else {
1123                 $ref_item{'reftype'} = $type;
1124                 $ref_item{'name'} = $ref_file;
1125                 $ref_item{'refid'} = $ref_id;
1126         }
1128         return %ref_item;
1131 # parse line of git-diff-tree "raw" output
1132 sub parse_difftree_raw_line {
1133         my $line = shift;
1134         my %res;
1136         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1137         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1138         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1139                 $res{'from_mode'} = $1;
1140                 $res{'to_mode'} = $2;
1141                 $res{'from_id'} = $3;
1142                 $res{'to_id'} = $4;
1143                 $res{'status'} = $5;
1144                 $res{'similarity'} = $6;
1145                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1146                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1147                 } else {
1148                         $res{'file'} = unquote($7);
1149                 }
1150         }
1151         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1152         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1153                 $res{'commit'} = $1;
1154         }
1156         return wantarray ? %res : \%res;
1159 # parse line of git-ls-tree output
1160 sub parse_ls_tree_line ($;%) {
1161         my $line = shift;
1162         my %opts = @_;
1163         my %res;
1165         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1166         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1168         $res{'mode'} = $1;
1169         $res{'type'} = $2;
1170         $res{'hash'} = $3;
1171         if ($opts{'-z'}) {
1172                 $res{'name'} = $4;
1173         } else {
1174                 $res{'name'} = unquote($4);
1175         }
1177         return wantarray ? %res : \%res;
1180 ## ......................................................................
1181 ## parse to array of hashes functions
1183 sub git_get_refs_list {
1184         my $type = shift || "";
1185         my %refs;
1186         my @reflist;
1188         my @refs;
1189         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1190                 or return;
1191         while (my $line = <$fd>) {
1192                 chomp $line;
1193                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?([^\^]+))(\^\{\})?$/) {
1194                         if (defined $refs{$1}) {
1195                                 push @{$refs{$1}}, $2;
1196                         } else {
1197                                 $refs{$1} = [ $2 ];
1198                         }
1200                         if (! $4) { # unpeeled, direct reference
1201                                 push @refs, { hash => $1, name => $3 }; # without type
1202                         } elsif ($3 eq $refs[-1]{'name'}) {
1203                                 # most likely a tag is followed by its peeled
1204                                 # (deref) one, and when that happens we know the
1205                                 # previous one was of type 'tag'.
1206                                 $refs[-1]{'type'} = "tag";
1207                         }
1208                 }
1209         }
1210         close $fd;
1212         foreach my $ref (@refs) {
1213                 my $ref_file = $ref->{'name'};
1214                 my $ref_id   = $ref->{'hash'};
1216                 my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1217                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
1219                 push @reflist, \%ref_item;
1220         }
1221         # sort refs by age
1222         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1223         return (\@reflist, \%refs);
1226 ## ----------------------------------------------------------------------
1227 ## filesystem-related functions
1229 sub get_file_owner {
1230         my $path = shift;
1232         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1233         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1234         if (!defined $gcos) {
1235                 return undef;
1236         }
1237         my $owner = $gcos;
1238         $owner =~ s/[,;].*$//;
1239         return decode("utf8", $owner, Encode::FB_DEFAULT);
1242 ## ......................................................................
1243 ## mimetype related functions
1245 sub mimetype_guess_file {
1246         my $filename = shift;
1247         my $mimemap = shift;
1248         -r $mimemap or return undef;
1250         my %mimemap;
1251         open(MIME, $mimemap) or return undef;
1252         while (<MIME>) {
1253                 next if m/^#/; # skip comments
1254                 my ($mime, $exts) = split(/\t+/);
1255                 if (defined $exts) {
1256                         my @exts = split(/\s+/, $exts);
1257                         foreach my $ext (@exts) {
1258                                 $mimemap{$ext} = $mime;
1259                         }
1260                 }
1261         }
1262         close(MIME);
1264         $filename =~ /\.([^.]*)$/;
1265         return $mimemap{$1};
1268 sub mimetype_guess {
1269         my $filename = shift;
1270         my $mime;
1271         $filename =~ /\./ or return undef;
1273         if ($mimetypes_file) {
1274                 my $file = $mimetypes_file;
1275                 if ($file !~ m!^/!) { # if it is relative path
1276                         # it is relative to project
1277                         $file = "$projectroot/$project/$file";
1278                 }
1279                 $mime = mimetype_guess_file($filename, $file);
1280         }
1281         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1282         return $mime;
1285 sub blob_mimetype {
1286         my $fd = shift;
1287         my $filename = shift;
1289         if ($filename) {
1290                 my $mime = mimetype_guess($filename);
1291                 $mime and return $mime;
1292         }
1294         # just in case
1295         return $default_blob_plain_mimetype unless $fd;
1297         if (-T $fd) {
1298                 return 'text/plain' .
1299                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1300         } elsif (! $filename) {
1301                 return 'application/octet-stream';
1302         } elsif ($filename =~ m/\.png$/i) {
1303                 return 'image/png';
1304         } elsif ($filename =~ m/\.gif$/i) {
1305                 return 'image/gif';
1306         } elsif ($filename =~ m/\.jpe?g$/i) {
1307                 return 'image/jpeg';
1308         } else {
1309                 return 'application/octet-stream';
1310         }
1313 ## ======================================================================
1314 ## functions printing HTML: header, footer, error page
1316 sub git_header_html {
1317         my $status = shift || "200 OK";
1318         my $expires = shift;
1320         my $title = "$site_name git";
1321         if (defined $project) {
1322                 $title .= " - $project";
1323                 if (defined $action) {
1324                         $title .= "/$action";
1325                         if (defined $file_name) {
1326                                 $title .= " - " . esc_html($file_name);
1327                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1328                                         $title .= "/";
1329                                 }
1330                         }
1331                 }
1332         }
1333         my $content_type;
1334         # require explicit support from the UA if we are to send the page as
1335         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1336         # we have to do this because MSIE sometimes globs '*/*', pretending to
1337         # support xhtml+xml but choking when it gets what it asked for.
1338         if (defined $cgi->http('HTTP_ACCEPT') &&
1339             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1340             $cgi->Accept('application/xhtml+xml') != 0) {
1341                 $content_type = 'application/xhtml+xml';
1342         } else {
1343                 $content_type = 'text/html';
1344         }
1345         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1346                            -status=> $status, -expires => $expires);
1347         print <<EOF;
1348 <?xml version="1.0" encoding="utf-8"?>
1349 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1350 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1351 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1352 <!-- git core binaries version $git_version -->
1353 <head>
1354 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1355 <meta name="generator" content="gitweb/$version git/$git_version"/>
1356 <meta name="robots" content="index, nofollow"/>
1357 <title>$title</title>
1358 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1359 EOF
1360         if (defined $project) {
1361                 printf('<link rel="alternate" title="%s log" '.
1362                        'href="%s" type="application/rss+xml"/>'."\n",
1363                        esc_param($project), href(action=>"rss"));
1364         } else {
1365                 printf('<link rel="alternate" title="%s projects list" '.
1366                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1367                        $site_name, href(project=>undef, action=>"project_index"));
1368                 printf('<link rel="alternate" title="%s projects logs" '.
1369                        'href="%s" type="text/x-opml"/>'."\n",
1370                        $site_name, href(project=>undef, action=>"opml"));
1371         }
1372         if (defined $favicon) {
1373                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1374         }
1376         print "</head>\n" .
1377               "<body>\n" .
1378               "<div class=\"page_header\">\n" .
1379               "<a href=\"" . esc_html($githelp_url) .
1380               "\" title=\"" . esc_html($githelp_label) .
1381               "\">" .
1382               "<img src=\"$logo\" width=\"72\" height=\"27\" alt=\"git\" style=\"float:right; border-width:0px;\"/>" .
1383               "</a>\n";
1384         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1385         if (defined $project) {
1386                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1387                 if (defined $action) {
1388                         print " / $action";
1389                 }
1390                 print "\n";
1391                 if (!defined $searchtext) {
1392                         $searchtext = "";
1393                 }
1394                 my $search_hash;
1395                 if (defined $hash_base) {
1396                         $search_hash = $hash_base;
1397                 } elsif (defined $hash) {
1398                         $search_hash = $hash;
1399                 } else {
1400                         $search_hash = "HEAD";
1401                 }
1402                 $cgi->param("a", "search");
1403                 $cgi->param("h", $search_hash);
1404                 print $cgi->startform(-method => "get", -action => $my_uri) .
1405                       "<div class=\"search\">\n" .
1406                       $cgi->hidden(-name => "p") . "\n" .
1407                       $cgi->hidden(-name => "a") . "\n" .
1408                       $cgi->hidden(-name => "h") . "\n" .
1409                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1410                       "</div>" .
1411                       $cgi->end_form() . "\n";
1412         }
1413         print "</div>\n";
1416 sub git_footer_html {
1417         print "<div class=\"page_footer\">\n";
1418         if (defined $project) {
1419                 my $descr = git_get_project_description($project);
1420                 if (defined $descr) {
1421                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1422                 }
1423                 print $cgi->a({-href => href(action=>"rss"),
1424                               -class => "rss_logo"}, "RSS") . "\n";
1425         } else {
1426                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1427                               -class => "rss_logo"}, "OPML") . " ";
1428                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1429                               -class => "rss_logo"}, "TXT") . "\n";
1430         }
1431         print "</div>\n" .
1432               "</body>\n" .
1433               "</html>";
1436 sub die_error {
1437         my $status = shift || "403 Forbidden";
1438         my $error = shift || "Malformed query, file missing or permission denied";
1440         git_header_html($status);
1441         print <<EOF;
1442 <div class="page_body">
1443 <br /><br />
1444 $status - $error
1445 <br />
1446 </div>
1447 EOF
1448         git_footer_html();
1449         exit;
1452 ## ----------------------------------------------------------------------
1453 ## functions printing or outputting HTML: navigation
1455 sub git_print_page_nav {
1456         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1457         $extra = '' if !defined $extra; # pager or formats
1459         my @navs = qw(summary shortlog log commit commitdiff tree);
1460         if ($suppress) {
1461                 @navs = grep { $_ ne $suppress } @navs;
1462         }
1464         my %arg = map { $_ => {action=>$_} } @navs;
1465         if (defined $head) {
1466                 for (qw(commit commitdiff)) {
1467                         $arg{$_}{hash} = $head;
1468                 }
1469                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1470                         for (qw(shortlog log)) {
1471                                 $arg{$_}{hash} = $head;
1472                         }
1473                 }
1474         }
1475         $arg{tree}{hash} = $treehead if defined $treehead;
1476         $arg{tree}{hash_base} = $treebase if defined $treebase;
1478         print "<div class=\"page_nav\">\n" .
1479                 (join " | ",
1480                  map { $_ eq $current ?
1481                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1482                  } @navs);
1483         print "<br/>\n$extra<br/>\n" .
1484               "</div>\n";
1487 sub format_paging_nav {
1488         my ($action, $hash, $head, $page, $nrevs) = @_;
1489         my $paging_nav;
1492         if ($hash ne $head || $page) {
1493                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1494         } else {
1495                 $paging_nav .= "HEAD";
1496         }
1498         if ($page > 0) {
1499                 $paging_nav .= " &sdot; " .
1500                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1501                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1502         } else {
1503                 $paging_nav .= " &sdot; prev";
1504         }
1506         if ($nrevs >= (100 * ($page+1)-1)) {
1507                 $paging_nav .= " &sdot; " .
1508                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1509                                  -accesskey => "n", -title => "Alt-n"}, "next");
1510         } else {
1511                 $paging_nav .= " &sdot; next";
1512         }
1514         return $paging_nav;
1517 ## ......................................................................
1518 ## functions printing or outputting HTML: div
1520 sub git_print_header_div {
1521         my ($action, $title, $hash, $hash_base) = @_;
1522         my %args = ();
1524         $args{action} = $action;
1525         $args{hash} = $hash if $hash;
1526         $args{hash_base} = $hash_base if $hash_base;
1528         print "<div class=\"header\">\n" .
1529               $cgi->a({-href => href(%args), -class => "title"},
1530               $title ? $title : $action) .
1531               "\n</div>\n";
1534 #sub git_print_authorship (\%) {
1535 sub git_print_authorship {
1536         my $co = shift;
1538         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1539         print "<div class=\"author_date\">" .
1540               esc_html($co->{'author_name'}) .
1541               " [$ad{'rfc2822'}";
1542         if ($ad{'hour_local'} < 6) {
1543                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1544                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1545         } else {
1546                 printf(" (%02d:%02d %s)",
1547                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1548         }
1549         print "]</div>\n";
1552 sub git_print_page_path {
1553         my $name = shift;
1554         my $type = shift;
1555         my $hb = shift;
1557         if (!defined $name) {
1558                 print "<div class=\"page_path\">/</div>\n";
1559         } else {
1560                 my @dirname = split '/', $name;
1561                 my $basename = pop @dirname;
1562                 my $fullname = '';
1564                 print "<div class=\"page_path\">";
1565                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1566                               -title => 'tree root'}, "[$project]");
1567                 print " / ";
1568                 foreach my $dir (@dirname) {
1569                         $fullname .= ($fullname ? '/' : '') . $dir;
1570                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1571                                                      hash_base=>$hb),
1572                                       -title => $fullname}, esc_html($dir));
1573                         print " / ";
1574                 }
1575                 if (defined $type && $type eq 'blob') {
1576                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1577                                                      hash_base=>$hb),
1578                                       -title => $name}, esc_html($basename));
1579                 } elsif (defined $type && $type eq 'tree') {
1580                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1581                                                      hash_base=>$hb),
1582                                       -title => $name}, esc_html($basename));
1583                 } else {
1584                         print esc_html($basename);
1585                 }
1586                 print "<br/></div>\n";
1587         }
1590 # sub git_print_log (\@;%) {
1591 sub git_print_log ($;%) {
1592         my $log = shift;
1593         my %opts = @_;
1595         if ($opts{'-remove_title'}) {
1596                 # remove title, i.e. first line of log
1597                 shift @$log;
1598         }
1599         # remove leading empty lines
1600         while (defined $log->[0] && $log->[0] eq "") {
1601                 shift @$log;
1602         }
1604         # print log
1605         my $signoff = 0;
1606         my $empty = 0;
1607         foreach my $line (@$log) {
1608                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1609                         $signoff = 1;
1610                         $empty = 0;
1611                         if (! $opts{'-remove_signoff'}) {
1612                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1613                                 next;
1614                         } else {
1615                                 # remove signoff lines
1616                                 next;
1617                         }
1618                 } else {
1619                         $signoff = 0;
1620                 }
1622                 # print only one empty line
1623                 # do not print empty line after signoff
1624                 if ($line eq "") {
1625                         next if ($empty || $signoff);
1626                         $empty = 1;
1627                 } else {
1628                         $empty = 0;
1629                 }
1631                 print format_log_line_html($line) . "<br/>\n";
1632         }
1634         if ($opts{'-final_empty_line'}) {
1635                 # end with single empty line
1636                 print "<br/>\n" unless $empty;
1637         }
1640 sub git_print_simplified_log {
1641         my $log = shift;
1642         my $remove_title = shift;
1644         git_print_log($log,
1645                 -final_empty_line=> 1,
1646                 -remove_title => $remove_title);
1649 # print tree entry (row of git_tree), but without encompassing <tr> element
1650 sub git_print_tree_entry {
1651         my ($t, $basedir, $hash_base, $have_blame) = @_;
1653         my %base_key = ();
1654         $base_key{hash_base} = $hash_base if defined $hash_base;
1656         # The format of a table row is: mode list link.  Where mode is
1657         # the mode of the entry, list is the name of the entry, an href,
1658         # and link is the action links of the entry.
1660         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1661         if ($t->{'type'} eq "blob") {
1662                 print "<td class=\"list\">" .
1663                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1664                                                file_name=>"$basedir$t->{'name'}", %base_key),
1665                                  -class => "list"}, esc_html($t->{'name'})) . "</td>\n";
1666                 print "<td class=\"link\">";
1667                 if ($have_blame) {
1668                         print $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1669                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
1670                                       "blame");
1671                 }
1672                 if (defined $hash_base) {
1673                         if ($have_blame) {
1674                                 print " | ";
1675                         }
1676                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1677                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1678                                       "history");
1679                 }
1680                 print " | " .
1681                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
1682                                                file_name=>"$basedir$t->{'name'}")},
1683                                 "raw");
1684                 print "</td>\n";
1686         } elsif ($t->{'type'} eq "tree") {
1687                 print "<td class=\"list\">";
1688                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1689                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1690                               esc_html($t->{'name'}));
1691                 print "</td>\n";
1692                 print "<td class=\"link\">";
1693                 if (defined $hash_base) {
1694                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1695                                                      file_name=>"$basedir$t->{'name'}")},
1696                                       "history");
1697                 }
1698                 print "</td>\n";
1699         }
1702 ## ......................................................................
1703 ## functions printing large fragments of HTML
1705 sub git_difftree_body {
1706         my ($difftree, $hash, $parent) = @_;
1708         print "<div class=\"list_head\">\n";
1709         if ($#{$difftree} > 10) {
1710                 print(($#{$difftree} + 1) . " files changed:\n");
1711         }
1712         print "</div>\n";
1714         print "<table class=\"diff_tree\">\n";
1715         my $alternate = 1;
1716         my $patchno = 0;
1717         foreach my $line (@{$difftree}) {
1718                 my %diff = parse_difftree_raw_line($line);
1720                 if ($alternate) {
1721                         print "<tr class=\"dark\">\n";
1722                 } else {
1723                         print "<tr class=\"light\">\n";
1724                 }
1725                 $alternate ^= 1;
1727                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1728                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1729                 if ($diff{'to_mode'} ne ('0' x 6)) {
1730                         $to_mode_oct = oct $diff{'to_mode'};
1731                         if (S_ISREG($to_mode_oct)) { # only for regular file
1732                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1733                         }
1734                         $to_file_type = file_type($diff{'to_mode'});
1735                 }
1736                 if ($diff{'from_mode'} ne ('0' x 6)) {
1737                         $from_mode_oct = oct $diff{'from_mode'};
1738                         if (S_ISREG($to_mode_oct)) { # only for regular file
1739                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1740                         }
1741                         $from_file_type = file_type($diff{'from_mode'});
1742                 }
1744                 if ($diff{'status'} eq "A") { # created
1745                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1746                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1747                         $mode_chng   .= "]</span>";
1748                         print "<td>";
1749                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1750                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1751                                        -class => "list"}, esc_html($diff{'file'}));
1752                         print "</td>\n";
1753                         print "<td>$mode_chng</td>\n";
1754                         print "<td class=\"link\">";
1755                         if ($action eq 'commitdiff') {
1756                                 # link to patch
1757                                 $patchno++;
1758                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
1759                         }
1760                         print "</td>\n";
1762                 } elsif ($diff{'status'} eq "D") { # deleted
1763                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1764                         print "<td>";
1765                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1766                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1767                                        -class => "list"}, esc_html($diff{'file'}));
1768                         print "</td>\n";
1769                         print "<td>$mode_chng</td>\n";
1770                         print "<td class=\"link\">";
1771                         if ($action eq 'commitdiff') {
1772                                 # link to patch
1773                                 $patchno++;
1774                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
1775                                 print " | ";
1776                         }
1777                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1778                                                      file_name=>$diff{'file'})},
1779                                       "blame") . " | ";
1780                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1781                                                      file_name=>$diff{'file'})},
1782                                       "history");
1783                         print "</td>\n";
1785                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1786                         my $mode_chnge = "";
1787                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1788                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1789                                 if ($from_file_type != $to_file_type) {
1790                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1791                                 }
1792                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1793                                         if ($from_mode_str && $to_mode_str) {
1794                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1795                                         } elsif ($to_mode_str) {
1796                                                 $mode_chnge .= " mode: $to_mode_str";
1797                                         }
1798                                 }
1799                                 $mode_chnge .= "]</span>\n";
1800                         }
1801                         print "<td>";
1802                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1803                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1804                                        -class => "list"}, esc_html($diff{'file'}));
1805                         print "</td>\n";
1806                         print "<td>$mode_chnge</td>\n";
1807                         print "<td class=\"link\">";
1808                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1809                                 if ($action eq 'commitdiff') {
1810                                         # link to patch
1811                                         $patchno++;
1812                                         print $cgi->a({-href => "#patch$patchno"}, "patch");
1813                                 } else {
1814                                         print $cgi->a({-href => href(action=>"blobdiff",
1815                                                                      hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1816                                                                      hash_base=>$hash, hash_parent_base=>$parent,
1817                                                                      file_name=>$diff{'file'})},
1818                                                       "diff");
1819                                 }
1820                                 print " | ";
1821                         }
1822                         print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
1823                                                      file_name=>$diff{'file'})},
1824                                       "blame") . " | ";
1825                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
1826                                                      file_name=>$diff{'file'})},
1827                                       "history");
1828                         print "</td>\n";
1830                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1831                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1832                         my $nstatus = $status_name{$diff{'status'}};
1833                         my $mode_chng = "";
1834                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1835                                 # mode also for directories, so we cannot use $to_mode_str
1836                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1837                         }
1838                         print "<td>" .
1839                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1840                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1841                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1842                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1843                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1844                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1845                                       -class => "list"}, esc_html($diff{'from_file'})) .
1846                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1847                               "<td class=\"link\">";
1848                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1849                                 if ($action eq 'commitdiff') {
1850                                         # link to patch
1851                                         $patchno++;
1852                                         print $cgi->a({-href => "#patch$patchno"}, "patch");
1853                                 } else {
1854                                         print $cgi->a({-href => href(action=>"blobdiff",
1855                                                                      hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1856                                                                      hash_base=>$hash, hash_parent_base=>$parent,
1857                                                                      file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1858                                                       "diff");
1859                                 }
1860                                 print " | ";
1861                         }
1862                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1863                                                      file_name=>$diff{'from_file'})},
1864                                       "blame") . " | ";
1865                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1866                                                      file_name=>$diff{'from_file'})},
1867                                       "history");
1868                         print "</td>\n";
1870                 } # we should not encounter Unmerged (U) or Unknown (X) status
1871                 print "</tr>\n";
1872         }
1873         print "</table>\n";
1876 sub git_patchset_body {
1877         my ($fd, $difftree, $hash, $hash_parent) = @_;
1879         my $patch_idx = 0;
1880         my $in_header = 0;
1881         my $patch_found = 0;
1882         my $diffinfo;
1884         print "<div class=\"patchset\">\n";
1886         LINE:
1887         while (my $patch_line = <$fd>) {
1888                 chomp $patch_line;
1890                 if ($patch_line =~ m/^diff /) { # "git diff" header
1891                         # beginning of patch (in patchset)
1892                         if ($patch_found) {
1893                                 # close previous patch
1894                                 print "</div>\n"; # class="patch"
1895                         } else {
1896                                 # first patch in patchset
1897                                 $patch_found = 1;
1898                         }
1899                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1901                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1902                                 $diffinfo = $difftree->[$patch_idx];
1903                         } else {
1904                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1905                         }
1906                         $patch_idx++;
1908                         # for now, no extended header, hence we skip empty patches
1909                         # companion to  next LINE if $in_header;
1910                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1911                                 $in_header = 1;
1912                                 next LINE;
1913                         }
1915                         if ($diffinfo->{'status'} eq "A") { # added
1916                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1917                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1918                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1919                                               $diffinfo->{'to_id'}) . "(new)" .
1920                                       "</div>\n"; # class="diff_info"
1922                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1923                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1924                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1925                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1926                                               $diffinfo->{'from_id'}) . "(deleted)" .
1927                                       "</div>\n"; # class="diff_info"
1929                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1930                                  $diffinfo->{'status'} eq "C" || # copied
1931                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1932                                 print "<div class=\"diff_info\">" .
1933                                       file_type($diffinfo->{'from_mode'}) . ":" .
1934                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1935                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1936                                               $diffinfo->{'from_id'}) .
1937                                       " -> " .
1938                                       file_type($diffinfo->{'to_mode'}) . ":" .
1939                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1940                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
1941                                               $diffinfo->{'to_id'});
1942                                 print "</div>\n"; # class="diff_info"
1944                         } else { # modified, mode changed, ...
1945                                 print "<div class=\"diff_info\">" .
1946                                       file_type($diffinfo->{'from_mode'}) . ":" .
1947                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1948                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1949                                               $diffinfo->{'from_id'}) .
1950                                       " -> " .
1951                                       file_type($diffinfo->{'to_mode'}) . ":" .
1952                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1953                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1954                                               $diffinfo->{'to_id'});
1955                                 print "</div>\n"; # class="diff_info"
1956                         }
1958                         #print "<div class=\"diff extended_header\">\n";
1959                         $in_header = 1;
1960                         next LINE;
1961                 } # start of patch in patchset
1964                 if ($in_header && $patch_line =~ m/^---/) {
1965                         #print "</div>\n"; # class="diff extended_header"
1966                         $in_header = 0;
1968                         my $file = $diffinfo->{'from_file'};
1969                         $file  ||= $diffinfo->{'file'};
1970                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1971                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
1972                                         -class => "list"}, esc_html($file));
1973                         $patch_line =~ s|a/.*$|a/$file|g;
1974                         print "<div class=\"diff from_file\">$patch_line</div>\n";
1976                         $patch_line = <$fd>;
1977                         chomp $patch_line;
1979                         #$patch_line =~ m/^+++/;
1980                         $file    = $diffinfo->{'to_file'};
1981                         $file  ||= $diffinfo->{'file'};
1982                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1983                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
1984                                         -class => "list"}, esc_html($file));
1985                         $patch_line =~ s|b/.*|b/$file|g;
1986                         print "<div class=\"diff to_file\">$patch_line</div>\n";
1988                         next LINE;
1989                 }
1990                 next LINE if $in_header;
1992                 print format_diff_line($patch_line);
1993         }
1994         print "</div>\n" if $patch_found; # class="patch"
1996         print "</div>\n"; # class="patchset"
1999 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2001 sub git_shortlog_body {
2002         # uses global variable $project
2003         my ($revlist, $from, $to, $refs, $extra) = @_;
2005         $from = 0 unless defined $from;
2006         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2008         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2009         my $alternate = 1;
2010         for (my $i = $from; $i <= $to; $i++) {
2011                 my $commit = $revlist->[$i];
2012                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2013                 my $ref = format_ref_marker($refs, $commit);
2014                 my %co = parse_commit($commit);
2015                 if ($alternate) {
2016                         print "<tr class=\"dark\">\n";
2017                 } else {
2018                         print "<tr class=\"light\">\n";
2019                 }
2020                 $alternate ^= 1;
2021                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2022                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2023                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2024                       "<td>";
2025                 print format_subject_html($co{'title'}, $co{'title_short'},
2026                                           href(action=>"commit", hash=>$commit), $ref);
2027                 print "</td>\n" .
2028                       "<td class=\"link\">" .
2029                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2030                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") . " | " .
2031                       $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2032                 print "</td>\n" .
2033                       "</tr>\n";
2034         }
2035         if (defined $extra) {
2036                 print "<tr>\n" .
2037                       "<td colspan=\"4\">$extra</td>\n" .
2038                       "</tr>\n";
2039         }
2040         print "</table>\n";
2043 sub git_history_body {
2044         # Warning: assumes constant type (blob or tree) during history
2045         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2047         $from = 0 unless defined $from;
2048         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2050         print "<table class=\"history\" cellspacing=\"0\">\n";
2051         my $alternate = 1;
2052         for (my $i = $from; $i <= $to; $i++) {
2053                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2054                         next;
2055                 }
2057                 my $commit = $1;
2058                 my %co = parse_commit($commit);
2059                 if (!%co) {
2060                         next;
2061                 }
2063                 my $ref = format_ref_marker($refs, $commit);
2065                 if ($alternate) {
2066                         print "<tr class=\"dark\">\n";
2067                 } else {
2068                         print "<tr class=\"light\">\n";
2069                 }
2070                 $alternate ^= 1;
2071                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2072                       # shortlog uses      chop_str($co{'author_name'}, 10)
2073                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2074                       "<td>";
2075                 # originally git_history used chop_str($co{'title'}, 50)
2076                 print format_subject_html($co{'title'}, $co{'title_short'},
2077                                           href(action=>"commit", hash=>$commit), $ref);
2078                 print "</td>\n" .
2079                       "<td class=\"link\">" .
2080                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2081                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2083                 if ($ftype eq 'blob') {
2084                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2085                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2086                         if (defined $blob_current && defined $blob_parent &&
2087                                         $blob_current ne $blob_parent) {
2088                                 print " | " .
2089                                         $cgi->a({-href => href(action=>"blobdiff",
2090                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2091                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2092                                                                file_name=>$file_name)},
2093                                                 "diff to current");
2094                         }
2095                 }
2096                 print "</td>\n" .
2097                       "</tr>\n";
2098         }
2099         if (defined $extra) {
2100                 print "<tr>\n" .
2101                       "<td colspan=\"4\">$extra</td>\n" .
2102                       "</tr>\n";
2103         }
2104         print "</table>\n";
2107 sub git_tags_body {
2108         # uses global variable $project
2109         my ($taglist, $from, $to, $extra) = @_;
2110         $from = 0 unless defined $from;
2111         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2113         print "<table class=\"tags\" cellspacing=\"0\">\n";
2114         my $alternate = 1;
2115         for (my $i = $from; $i <= $to; $i++) {
2116                 my $entry = $taglist->[$i];
2117                 my %tag = %$entry;
2118                 my $comment_lines = $tag{'comment'};
2119                 my $comment = shift @$comment_lines;
2120                 my $comment_short;
2121                 if (defined $comment) {
2122                         $comment_short = chop_str($comment, 30, 5);
2123                 }
2124                 if ($alternate) {
2125                         print "<tr class=\"dark\">\n";
2126                 } else {
2127                         print "<tr class=\"light\">\n";
2128                 }
2129                 $alternate ^= 1;
2130                 print "<td><i>$tag{'age'}</i></td>\n" .
2131                       "<td>" .
2132                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2133                                -class => "list name"}, esc_html($tag{'name'})) .
2134                       "</td>\n" .
2135                       "<td>";
2136                 if (defined $comment) {
2137                         print format_subject_html($comment, $comment_short,
2138                                                   href(action=>"tag", hash=>$tag{'id'}));
2139                 }
2140                 print "</td>\n" .
2141                       "<td class=\"selflink\">";
2142                 if ($tag{'type'} eq "tag") {
2143                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2144                 } else {
2145                         print "&nbsp;";
2146                 }
2147                 print "</td>\n" .
2148                       "<td class=\"link\">" . " | " .
2149                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2150                 if ($tag{'reftype'} eq "commit") {
2151                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2152                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2153                 } elsif ($tag{'reftype'} eq "blob") {
2154                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2155                 }
2156                 print "</td>\n" .
2157                       "</tr>";
2158         }
2159         if (defined $extra) {
2160                 print "<tr>\n" .
2161                       "<td colspan=\"5\">$extra</td>\n" .
2162                       "</tr>\n";
2163         }
2164         print "</table>\n";
2167 sub git_heads_body {
2168         # uses global variable $project
2169         my ($headlist, $head, $from, $to, $extra) = @_;
2170         $from = 0 unless defined $from;
2171         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2173         print "<table class=\"heads\" cellspacing=\"0\">\n";
2174         my $alternate = 1;
2175         for (my $i = $from; $i <= $to; $i++) {
2176                 my $entry = $headlist->[$i];
2177                 my %tag = %$entry;
2178                 my $curr = $tag{'id'} eq $head;
2179                 if ($alternate) {
2180                         print "<tr class=\"dark\">\n";
2181                 } else {
2182                         print "<tr class=\"light\">\n";
2183                 }
2184                 $alternate ^= 1;
2185                 print "<td><i>$tag{'age'}</i></td>\n" .
2186                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2187                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2188                                -class => "list name"},esc_html($tag{'name'})) .
2189                       "</td>\n" .
2190                       "<td class=\"link\">" .
2191                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2192                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") . " | " .
2193                       $cgi->a({-href => href(action=>"tree", hash=>$tag{'name'}, hash_base=>$tag{'name'})}, "tree") .
2194                       "</td>\n" .
2195                       "</tr>";
2196         }
2197         if (defined $extra) {
2198                 print "<tr>\n" .
2199                       "<td colspan=\"3\">$extra</td>\n" .
2200                       "</tr>\n";
2201         }
2202         print "</table>\n";
2205 ## ======================================================================
2206 ## ======================================================================
2207 ## actions
2209 sub git_project_list {
2210         my $order = $cgi->param('o');
2211         if (defined $order && $order !~ m/project|descr|owner|age/) {
2212                 die_error(undef, "Unknown order parameter");
2213         }
2215         my @list = git_get_projects_list();
2216         my @projects;
2217         if (!@list) {
2218                 die_error(undef, "No projects found");
2219         }
2220         foreach my $pr (@list) {
2221                 my $head = git_get_head_hash($pr->{'path'});
2222                 if (!defined $head) {
2223                         next;
2224                 }
2225                 $git_dir = "$projectroot/$pr->{'path'}";
2226                 my %co = parse_commit($head);
2227                 if (!%co) {
2228                         next;
2229                 }
2230                 $pr->{'commit'} = \%co;
2231                 if (!defined $pr->{'descr'}) {
2232                         my $descr = git_get_project_description($pr->{'path'}) || "";
2233                         $pr->{'descr'} = chop_str($descr, 25, 5);
2234                 }
2235                 if (!defined $pr->{'owner'}) {
2236                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2237                 }
2238                 push @projects, $pr;
2239         }
2241         git_header_html();
2242         if (-f $home_text) {
2243                 print "<div class=\"index_include\">\n";
2244                 open (my $fd, $home_text);
2245                 print <$fd>;
2246                 close $fd;
2247                 print "</div>\n";
2248         }
2249         print "<table class=\"project_list\">\n" .
2250               "<tr>\n";
2251         $order ||= "project";
2252         if ($order eq "project") {
2253                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2254                 print "<th>Project</th>\n";
2255         } else {
2256                 print "<th>" .
2257                       $cgi->a({-href => href(project=>undef, order=>'project'),
2258                                -class => "header"}, "Project") .
2259                       "</th>\n";
2260         }
2261         if ($order eq "descr") {
2262                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2263                 print "<th>Description</th>\n";
2264         } else {
2265                 print "<th>" .
2266                       $cgi->a({-href => href(project=>undef, order=>'descr'),
2267                                -class => "header"}, "Description") .
2268                       "</th>\n";
2269         }
2270         if ($order eq "owner") {
2271                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2272                 print "<th>Owner</th>\n";
2273         } else {
2274                 print "<th>" .
2275                       $cgi->a({-href => href(project=>undef, order=>'owner'),
2276                                -class => "header"}, "Owner") .
2277                       "</th>\n";
2278         }
2279         if ($order eq "age") {
2280                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2281                 print "<th>Last Change</th>\n";
2282         } else {
2283                 print "<th>" .
2284                       $cgi->a({-href => href(project=>undef, order=>'age'),
2285                                -class => "header"}, "Last Change") .
2286                       "</th>\n";
2287         }
2288         print "<th></th>\n" .
2289               "</tr>\n";
2290         my $alternate = 1;
2291         foreach my $pr (@projects) {
2292                 if ($alternate) {
2293                         print "<tr class=\"dark\">\n";
2294                 } else {
2295                         print "<tr class=\"light\">\n";
2296                 }
2297                 $alternate ^= 1;
2298                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2299                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2300                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2301                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2302                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2303                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2304                       "<td class=\"link\">" .
2305                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2306                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2307                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2308                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2309                       "</td>\n" .
2310                       "</tr>\n";
2311         }
2312         print "</table>\n";
2313         git_footer_html();
2316 sub git_project_index {
2317         my @projects = git_get_projects_list();
2319         print $cgi->header(
2320                 -type => 'text/plain',
2321                 -charset => 'utf-8',
2322                 -content_disposition => 'inline; filename="index.aux"');
2324         foreach my $pr (@projects) {
2325                 if (!exists $pr->{'owner'}) {
2326                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2327                 }
2329                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2330                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2331                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2332                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2333                 $path  =~ s/ /\+/g;
2334                 $owner =~ s/ /\+/g;
2336                 print "$path $owner\n";
2337         }
2340 sub git_summary {
2341         my $descr = git_get_project_description($project) || "none";
2342         my $head = git_get_head_hash($project);
2343         my %co = parse_commit($head);
2344         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2346         my $owner = git_get_project_owner($project);
2348         my ($reflist, $refs) = git_get_refs_list();
2350         my @taglist;
2351         my @headlist;
2352         foreach my $ref (@$reflist) {
2353                 if ($ref->{'name'} =~ s!^heads/!!) {
2354                         push @headlist, $ref;
2355                 } else {
2356                         $ref->{'name'} =~ s!^tags/!!;
2357                         push @taglist, $ref;
2358                 }
2359         }
2361         git_header_html();
2362         git_print_page_nav('summary','', $head);
2364         print "<div class=\"title\">&nbsp;</div>\n";
2365         print "<table cellspacing=\"0\">\n" .
2366               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2367               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2368               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2369         # use per project git URL list in $projectroot/$project/cloneurl
2370         # or make project git URL from git base URL and project name
2371         my $url_tag = "URL";
2372         my @url_list = git_get_project_url_list($project);
2373         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2374         foreach my $git_url (@url_list) {
2375                 next unless $git_url;
2376                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2377                 $url_tag = "";
2378         }
2379         print "</table>\n";
2381         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2382                 git_get_head_hash($project)
2383                 or die_error(undef, "Open git-rev-list failed");
2384         my @revlist = map { chomp; $_ } <$fd>;
2385         close $fd;
2386         git_print_header_div('shortlog');
2387         git_shortlog_body(\@revlist, 0, 15, $refs,
2388                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2390         if (@taglist) {
2391                 git_print_header_div('tags');
2392                 git_tags_body(\@taglist, 0, 15,
2393                               $cgi->a({-href => href(action=>"tags")}, "..."));
2394         }
2396         if (@headlist) {
2397                 git_print_header_div('heads');
2398                 git_heads_body(\@headlist, $head, 0, 15,
2399                                $cgi->a({-href => href(action=>"heads")}, "..."));
2400         }
2402         git_footer_html();
2405 sub git_tag {
2406         my $head = git_get_head_hash($project);
2407         git_header_html();
2408         git_print_page_nav('','', $head,undef,$head);
2409         my %tag = parse_tag($hash);
2410         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2411         print "<div class=\"title_text\">\n" .
2412               "<table cellspacing=\"0\">\n" .
2413               "<tr>\n" .
2414               "<td>object</td>\n" .
2415               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2416                                $tag{'object'}) . "</td>\n" .
2417               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2418                                               $tag{'type'}) . "</td>\n" .
2419               "</tr>\n";
2420         if (defined($tag{'author'})) {
2421                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2422                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2423                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2424                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2425                         "</td></tr>\n";
2426         }
2427         print "</table>\n\n" .
2428               "</div>\n";
2429         print "<div class=\"page_body\">";
2430         my $comment = $tag{'comment'};
2431         foreach my $line (@$comment) {
2432                 print esc_html($line) . "<br/>\n";
2433         }
2434         print "</div>\n";
2435         git_footer_html();
2438 sub git_blame2 {
2439         my $fd;
2440         my $ftype;
2442         my ($have_blame) = gitweb_check_feature('blame');
2443         if (!$have_blame) {
2444                 die_error('403 Permission denied', "Permission denied");
2445         }
2446         die_error('404 Not Found', "File name not defined") if (!$file_name);
2447         $hash_base ||= git_get_head_hash($project);
2448         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2449         my %co = parse_commit($hash_base)
2450                 or die_error(undef, "Reading commit failed");
2451         if (!defined $hash) {
2452                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2453                         or die_error(undef, "Error looking up file");
2454         }
2455         $ftype = git_get_type($hash);
2456         if ($ftype !~ "blob") {
2457                 die_error("400 Bad Request", "Object is not a blob");
2458         }
2459         open ($fd, "-|", git_cmd(), "blame", '-l', '--', $file_name, $hash_base)
2460                 or die_error(undef, "Open git-blame failed");
2461         git_header_html();
2462         my $formats_nav =
2463                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2464                         "blob") .
2465                 " | " .
2466                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2467                         "history") .
2468                 " | " .
2469                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2470                         "HEAD");
2471         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2472         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2473         git_print_page_path($file_name, $ftype, $hash_base);
2474         my @rev_color = (qw(light2 dark2));
2475         my $num_colors = scalar(@rev_color);
2476         my $current_color = 0;
2477         my $last_rev;
2478         print <<HTML;
2479 <div class="page_body">
2480 <table class="blame">
2481 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2482 HTML
2483         while (<$fd>) {
2484                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2485                 my $full_rev = $1;
2486                 my $rev = substr($full_rev, 0, 8);
2487                 my $lineno = $2;
2488                 my $data = $3;
2490                 if (!defined $last_rev) {
2491                         $last_rev = $full_rev;
2492                 } elsif ($last_rev ne $full_rev) {
2493                         $last_rev = $full_rev;
2494                         $current_color = ++$current_color % $num_colors;
2495                 }
2496                 print "<tr class=\"$rev_color[$current_color]\">\n";
2497                 print "<td class=\"sha1\">" .
2498                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2499                                 esc_html($rev)) . "</td>\n";
2500                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2501                       esc_html($lineno) . "</a></td>\n";
2502                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2503                 print "</tr>\n";
2504         }
2505         print "</table>\n";
2506         print "</div>";
2507         close $fd
2508                 or print "Reading blob failed\n";
2509         git_footer_html();
2512 sub git_blame {
2513         my $fd;
2515         my ($have_blame) = gitweb_check_feature('blame');
2516         if (!$have_blame) {
2517                 die_error('403 Permission denied', "Permission denied");
2518         }
2519         die_error('404 Not Found', "File name not defined") if (!$file_name);
2520         $hash_base ||= git_get_head_hash($project);
2521         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2522         my %co = parse_commit($hash_base)
2523                 or die_error(undef, "Reading commit failed");
2524         if (!defined $hash) {
2525                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2526                         or die_error(undef, "Error lookup file");
2527         }
2528         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2529                 or die_error(undef, "Open git-annotate failed");
2530         git_header_html();
2531         my $formats_nav =
2532                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2533                         "blob") .
2534                 " | " .
2535                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2536                         "history") .
2537                 " | " .
2538                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2539                         "HEAD");
2540         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2541         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2542         git_print_page_path($file_name, 'blob', $hash_base);
2543         print "<div class=\"page_body\">\n";
2544         print <<HTML;
2545 <table class="blame">
2546   <tr>
2547     <th>Commit</th>
2548     <th>Age</th>
2549     <th>Author</th>
2550     <th>Line</th>
2551     <th>Data</th>
2552   </tr>
2553 HTML
2554         my @line_class = (qw(light dark));
2555         my $line_class_len = scalar (@line_class);
2556         my $line_class_num = $#line_class;
2557         while (my $line = <$fd>) {
2558                 my $long_rev;
2559                 my $short_rev;
2560                 my $author;
2561                 my $time;
2562                 my $lineno;
2563                 my $data;
2564                 my $age;
2565                 my $age_str;
2566                 my $age_class;
2568                 chomp $line;
2569                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2571                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2572                         $long_rev = $1;
2573                         $author   = $2;
2574                         $time     = $3;
2575                         $lineno   = $4;
2576                         $data     = $5;
2577                 } else {
2578                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2579                         next;
2580                 }
2581                 $short_rev  = substr ($long_rev, 0, 8);
2582                 $age        = time () - $time;
2583                 $age_str    = age_string ($age);
2584                 $age_str    =~ s/ /&nbsp;/g;
2585                 $age_class  = age_class($age);
2586                 $author     = esc_html ($author);
2587                 $author     =~ s/ /&nbsp;/g;
2589                 $data = untabify($data);
2590                 $data = esc_html ($data);
2592                 print <<HTML;
2593   <tr class="$line_class[$line_class_num]">
2594     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2595     <td class="$age_class">$age_str</td>
2596     <td>$author</td>
2597     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2598     <td class="pre">$data</td>
2599   </tr>
2600 HTML
2601         } # while (my $line = <$fd>)
2602         print "</table>\n\n";
2603         close $fd
2604                 or print "Reading blob failed.\n";
2605         print "</div>";
2606         git_footer_html();
2609 sub git_tags {
2610         my $head = git_get_head_hash($project);
2611         git_header_html();
2612         git_print_page_nav('','', $head,undef,$head);
2613         git_print_header_div('summary', $project);
2615         my ($taglist) = git_get_refs_list("tags");
2616         if (@$taglist) {
2617                 git_tags_body($taglist);
2618         }
2619         git_footer_html();
2622 sub git_heads {
2623         my $head = git_get_head_hash($project);
2624         git_header_html();
2625         git_print_page_nav('','', $head,undef,$head);
2626         git_print_header_div('summary', $project);
2628         my ($headlist) = git_get_refs_list("heads");
2629         if (@$headlist) {
2630                 git_heads_body($headlist, $head);
2631         }
2632         git_footer_html();
2635 sub git_blob_plain {
2636         my $expires;
2638         if (!defined $hash) {
2639                 if (defined $file_name) {
2640                         my $base = $hash_base || git_get_head_hash($project);
2641                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2642                                 or die_error(undef, "Error lookup file");
2643                 } else {
2644                         die_error(undef, "No file name defined");
2645                 }
2646         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2647                 # blobs defined by non-textual hash id's can be cached
2648                 $expires = "+1d";
2649         }
2651         my $type = shift;
2652         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2653                 or die_error(undef, "Couldn't cat $file_name, $hash");
2655         $type ||= blob_mimetype($fd, $file_name);
2657         # save as filename, even when no $file_name is given
2658         my $save_as = "$hash";
2659         if (defined $file_name) {
2660                 $save_as = $file_name;
2661         } elsif ($type =~ m/^text\//) {
2662                 $save_as .= '.txt';
2663         }
2665         print $cgi->header(
2666                 -type => "$type",
2667                 -expires=>$expires,
2668                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
2669         undef $/;
2670         binmode STDOUT, ':raw';
2671         print <$fd>;
2672         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2673         $/ = "\n";
2674         close $fd;
2677 sub git_blob {
2678         my $expires;
2680         if (!defined $hash) {
2681                 if (defined $file_name) {
2682                         my $base = $hash_base || git_get_head_hash($project);
2683                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2684                                 or die_error(undef, "Error lookup file");
2685                 } else {
2686                         die_error(undef, "No file name defined");
2687                 }
2688         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2689                 # blobs defined by non-textual hash id's can be cached
2690                 $expires = "+1d";
2691         }
2693         my ($have_blame) = gitweb_check_feature('blame');
2694         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2695                 or die_error(undef, "Couldn't cat $file_name, $hash");
2696         my $mimetype = blob_mimetype($fd, $file_name);
2697         if ($mimetype !~ m/^text\//) {
2698                 close $fd;
2699                 return git_blob_plain($mimetype);
2700         }
2701         git_header_html(undef, $expires);
2702         my $formats_nav = '';
2703         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2704                 if (defined $file_name) {
2705                         if ($have_blame) {
2706                                 $formats_nav .=
2707                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2708                                                                hash=>$hash, file_name=>$file_name)},
2709                                                 "blame") .
2710                                         " | ";
2711                         }
2712                         $formats_nav .=
2713                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2714                                                        hash=>$hash, file_name=>$file_name)},
2715                                         "history") .
2716                                 " | " .
2717                                 $cgi->a({-href => href(action=>"blob_plain",
2718                                                        hash=>$hash, file_name=>$file_name)},
2719                                         "raw") .
2720                                 " | " .
2721                                 $cgi->a({-href => href(action=>"blob",
2722                                                        hash_base=>"HEAD", file_name=>$file_name)},
2723                                         "HEAD");
2724                 } else {
2725                         $formats_nav .=
2726                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
2727                 }
2728                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2729                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2730         } else {
2731                 print "<div class=\"page_nav\">\n" .
2732                       "<br/><br/></div>\n" .
2733                       "<div class=\"title\">$hash</div>\n";
2734         }
2735         git_print_page_path($file_name, "blob", $hash_base);
2736         print "<div class=\"page_body\">\n";
2737         my $nr;
2738         while (my $line = <$fd>) {
2739                 chomp $line;
2740                 $nr++;
2741                 $line = untabify($line);
2742                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2743                        $nr, $nr, $nr, esc_html($line);
2744         }
2745         close $fd
2746                 or print "Reading blob failed.\n";
2747         print "</div>";
2748         git_footer_html();
2751 sub git_tree {
2752         my $have_snapshot = gitweb_have_snapshot();
2754         if (!defined $hash_base) {
2755                 $hash_base = "HEAD";
2756         }
2757         if (!defined $hash) {
2758                 if (defined $file_name) {
2759                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
2760                 } else {
2761                         $hash = $hash_base;
2762                 }
2763         }
2764         $/ = "\0";
2765         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2766                 or die_error(undef, "Open git-ls-tree failed");
2767         my @entries = map { chomp; $_ } <$fd>;
2768         close $fd or die_error(undef, "Reading tree failed");
2769         $/ = "\n";
2771         my $refs = git_get_references();
2772         my $ref = format_ref_marker($refs, $hash_base);
2773         git_header_html();
2774         my $base = "";
2775         my ($have_blame) = gitweb_check_feature('blame');
2776         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2777                 my @views_nav = ();
2778                 if (defined $file_name) {
2779                         push @views_nav,
2780                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2781                                                        hash=>$hash, file_name=>$file_name)},
2782                                         "history"),
2783                                 $cgi->a({-href => href(action=>"tree",
2784                                                        hash_base=>"HEAD", file_name=>$file_name)},
2785                                         "HEAD"),
2786                 }
2787                 if ($have_snapshot) {
2788                         # FIXME: Should be available when we have no hash base as well.
2789                         push @views_nav,
2790                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
2791                                         "snapshot");
2792                 }
2793                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
2794                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2795         } else {
2796                 undef $hash_base;
2797                 print "<div class=\"page_nav\">\n";
2798                 print "<br/><br/></div>\n";
2799                 print "<div class=\"title\">$hash</div>\n";
2800         }
2801         if (defined $file_name) {
2802                 $base = esc_html("$file_name/");
2803         }
2804         git_print_page_path($file_name, 'tree', $hash_base);
2805         print "<div class=\"page_body\">\n";
2806         print "<table cellspacing=\"0\">\n";
2807         my $alternate = 1;
2808         foreach my $line (@entries) {
2809                 my %t = parse_ls_tree_line($line, -z => 1);
2811                 if ($alternate) {
2812                         print "<tr class=\"dark\">\n";
2813                 } else {
2814                         print "<tr class=\"light\">\n";
2815                 }
2816                 $alternate ^= 1;
2818                 git_print_tree_entry(\%t, $base, $hash_base, $have_blame);
2820                 print "</tr>\n";
2821         }
2822         print "</table>\n" .
2823               "</div>";
2824         git_footer_html();
2827 sub git_snapshot {
2828         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2829         my $have_snapshot = (defined $ctype && defined $suffix);
2830         if (!$have_snapshot) {
2831                 die_error('403 Permission denied', "Permission denied");
2832         }
2834         if (!defined $hash) {
2835                 $hash = git_get_head_hash($project);
2836         }
2838         my $filename = basename($project) . "-$hash.tar.$suffix";
2840         print $cgi->header(
2841                 -type => 'application/x-tar',
2842                 -content_encoding => $ctype,
2843                 -content_disposition => 'inline; filename="' . "$filename" . '"',
2844                 -status => '200 OK');
2846         my $git = git_cmd_str();
2847         my $name = $project;
2848         $name =~ s/\047/\047\\\047\047/g;
2849         open my $fd, "-|",
2850         "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
2851                 or die_error(undef, "Execute git-tar-tree failed.");
2852         binmode STDOUT, ':raw';
2853         print <$fd>;
2854         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2855         close $fd;
2859 sub git_log {
2860         my $head = git_get_head_hash($project);
2861         if (!defined $hash) {
2862                 $hash = $head;
2863         }
2864         if (!defined $page) {
2865                 $page = 0;
2866         }
2867         my $refs = git_get_references();
2869         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2870         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2871                 or die_error(undef, "Open git-rev-list failed");
2872         my @revlist = map { chomp; $_ } <$fd>;
2873         close $fd;
2875         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2877         git_header_html();
2878         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2880         if (!@revlist) {
2881                 my %co = parse_commit($hash);
2883                 git_print_header_div('summary', $project);
2884                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2885         }
2886         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2887                 my $commit = $revlist[$i];
2888                 my $ref = format_ref_marker($refs, $commit);
2889                 my %co = parse_commit($commit);
2890                 next if !%co;
2891                 my %ad = parse_date($co{'author_epoch'});
2892                 git_print_header_div('commit',
2893                                "<span class=\"age\">$co{'age_string'}</span>" .
2894                                esc_html($co{'title'}) . $ref,
2895                                $commit);
2896                 print "<div class=\"title_text\">\n" .
2897                       "<div class=\"log_link\">\n" .
2898                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2899                       " | " .
2900                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2901                       " | " .
2902                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
2903                       "<br/>\n" .
2904                       "</div>\n" .
2905                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2906                       "</div>\n";
2908                 print "<div class=\"log_body\">\n";
2909                 git_print_simplified_log($co{'comment'});
2910                 print "</div>\n";
2911         }
2912         git_footer_html();
2915 sub git_commit {
2916         my %co = parse_commit($hash);
2917         if (!%co) {
2918                 die_error(undef, "Unknown commit object");
2919         }
2920         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2921         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2923         my $parent = $co{'parent'};
2924         if (!defined $parent) {
2925                 $parent = "--root";
2926         }
2927         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2928                 or die_error(undef, "Open git-diff-tree failed");
2929         my @difftree = map { chomp; $_ } <$fd>;
2930         close $fd or die_error(undef, "Reading git-diff-tree failed");
2932         # non-textual hash id's can be cached
2933         my $expires;
2934         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2935                 $expires = "+1d";
2936         }
2937         my $refs = git_get_references();
2938         my $ref = format_ref_marker($refs, $co{'id'});
2940         my $have_snapshot = gitweb_have_snapshot();
2942         my @views_nav = ();
2943         if (defined $file_name && defined $co{'parent'}) {
2944                 push @views_nav,
2945                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
2946                                 "blame");
2947         }
2948         git_header_html(undef, $expires);
2949         git_print_page_nav('commit', defined $co{'parent'} ? '' : 'commitdiff',
2950                            $hash, $co{'tree'}, $hash,
2951                            join (' | ', @views_nav));
2953         if (defined $co{'parent'}) {
2954                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
2955         } else {
2956                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
2957         }
2958         print "<div class=\"title_text\">\n" .
2959               "<table cellspacing=\"0\">\n";
2960         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
2961               "<tr>" .
2962               "<td></td><td> $ad{'rfc2822'}";
2963         if ($ad{'hour_local'} < 6) {
2964                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2965                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2966         } else {
2967                 printf(" (%02d:%02d %s)",
2968                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2969         }
2970         print "</td>" .
2971               "</tr>\n";
2972         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
2973         print "<tr><td></td><td> $cd{'rfc2822'}" .
2974               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
2975               "</td></tr>\n";
2976         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
2977         print "<tr>" .
2978               "<td>tree</td>" .
2979               "<td class=\"sha1\">" .
2980               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
2981                        class => "list"}, $co{'tree'}) .
2982               "</td>" .
2983               "<td class=\"link\">" .
2984               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
2985                       "tree");
2986         if ($have_snapshot) {
2987                 print " | " .
2988                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
2989         }
2990         print "</td>" .
2991               "</tr>\n";
2992         my $parents = $co{'parents'};
2993         foreach my $par (@$parents) {
2994                 print "<tr>" .
2995                       "<td>parent</td>" .
2996                       "<td class=\"sha1\">" .
2997                       $cgi->a({-href => href(action=>"commit", hash=>$par),
2998                                class => "list"}, $par) .
2999                       "</td>" .
3000                       "<td class=\"link\">" .
3001                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3002                       " | " .
3003                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3004                       "</td>" .
3005                       "</tr>\n";
3006         }
3007         print "</table>".
3008               "</div>\n";
3010         print "<div class=\"page_body\">\n";
3011         git_print_log($co{'comment'});
3012         print "</div>\n";
3014         git_difftree_body(\@difftree, $hash, $parent);
3016         git_footer_html();
3019 sub git_blobdiff {
3020         my $format = shift || 'html';
3022         my $fd;
3023         my @difftree;
3024         my %diffinfo;
3025         my $expires;
3027         # preparing $fd and %diffinfo for git_patchset_body
3028         # new style URI
3029         if (defined $hash_base && defined $hash_parent_base) {
3030                 if (defined $file_name) {
3031                         # read raw output
3032                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
3033                                 "--", $file_name
3034                                 or die_error(undef, "Open git-diff-tree failed");
3035                         @difftree = map { chomp; $_ } <$fd>;
3036                         close $fd
3037                                 or die_error(undef, "Reading git-diff-tree failed");
3038                         @difftree
3039                                 or die_error('404 Not Found', "Blob diff not found");
3041                 } elsif (defined $hash &&
3042                          $hash =~ /[0-9a-fA-F]{40}/) {
3043                         # try to find filename from $hash
3045                         # read filtered raw output
3046                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
3047                                 or die_error(undef, "Open git-diff-tree failed");
3048                         @difftree =
3049                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3050                                 # $hash == to_id
3051                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3052                                 map { chomp; $_ } <$fd>;
3053                         close $fd
3054                                 or die_error(undef, "Reading git-diff-tree failed");
3055                         @difftree
3056                                 or die_error('404 Not Found', "Blob diff not found");
3058                 } else {
3059                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3060                 }
3062                 if (@difftree > 1) {
3063                         die_error('404 Not Found', "Ambiguous blob diff specification");
3064                 }
3066                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3067                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3068                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3070                 $hash_parent ||= $diffinfo{'from_id'};
3071                 $hash        ||= $diffinfo{'to_id'};
3073                 # non-textual hash id's can be cached
3074                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3075                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3076                         $expires = '+1d';
3077                 }
3079                 # open patch output
3080                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3081                         '-p', $hash_parent_base, $hash_base,
3082                         "--", $file_name
3083                         or die_error(undef, "Open git-diff-tree failed");
3084         }
3086         # old/legacy style URI
3087         if (!%diffinfo && # if new style URI failed
3088             defined $hash && defined $hash_parent) {
3089                 # fake git-diff-tree raw output
3090                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3091                 $diffinfo{'from_id'} = $hash_parent;
3092                 $diffinfo{'to_id'}   = $hash;
3093                 if (defined $file_name) {
3094                         if (defined $file_parent) {
3095                                 $diffinfo{'status'} = '2';
3096                                 $diffinfo{'from_file'} = $file_parent;
3097                                 $diffinfo{'to_file'}   = $file_name;
3098                         } else { # assume not renamed
3099                                 $diffinfo{'status'} = '1';
3100                                 $diffinfo{'from_file'} = $file_name;
3101                                 $diffinfo{'to_file'}   = $file_name;
3102                         }
3103                 } else { # no filename given
3104                         $diffinfo{'status'} = '2';
3105                         $diffinfo{'from_file'} = $hash_parent;
3106                         $diffinfo{'to_file'}   = $hash;
3107                 }
3109                 # non-textual hash id's can be cached
3110                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3111                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3112                         $expires = '+1d';
3113                 }
3115                 # open patch output
3116                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3117                         or die_error(undef, "Open git-diff failed");
3118         } else  {
3119                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3120                         unless %diffinfo;
3121         }
3123         # header
3124         if ($format eq 'html') {
3125                 my $formats_nav =
3126                         $cgi->a({-href => href(action=>"blobdiff_plain",
3127                                                hash=>$hash, hash_parent=>$hash_parent,
3128                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3129                                                file_name=>$file_name, file_parent=>$file_parent)},
3130                                 "raw");
3131                 git_header_html(undef, $expires);
3132                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3133                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3134                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3135                 } else {
3136                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3137                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3138                 }
3139                 if (defined $file_name) {
3140                         git_print_page_path($file_name, "blob", $hash_base);
3141                 } else {
3142                         print "<div class=\"page_path\"></div>\n";
3143                 }
3145         } elsif ($format eq 'plain') {
3146                 print $cgi->header(
3147                         -type => 'text/plain',
3148                         -charset => 'utf-8',
3149                         -expires => $expires,
3150                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
3152                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3154         } else {
3155                 die_error(undef, "Unknown blobdiff format");
3156         }
3158         # patch
3159         if ($format eq 'html') {
3160                 print "<div class=\"page_body\">\n";
3162                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3163                 close $fd;
3165                 print "</div>\n"; # class="page_body"
3166                 git_footer_html();
3168         } else {
3169                 while (my $line = <$fd>) {
3170                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_html($diffinfo{'from_file'})!eg;
3171                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_html($diffinfo{'to_file'})!eg;
3173                         print $line;
3175                         last if $line =~ m!^\+\+\+!;
3176                 }
3177                 local $/ = undef;
3178                 print <$fd>;
3179                 close $fd;
3180         }
3183 sub git_blobdiff_plain {
3184         git_blobdiff('plain');
3187 sub git_commitdiff {
3188         my $format = shift || 'html';
3189         my %co = parse_commit($hash);
3190         if (!%co) {
3191                 die_error(undef, "Unknown commit object");
3192         }
3193         if (!defined $hash_parent) {
3194                 $hash_parent = $co{'parent'} || '--root';
3195         }
3197         # read commitdiff
3198         my $fd;
3199         my @difftree;
3200         if ($format eq 'html') {
3201                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3202                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3203                         or die_error(undef, "Open git-diff-tree failed");
3205                 while (chomp(my $line = <$fd>)) {
3206                         # empty line ends raw part of diff-tree output
3207                         last unless $line;
3208                         push @difftree, $line;
3209                 }
3211         } elsif ($format eq 'plain') {
3212                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3213                         '-p', $hash_parent, $hash
3214                         or die_error(undef, "Open git-diff-tree failed");
3216         } else {
3217                 die_error(undef, "Unknown commitdiff format");
3218         }
3220         # non-textual hash id's can be cached
3221         my $expires;
3222         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3223                 $expires = "+1d";
3224         }
3226         # write commit message
3227         if ($format eq 'html') {
3228                 my $refs = git_get_references();
3229                 my $ref = format_ref_marker($refs, $co{'id'});
3230                 my $formats_nav =
3231                         $cgi->a({-href => href(action=>"commitdiff_plain",
3232                                                hash=>$hash, hash_parent=>$hash_parent)},
3233                                 "raw");
3235                 git_header_html(undef, $expires);
3236                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3237                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3238                 git_print_authorship(\%co);
3239                 print "<div class=\"page_body\">\n";
3240                 print "<div class=\"log\">\n";
3241                 git_print_simplified_log($co{'comment'}, 1); # skip title
3242                 print "</div>\n"; # class="log"
3244         } elsif ($format eq 'plain') {
3245                 my $refs = git_get_references("tags");
3246                 my $tagname = git_get_rev_name_tags($hash);
3247                 my $filename = basename($project) . "-$hash.patch";
3249                 print $cgi->header(
3250                         -type => 'text/plain',
3251                         -charset => 'utf-8',
3252                         -expires => $expires,
3253                         -content_disposition => 'inline; filename="' . "$filename" . '"');
3254                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3255                 print <<TEXT;
3256 From: $co{'author'}
3257 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3258 Subject: $co{'title'}
3259 TEXT
3260                 print "X-Git-Tag: $tagname\n" if $tagname;
3261                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3263                 foreach my $line (@{$co{'comment'}}) {
3264                         print "$line\n";
3265                 }
3266                 print "---\n\n";
3267         }
3269         # write patch
3270         if ($format eq 'html') {
3271                 git_difftree_body(\@difftree, $hash, $hash_parent);
3272                 print "<br/>\n";
3274                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3275                 close $fd;
3276                 print "</div>\n"; # class="page_body"
3277                 git_footer_html();
3279         } elsif ($format eq 'plain') {
3280                 local $/ = undef;
3281                 print <$fd>;
3282                 close $fd
3283                         or print "Reading git-diff-tree failed\n";
3284         }
3287 sub git_commitdiff_plain {
3288         git_commitdiff('plain');
3291 sub git_history {
3292         if (!defined $hash_base) {
3293                 $hash_base = git_get_head_hash($project);
3294         }
3295         if (!defined $page) {
3296                 $page = 0;
3297         }
3298         my $ftype;
3299         my %co = parse_commit($hash_base);
3300         if (!%co) {
3301                 die_error(undef, "Unknown commit object");
3302         }
3304         my $refs = git_get_references();
3305         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3307         if (!defined $hash && defined $file_name) {
3308                 $hash = git_get_hash_by_path($hash_base, $file_name);
3309         }
3310         if (defined $hash) {
3311                 $ftype = git_get_type($hash);
3312         }
3314         open my $fd, "-|",
3315                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3316                         or die_error(undef, "Open git-rev-list-failed");
3317         my @revlist = map { chomp; $_ } <$fd>;
3318         close $fd
3319                 or die_error(undef, "Reading git-rev-list failed");
3321         my $paging_nav = '';
3322         if ($page > 0) {
3323                 $paging_nav .=
3324                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3325                                                file_name=>$file_name)},
3326                                 "first");
3327                 $paging_nav .= " &sdot; " .
3328                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3329                                                file_name=>$file_name, page=>$page-1),
3330                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3331         } else {
3332                 $paging_nav .= "first";
3333                 $paging_nav .= " &sdot; prev";
3334         }
3335         if ($#revlist >= (100 * ($page+1)-1)) {
3336                 $paging_nav .= " &sdot; " .
3337                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3338                                                file_name=>$file_name, page=>$page+1),
3339                                  -accesskey => "n", -title => "Alt-n"}, "next");
3340         } else {
3341                 $paging_nav .= " &sdot; next";
3342         }
3343         my $next_link = '';
3344         if ($#revlist >= (100 * ($page+1)-1)) {
3345                 $next_link =
3346                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3347                                                file_name=>$file_name, page=>$page+1),
3348                                  -title => "Alt-n"}, "next");
3349         }
3351         git_header_html();
3352         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3353         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3354         git_print_page_path($file_name, $ftype, $hash_base);
3356         git_history_body(\@revlist, ($page * 100), $#revlist,
3357                          $refs, $hash_base, $ftype, $next_link);
3359         git_footer_html();
3362 sub git_search {
3363         if (!defined $searchtext) {
3364                 die_error(undef, "Text field empty");
3365         }
3366         if (!defined $hash) {
3367                 $hash = git_get_head_hash($project);
3368         }
3369         my %co = parse_commit($hash);
3370         if (!%co) {
3371                 die_error(undef, "Unknown commit object");
3372         }
3374         my $commit_search = 1;
3375         my $author_search = 0;
3376         my $committer_search = 0;
3377         my $pickaxe_search = 0;
3378         if ($searchtext =~ s/^author\\://i) {
3379                 $author_search = 1;
3380         } elsif ($searchtext =~ s/^committer\\://i) {
3381                 $committer_search = 1;
3382         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3383                 $commit_search = 0;
3384                 $pickaxe_search = 1;
3386                 # pickaxe may take all resources of your box and run for several minutes
3387                 # with every query - so decide by yourself how public you make this feature
3388                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3389                 if (!$have_pickaxe) {
3390                         die_error('403 Permission denied', "Permission denied");
3391                 }
3392         }
3393         git_header_html();
3394         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3395         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3397         print "<table cellspacing=\"0\">\n";
3398         my $alternate = 1;
3399         if ($commit_search) {
3400                 $/ = "\0";
3401                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3402                 while (my $commit_text = <$fd>) {
3403                         if (!grep m/$searchtext/i, $commit_text) {
3404                                 next;
3405                         }
3406                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3407                                 next;
3408                         }
3409                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3410                                 next;
3411                         }
3412                         my @commit_lines = split "\n", $commit_text;
3413                         my %co = parse_commit(undef, \@commit_lines);
3414                         if (!%co) {
3415                                 next;
3416                         }
3417                         if ($alternate) {
3418                                 print "<tr class=\"dark\">\n";
3419                         } else {
3420                                 print "<tr class=\"light\">\n";
3421                         }
3422                         $alternate ^= 1;
3423                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3424                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3425                               "<td>" .
3426                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3427                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3428                         my $comment = $co{'comment'};
3429                         foreach my $line (@$comment) {
3430                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3431                                         my $lead = esc_html($1) || "";
3432                                         $lead = chop_str($lead, 30, 10);
3433                                         my $match = esc_html($2) || "";
3434                                         my $trail = esc_html($3) || "";
3435                                         $trail = chop_str($trail, 30, 10);
3436                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3437                                         print chop_str($text, 80, 5) . "<br/>\n";
3438                                 }
3439                         }
3440                         print "</td>\n" .
3441                               "<td class=\"link\">" .
3442                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3443                               " | " .
3444                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3445                         print "</td>\n" .
3446                               "</tr>\n";
3447                 }
3448                 close $fd;
3449         }
3451         if ($pickaxe_search) {
3452                 $/ = "\n";
3453                 my $git_command = git_cmd_str();
3454                 open my $fd, "-|", "$git_command rev-list $hash | " .
3455                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3456                 undef %co;
3457                 my @files;
3458                 while (my $line = <$fd>) {
3459                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3460                                 my %set;
3461                                 $set{'file'} = $6;
3462                                 $set{'from_id'} = $3;
3463                                 $set{'to_id'} = $4;
3464                                 $set{'id'} = $set{'to_id'};
3465                                 if ($set{'id'} =~ m/0{40}/) {
3466                                         $set{'id'} = $set{'from_id'};
3467                                 }
3468                                 if ($set{'id'} =~ m/0{40}/) {
3469                                         next;
3470                                 }
3471                                 push @files, \%set;
3472                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3473                                 if (%co) {
3474                                         if ($alternate) {
3475                                                 print "<tr class=\"dark\">\n";
3476                                         } else {
3477                                                 print "<tr class=\"light\">\n";
3478                                         }
3479                                         $alternate ^= 1;
3480                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3481                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3482                                               "<td>" .
3483                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3484                                                       -class => "list subject"},
3485                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3486                                         while (my $setref = shift @files) {
3487                                                 my %set = %$setref;
3488                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3489                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3490                                                               -class => "list"},
3491                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3492                                                       "<br/>\n";
3493                                         }
3494                                         print "</td>\n" .
3495                                               "<td class=\"link\">" .
3496                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3497                                               " | " .
3498                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3499                                         print "</td>\n" .
3500                                               "</tr>\n";
3501                                 }
3502                                 %co = parse_commit($1);
3503                         }
3504                 }
3505                 close $fd;
3506         }
3507         print "</table>\n";
3508         git_footer_html();
3511 sub git_shortlog {
3512         my $head = git_get_head_hash($project);
3513         if (!defined $hash) {
3514                 $hash = $head;
3515         }
3516         if (!defined $page) {
3517                 $page = 0;
3518         }
3519         my $refs = git_get_references();
3521         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3522         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3523                 or die_error(undef, "Open git-rev-list failed");
3524         my @revlist = map { chomp; $_ } <$fd>;
3525         close $fd;
3527         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3528         my $next_link = '';
3529         if ($#revlist >= (100 * ($page+1)-1)) {
3530                 $next_link =
3531                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3532                                  -title => "Alt-n"}, "next");
3533         }
3536         git_header_html();
3537         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3538         git_print_header_div('summary', $project);
3540         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3542         git_footer_html();
3545 ## ......................................................................
3546 ## feeds (RSS, OPML)
3548 sub git_rss {
3549         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3550         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3551                 or die_error(undef, "Open git-rev-list failed");
3552         my @revlist = map { chomp; $_ } <$fd>;
3553         close $fd or die_error(undef, "Reading git-rev-list failed");
3554         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3555         print <<XML;
3556 <?xml version="1.0" encoding="utf-8"?>
3557 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3558 <channel>
3559 <title>$project $my_uri $my_url</title>
3560 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3561 <description>$project log</description>
3562 <language>en</language>
3563 XML
3565         for (my $i = 0; $i <= $#revlist; $i++) {
3566                 my $commit = $revlist[$i];
3567                 my %co = parse_commit($commit);
3568                 # we read 150, we always show 30 and the ones more recent than 48 hours
3569                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3570                         last;
3571                 }
3572                 my %cd = parse_date($co{'committer_epoch'});
3573                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3574                         $co{'parent'}, $co{'id'}
3575                         or next;
3576                 my @difftree = map { chomp; $_ } <$fd>;
3577                 close $fd
3578                         or next;
3579                 print "<item>\n" .
3580                       "<title>" .
3581                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3582                       "</title>\n" .
3583                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3584                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3585                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3586                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3587                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3588                       "<content:encoded>" .
3589                       "<![CDATA[\n";
3590                 my $comment = $co{'comment'};
3591                 foreach my $line (@$comment) {
3592                         $line = decode("utf8", $line, Encode::FB_DEFAULT);
3593                         print "$line<br/>\n";
3594                 }
3595                 print "<br/>\n";
3596                 foreach my $line (@difftree) {
3597                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3598                                 next;
3599                         }
3600                         my $file = esc_html(unquote($7));
3601                         $file = decode("utf8", $file, Encode::FB_DEFAULT);
3602                         print "$file<br/>\n";
3603                 }
3604                 print "]]>\n" .
3605                       "</content:encoded>\n" .
3606                       "</item>\n";
3607         }
3608         print "</channel></rss>";
3611 sub git_opml {
3612         my @list = git_get_projects_list();
3614         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3615         print <<XML;
3616 <?xml version="1.0" encoding="utf-8"?>
3617 <opml version="1.0">
3618 <head>
3619   <title>$site_name Git OPML Export</title>
3620 </head>
3621 <body>
3622 <outline text="git RSS feeds">
3623 XML
3625         foreach my $pr (@list) {
3626                 my %proj = %$pr;
3627                 my $head = git_get_head_hash($proj{'path'});
3628                 if (!defined $head) {
3629                         next;
3630                 }
3631                 $git_dir = "$projectroot/$proj{'path'}";
3632                 my %co = parse_commit($head);
3633                 if (!%co) {
3634                         next;
3635                 }
3637                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3638                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3639                 my $html = "$my_url?p=$proj{'path'};a=summary";
3640                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3641         }
3642         print <<XML;
3643 </outline>
3644 </body>
3645 </opml>
3646 XML