Code

Merge branch 'maint'
[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 (72x27 size)
50 our $logo = "++GITWEB_LOGO++";
51 # URI of GIT favicon, assumed to be image/png type
52 our $favicon = "++GITWEB_FAVICON++";
54 # URI and label (title) of GIT logo link
55 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
56 #our $logo_label = "git documentation";
57 our $logo_url = "http://git.or.cz/";
58 our $logo_label = "git homepage";
60 # source of projects list
61 our $projects_list = "++GITWEB_LIST++";
63 # show repository only if this file exists
64 # (only effective if this variable evaluates to true)
65 our $export_ok = "++GITWEB_EXPORT_OK++";
67 # only allow viewing of repositories also shown on the overview page
68 our $strict_export = "++GITWEB_STRICT_EXPORT++";
70 # list of git base URLs used for URL to where fetch project from,
71 # i.e. full URL is "$git_base_url/$project"
72 our @git_base_url_list = ("++GITWEB_BASE_URL++");
74 # default blob_plain mimetype and default charset for text/plain blob
75 our $default_blob_plain_mimetype = 'text/plain';
76 our $default_text_plain_charset  = undef;
78 # file to use for guessing MIME types before trying /etc/mime.types
79 # (relative to the current git repository)
80 our $mimetypes_file = undef;
82 # You define site-wide feature defaults here; override them with
83 # $GITWEB_CONFIG as necessary.
84 our %feature = (
85         # feature => {
86         #       'sub' => feature-sub (subroutine),
87         #       'override' => allow-override (boolean),
88         #       'default' => [ default options...] (array reference)}
89         #
90         # if feature is overridable (it means that allow-override has true value,
91         # then feature-sub will be called with default options as parameters;
92         # return value of feature-sub indicates if to enable specified feature
93         #
94         # use gitweb_check_feature(<feature>) to check if <feature> is enabled
96         # Enable the 'blame' blob view, showing the last commit that modified
97         # each line in the file. This can be very CPU-intensive.
99         # To enable system wide have in $GITWEB_CONFIG
100         # $feature{'blame'}{'default'} = [1];
101         # To have project specific config enable override in $GITWEB_CONFIG
102         # $feature{'blame'}{'override'} = 1;
103         # and in project config gitweb.blame = 0|1;
104         'blame' => {
105                 'sub' => \&feature_blame,
106                 'override' => 0,
107                 'default' => [0]},
109         # Enable the 'snapshot' link, providing a compressed tarball of any
110         # tree. This can potentially generate high traffic if you have large
111         # project.
113         # To disable system wide have in $GITWEB_CONFIG
114         # $feature{'snapshot'}{'default'} = [undef];
115         # To have project specific config enable override in $GITWEB_CONFIG
116         # $feature{'blame'}{'override'} = 1;
117         # and in project config gitweb.snapshot = none|gzip|bzip2;
118         'snapshot' => {
119                 'sub' => \&feature_snapshot,
120                 'override' => 0,
121                 #         => [content-encoding, suffix, program]
122                 'default' => ['x-gzip', 'gz', 'gzip']},
124         # Enable the pickaxe search, which will list the commits that modified
125         # a given string in a file. This can be practical and quite faster
126         # alternative to 'blame', but still potentially CPU-intensive.
128         # To enable system wide have in $GITWEB_CONFIG
129         # $feature{'pickaxe'}{'default'} = [1];
130         # To have project specific config enable override in $GITWEB_CONFIG
131         # $feature{'pickaxe'}{'override'} = 1;
132         # and in project config gitweb.pickaxe = 0|1;
133         'pickaxe' => {
134                 'sub' => \&feature_pickaxe,
135                 'override' => 0,
136                 'default' => [1]},
138         # Make gitweb use an alternative format of the URLs which can be
139         # more readable and natural-looking: project name is embedded
140         # directly in the path and the query string contains other
141         # auxiliary information. All gitweb installations recognize
142         # URL in either format; this configures in which formats gitweb
143         # generates links.
145         # To enable system wide have in $GITWEB_CONFIG
146         # $feature{'pathinfo'}{'default'} = [1];
147         # Project specific override is not supported.
149         # Note that you will need to change the default location of CSS,
150         # favicon, logo and possibly other files to an absolute URL. Also,
151         # if gitweb.cgi serves as your indexfile, you will need to force
152         # $my_uri to contain the script name in your $GITWEB_CONFIG.
153         'pathinfo' => {
154                 'override' => 0,
155                 'default' => [0]},
156 );
158 sub gitweb_check_feature {
159         my ($name) = @_;
160         return unless exists $feature{$name};
161         my ($sub, $override, @defaults) = (
162                 $feature{$name}{'sub'},
163                 $feature{$name}{'override'},
164                 @{$feature{$name}{'default'}});
165         if (!$override) { return @defaults; }
166         if (!defined $sub) {
167                 warn "feature $name is not overrideable";
168                 return @defaults;
169         }
170         return $sub->(@defaults);
173 sub feature_blame {
174         my ($val) = git_get_project_config('blame', '--bool');
176         if ($val eq 'true') {
177                 return 1;
178         } elsif ($val eq 'false') {
179                 return 0;
180         }
182         return $_[0];
185 sub feature_snapshot {
186         my ($ctype, $suffix, $command) = @_;
188         my ($val) = git_get_project_config('snapshot');
190         if ($val eq 'gzip') {
191                 return ('x-gzip', 'gz', 'gzip');
192         } elsif ($val eq 'bzip2') {
193                 return ('x-bzip2', 'bz2', 'bzip2');
194         } elsif ($val eq 'none') {
195                 return ();
196         }
198         return ($ctype, $suffix, $command);
201 sub gitweb_have_snapshot {
202         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
203         my $have_snapshot = (defined $ctype && defined $suffix);
205         return $have_snapshot;
208 sub feature_pickaxe {
209         my ($val) = git_get_project_config('pickaxe', '--bool');
211         if ($val eq 'true') {
212                 return (1);
213         } elsif ($val eq 'false') {
214                 return (0);
215         }
217         return ($_[0]);
220 # rename detection options for git-diff and git-diff-tree
221 # - default is '-M', with the cost proportional to
222 #   (number of removed files) * (number of new files).
223 # - more costly is '-C' (or '-C', '-M'), with the cost proportional to
224 #   (number of changed files + number of removed files) * (number of new files)
225 # - even more costly is '-C', '--find-copies-harder' with cost
226 #   (number of files in the original tree) * (number of new files)
227 # - one might want to include '-B' option, e.g. '-B', '-M'
228 our @diff_opts = ('-M'); # taken from git_commit
230 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
231 do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
233 # version of the core git binary
234 our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
236 $projects_list ||= $projectroot;
238 # ======================================================================
239 # input validation and dispatch
240 our $action = $cgi->param('a');
241 if (defined $action) {
242         if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
243                 die_error(undef, "Invalid action parameter");
244         }
247 # parameters which are pathnames
248 our $project = $cgi->param('p');
249 if (defined $project) {
250         if (!validate_pathname($project) ||
251             !(-d "$projectroot/$project") ||
252             !(-e "$projectroot/$project/HEAD") ||
253             ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
254             ($strict_export && !project_in_list($project))) {
255                 undef $project;
256                 die_error(undef, "No such project");
257         }
260 our $file_name = $cgi->param('f');
261 if (defined $file_name) {
262         if (!validate_pathname($file_name)) {
263                 die_error(undef, "Invalid file parameter");
264         }
267 our $file_parent = $cgi->param('fp');
268 if (defined $file_parent) {
269         if (!validate_pathname($file_parent)) {
270                 die_error(undef, "Invalid file parent parameter");
271         }
274 # parameters which are refnames
275 our $hash = $cgi->param('h');
276 if (defined $hash) {
277         if (!validate_refname($hash)) {
278                 die_error(undef, "Invalid hash parameter");
279         }
282 our $hash_parent = $cgi->param('hp');
283 if (defined $hash_parent) {
284         if (!validate_refname($hash_parent)) {
285                 die_error(undef, "Invalid hash parent parameter");
286         }
289 our $hash_base = $cgi->param('hb');
290 if (defined $hash_base) {
291         if (!validate_refname($hash_base)) {
292                 die_error(undef, "Invalid hash base parameter");
293         }
296 our $hash_parent_base = $cgi->param('hpb');
297 if (defined $hash_parent_base) {
298         if (!validate_refname($hash_parent_base)) {
299                 die_error(undef, "Invalid hash parent base parameter");
300         }
303 # other parameters
304 our $page = $cgi->param('pg');
305 if (defined $page) {
306         if ($page =~ m/[^0-9]/) {
307                 die_error(undef, "Invalid page parameter");
308         }
311 our $searchtext = $cgi->param('s');
312 if (defined $searchtext) {
313         if ($searchtext =~ m/[^a-zA-Z0-9_\.\/\-\+\:\@ ]/) {
314                 die_error(undef, "Invalid search parameter");
315         }
316         $searchtext = quotemeta $searchtext;
319 # now read PATH_INFO and use it as alternative to parameters
320 sub evaluate_path_info {
321         return if defined $project;
322         my $path_info = $ENV{"PATH_INFO"};
323         return if !$path_info;
324         $path_info =~ s,^/+,,;
325         return if !$path_info;
326         # find which part of PATH_INFO is project
327         $project = $path_info;
328         $project =~ s,/+$,,;
329         while ($project && !-e "$projectroot/$project/HEAD") {
330                 $project =~ s,/*[^/]*$,,;
331         }
332         # validate project
333         $project = validate_pathname($project);
334         if (!$project ||
335             ($export_ok && !-e "$projectroot/$project/$export_ok") ||
336             ($strict_export && !project_in_list($project))) {
337                 undef $project;
338                 return;
339         }
340         # do not change any parameters if an action is given using the query string
341         return if $action;
342         $path_info =~ s,^$project/*,,;
343         my ($refname, $pathname) = split(/:/, $path_info, 2);
344         if (defined $pathname) {
345                 # we got "project.git/branch:filename" or "project.git/branch:dir/"
346                 # we could use git_get_type(branch:pathname), but it needs $git_dir
347                 $pathname =~ s,^/+,,;
348                 if (!$pathname || substr($pathname, -1) eq "/") {
349                         $action  ||= "tree";
350                         $pathname =~ s,/$,,;
351                 } else {
352                         $action  ||= "blob_plain";
353                 }
354                 $hash_base ||= validate_refname($refname);
355                 $file_name ||= validate_pathname($pathname);
356         } elsif (defined $refname) {
357                 # we got "project.git/branch"
358                 $action ||= "shortlog";
359                 $hash   ||= validate_refname($refname);
360         }
362 evaluate_path_info();
364 # path to the current git repository
365 our $git_dir;
366 $git_dir = "$projectroot/$project" if $project;
368 # dispatch
369 my %actions = (
370         "blame" => \&git_blame2,
371         "blobdiff" => \&git_blobdiff,
372         "blobdiff_plain" => \&git_blobdiff_plain,
373         "blob" => \&git_blob,
374         "blob_plain" => \&git_blob_plain,
375         "commitdiff" => \&git_commitdiff,
376         "commitdiff_plain" => \&git_commitdiff_plain,
377         "commit" => \&git_commit,
378         "heads" => \&git_heads,
379         "history" => \&git_history,
380         "log" => \&git_log,
381         "rss" => \&git_rss,
382         "search" => \&git_search,
383         "shortlog" => \&git_shortlog,
384         "summary" => \&git_summary,
385         "tag" => \&git_tag,
386         "tags" => \&git_tags,
387         "tree" => \&git_tree,
388         "snapshot" => \&git_snapshot,
389         # those below don't need $project
390         "opml" => \&git_opml,
391         "project_list" => \&git_project_list,
392         "project_index" => \&git_project_index,
393 );
395 if (defined $project) {
396         $action ||= 'summary';
397 } else {
398         $action ||= 'project_list';
400 if (!defined($actions{$action})) {
401         die_error(undef, "Unknown action");
403 if ($action !~ m/^(opml|project_list|project_index)$/ &&
404     !$project) {
405         die_error(undef, "Project needed");
407 $actions{$action}->();
408 exit;
410 ## ======================================================================
411 ## action links
413 sub href(%) {
414         my %params = @_;
415         my $href = $my_uri;
417         # XXX: Warning: If you touch this, check the search form for updating,
418         # too.
420         my @mapping = (
421                 project => "p",
422                 action => "a",
423                 file_name => "f",
424                 file_parent => "fp",
425                 hash => "h",
426                 hash_parent => "hp",
427                 hash_base => "hb",
428                 hash_parent_base => "hpb",
429                 page => "pg",
430                 order => "o",
431                 searchtext => "s",
432         );
433         my %mapping = @mapping;
435         $params{'project'} = $project unless exists $params{'project'};
437         my ($use_pathinfo) = gitweb_check_feature('pathinfo');
438         if ($use_pathinfo) {
439                 # use PATH_INFO for project name
440                 $href .= "/$params{'project'}" if defined $params{'project'};
441                 delete $params{'project'};
443                 # Summary just uses the project path URL
444                 if (defined $params{'action'} && $params{'action'} eq 'summary') {
445                         delete $params{'action'};
446                 }
447         }
449         # now encode the parameters explicitly
450         my @result = ();
451         for (my $i = 0; $i < @mapping; $i += 2) {
452                 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
453                 if (defined $params{$name}) {
454                         push @result, $symbol . "=" . esc_param($params{$name});
455                 }
456         }
457         $href .= "?" . join(';', @result) if scalar @result;
459         return $href;
463 ## ======================================================================
464 ## validation, quoting/unquoting and escaping
466 sub validate_pathname {
467         my $input = shift || return undef;
469         # no '.' or '..' as elements of path, i.e. no '.' nor '..'
470         # at the beginning, at the end, and between slashes.
471         # also this catches doubled slashes
472         if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
473                 return undef;
474         }
475         # no null characters
476         if ($input =~ m!\0!) {
477                 return undef;
478         }
479         return $input;
482 sub validate_refname {
483         my $input = shift || return undef;
485         # textual hashes are O.K.
486         if ($input =~ m/^[0-9a-fA-F]{40}$/) {
487                 return $input;
488         }
489         # it must be correct pathname
490         $input = validate_pathname($input)
491                 or return undef;
492         # restrictions on ref name according to git-check-ref-format
493         if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
494                 return undef;
495         }
496         return $input;
499 # very thin wrapper for decode("utf8", $str, Encode::FB_DEFAULT);
500 sub to_utf8 {
501         my $str = shift;
502         return decode("utf8", $str, Encode::FB_DEFAULT);
505 # quote unsafe chars, but keep the slash, even when it's not
506 # correct, but quoted slashes look too horrible in bookmarks
507 sub esc_param {
508         my $str = shift;
509         $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
510         $str =~ s/\+/%2B/g;
511         $str =~ s/ /\+/g;
512         return $str;
515 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
516 sub esc_url {
517         my $str = shift;
518         $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
519         $str =~ s/\+/%2B/g;
520         $str =~ s/ /\+/g;
521         return $str;
524 # replace invalid utf8 character with SUBSTITUTION sequence
525 sub esc_html {
526         my $str = shift;
527         $str = to_utf8($str);
528         $str = escapeHTML($str);
529         $str =~ s/\014/^L/g; # escape FORM FEED (FF) character (e.g. in COPYING file)
530         $str =~ s/\033/^[/g; # "escape" ESCAPE (\e) character (e.g. commit 20a3847d8a5032ce41f90dcc68abfb36e6fee9b1)
531         return $str;
534 # git may return quoted and escaped filenames
535 sub unquote {
536         my $str = shift;
537         if ($str =~ m/^"(.*)"$/) {
538                 $str = $1;
539                 $str =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
540         }
541         return $str;
544 # escape tabs (convert tabs to spaces)
545 sub untabify {
546         my $line = shift;
548         while ((my $pos = index($line, "\t")) != -1) {
549                 if (my $count = (8 - ($pos % 8))) {
550                         my $spaces = ' ' x $count;
551                         $line =~ s/\t/$spaces/;
552                 }
553         }
555         return $line;
558 sub project_in_list {
559         my $project = shift;
560         my @list = git_get_projects_list();
561         return @list && scalar(grep { $_->{'path'} eq $project } @list);
564 ## ----------------------------------------------------------------------
565 ## HTML aware string manipulation
567 sub chop_str {
568         my $str = shift;
569         my $len = shift;
570         my $add_len = shift || 10;
572         # allow only $len chars, but don't cut a word if it would fit in $add_len
573         # if it doesn't fit, cut it if it's still longer than the dots we would add
574         $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
575         my $body = $1;
576         my $tail = $2;
577         if (length($tail) > 4) {
578                 $tail = " ...";
579                 $body =~ s/&[^;]*$//; # remove chopped character entities
580         }
581         return "$body$tail";
584 ## ----------------------------------------------------------------------
585 ## functions returning short strings
587 # CSS class for given age value (in seconds)
588 sub age_class {
589         my $age = shift;
591         if ($age < 60*60*2) {
592                 return "age0";
593         } elsif ($age < 60*60*24*2) {
594                 return "age1";
595         } else {
596                 return "age2";
597         }
600 # convert age in seconds to "nn units ago" string
601 sub age_string {
602         my $age = shift;
603         my $age_str;
605         if ($age > 60*60*24*365*2) {
606                 $age_str = (int $age/60/60/24/365);
607                 $age_str .= " years ago";
608         } elsif ($age > 60*60*24*(365/12)*2) {
609                 $age_str = int $age/60/60/24/(365/12);
610                 $age_str .= " months ago";
611         } elsif ($age > 60*60*24*7*2) {
612                 $age_str = int $age/60/60/24/7;
613                 $age_str .= " weeks ago";
614         } elsif ($age > 60*60*24*2) {
615                 $age_str = int $age/60/60/24;
616                 $age_str .= " days ago";
617         } elsif ($age > 60*60*2) {
618                 $age_str = int $age/60/60;
619                 $age_str .= " hours ago";
620         } elsif ($age > 60*2) {
621                 $age_str = int $age/60;
622                 $age_str .= " min ago";
623         } elsif ($age > 2) {
624                 $age_str = int $age;
625                 $age_str .= " sec ago";
626         } else {
627                 $age_str .= " right now";
628         }
629         return $age_str;
632 # convert file mode in octal to symbolic file mode string
633 sub mode_str {
634         my $mode = oct shift;
636         if (S_ISDIR($mode & S_IFMT)) {
637                 return 'drwxr-xr-x';
638         } elsif (S_ISLNK($mode)) {
639                 return 'lrwxrwxrwx';
640         } elsif (S_ISREG($mode)) {
641                 # git cares only about the executable bit
642                 if ($mode & S_IXUSR) {
643                         return '-rwxr-xr-x';
644                 } else {
645                         return '-rw-r--r--';
646                 };
647         } else {
648                 return '----------';
649         }
652 # convert file mode in octal to file type string
653 sub file_type {
654         my $mode = shift;
656         if ($mode !~ m/^[0-7]+$/) {
657                 return $mode;
658         } else {
659                 $mode = oct $mode;
660         }
662         if (S_ISDIR($mode & S_IFMT)) {
663                 return "directory";
664         } elsif (S_ISLNK($mode)) {
665                 return "symlink";
666         } elsif (S_ISREG($mode)) {
667                 return "file";
668         } else {
669                 return "unknown";
670         }
673 ## ----------------------------------------------------------------------
674 ## functions returning short HTML fragments, or transforming HTML fragments
675 ## which don't beling to other sections
677 # format line of commit message or tag comment
678 sub format_log_line_html {
679         my $line = shift;
681         $line = esc_html($line);
682         $line =~ s/ /&nbsp;/g;
683         if ($line =~ m/([0-9a-fA-F]{40})/) {
684                 my $hash_text = $1;
685                 if (git_get_type($hash_text) eq "commit") {
686                         my $link =
687                                 $cgi->a({-href => href(action=>"commit", hash=>$hash_text),
688                                         -class => "text"}, $hash_text);
689                         $line =~ s/$hash_text/$link/;
690                 }
691         }
692         return $line;
695 # format marker of refs pointing to given object
696 sub format_ref_marker {
697         my ($refs, $id) = @_;
698         my $markers = '';
700         if (defined $refs->{$id}) {
701                 foreach my $ref (@{$refs->{$id}}) {
702                         my ($type, $name) = qw();
703                         # e.g. tags/v2.6.11 or heads/next
704                         if ($ref =~ m!^(.*?)s?/(.*)$!) {
705                                 $type = $1;
706                                 $name = $2;
707                         } else {
708                                 $type = "ref";
709                                 $name = $ref;
710                         }
712                         $markers .= " <span class=\"$type\">" . esc_html($name) . "</span>";
713                 }
714         }
716         if ($markers) {
717                 return ' <span class="refs">'. $markers . '</span>';
718         } else {
719                 return "";
720         }
723 # format, perhaps shortened and with markers, title line
724 sub format_subject_html {
725         my ($long, $short, $href, $extra) = @_;
726         $extra = '' unless defined($extra);
728         if (length($short) < length($long)) {
729                 return $cgi->a({-href => $href, -class => "list subject",
730                                 -title => to_utf8($long)},
731                        esc_html($short) . $extra);
732         } else {
733                 return $cgi->a({-href => $href, -class => "list subject"},
734                        esc_html($long)  . $extra);
735         }
738 sub format_diff_line {
739         my $line = shift;
740         my $char = substr($line, 0, 1);
741         my $diff_class = "";
743         chomp $line;
745         if ($char eq '+') {
746                 $diff_class = " add";
747         } elsif ($char eq "-") {
748                 $diff_class = " rem";
749         } elsif ($char eq "@") {
750                 $diff_class = " chunk_header";
751         } elsif ($char eq "\\") {
752                 $diff_class = " incomplete";
753         }
754         $line = untabify($line);
755         return "<div class=\"diff$diff_class\">" . esc_html($line) . "</div>\n";
758 ## ----------------------------------------------------------------------
759 ## git utility subroutines, invoking git commands
761 # returns path to the core git executable and the --git-dir parameter as list
762 sub git_cmd {
763         return $GIT, '--git-dir='.$git_dir;
766 # returns path to the core git executable and the --git-dir parameter as string
767 sub git_cmd_str {
768         return join(' ', git_cmd());
771 # get HEAD ref of given project as hash
772 sub git_get_head_hash {
773         my $project = shift;
774         my $o_git_dir = $git_dir;
775         my $retval = undef;
776         $git_dir = "$projectroot/$project";
777         if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
778                 my $head = <$fd>;
779                 close $fd;
780                 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
781                         $retval = $1;
782                 }
783         }
784         if (defined $o_git_dir) {
785                 $git_dir = $o_git_dir;
786         }
787         return $retval;
790 # get type of given object
791 sub git_get_type {
792         my $hash = shift;
794         open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
795         my $type = <$fd>;
796         close $fd or return;
797         chomp $type;
798         return $type;
801 sub git_get_project_config {
802         my ($key, $type) = @_;
804         return unless ($key);
805         $key =~ s/^gitweb\.//;
806         return if ($key =~ m/\W/);
808         my @x = (git_cmd(), 'repo-config');
809         if (defined $type) { push @x, $type; }
810         push @x, "--get";
811         push @x, "gitweb.$key";
812         my $val = qx(@x);
813         chomp $val;
814         return ($val);
817 # get hash of given path at given ref
818 sub git_get_hash_by_path {
819         my $base = shift;
820         my $path = shift || return undef;
821         my $type = shift;
823         $path =~ s,/+$,,;
825         open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
826                 or die_error(undef, "Open git-ls-tree failed");
827         my $line = <$fd>;
828         close $fd or return undef;
830         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
831         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
832         if (defined $type && $type ne $2) {
833                 # type doesn't match
834                 return undef;
835         }
836         return $3;
839 ## ......................................................................
840 ## git utility functions, directly accessing git repository
842 sub git_get_project_description {
843         my $path = shift;
845         open my $fd, "$projectroot/$path/description" or return undef;
846         my $descr = <$fd>;
847         close $fd;
848         chomp $descr;
849         return $descr;
852 sub git_get_project_url_list {
853         my $path = shift;
855         open my $fd, "$projectroot/$path/cloneurl" or return;
856         my @git_project_url_list = map { chomp; $_ } <$fd>;
857         close $fd;
859         return wantarray ? @git_project_url_list : \@git_project_url_list;
862 sub git_get_projects_list {
863         my @list;
865         if (-d $projects_list) {
866                 # search in directory
867                 my $dir = $projects_list;
868                 my $pfxlen = length("$dir");
870                 File::Find::find({
871                         follow_fast => 1, # follow symbolic links
872                         dangling_symlinks => 0, # ignore dangling symlinks, silently
873                         wanted => sub {
874                                 # skip project-list toplevel, if we get it.
875                                 return if (m!^[/.]$!);
876                                 # only directories can be git repositories
877                                 return unless (-d $_);
879                                 my $subdir = substr($File::Find::name, $pfxlen + 1);
880                                 # we check related file in $projectroot
881                                 if (-e "$projectroot/$subdir/HEAD" && (!$export_ok ||
882                                     -e "$projectroot/$subdir/$export_ok")) {
883                                         push @list, { path => $subdir };
884                                         $File::Find::prune = 1;
885                                 }
886                         },
887                 }, "$dir");
889         } elsif (-f $projects_list) {
890                 # read from file(url-encoded):
891                 # 'git%2Fgit.git Linus+Torvalds'
892                 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
893                 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
894                 open my ($fd), $projects_list or return;
895                 while (my $line = <$fd>) {
896                         chomp $line;
897                         my ($path, $owner) = split ' ', $line;
898                         $path = unescape($path);
899                         $owner = unescape($owner);
900                         if (!defined $path) {
901                                 next;
902                         }
903                         if (-e "$projectroot/$path/HEAD" && (!$export_ok ||
904                             -e "$projectroot/$path/$export_ok")) {
905                                 my $pr = {
906                                         path => $path,
907                                         owner => to_utf8($owner),
908                                 };
909                                 push @list, $pr
910                         }
911                 }
912                 close $fd;
913         }
914         @list = sort {$a->{'path'} cmp $b->{'path'}} @list;
915         return @list;
918 sub git_get_project_owner {
919         my $project = shift;
920         my $owner;
922         return undef unless $project;
924         # read from file (url-encoded):
925         # 'git%2Fgit.git Linus+Torvalds'
926         # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
927         # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
928         if (-f $projects_list) {
929                 open (my $fd , $projects_list);
930                 while (my $line = <$fd>) {
931                         chomp $line;
932                         my ($pr, $ow) = split ' ', $line;
933                         $pr = unescape($pr);
934                         $ow = unescape($ow);
935                         if ($pr eq $project) {
936                                 $owner = to_utf8($ow);
937                                 last;
938                         }
939                 }
940                 close $fd;
941         }
942         if (!defined $owner) {
943                 $owner = get_file_owner("$projectroot/$project");
944         }
946         return $owner;
949 sub git_get_references {
950         my $type = shift || "";
951         my %refs;
952         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c      refs/tags/v2.6.11
953         # c39ae07f393806ccf406ef966e9a15afc43cc36a      refs/tags/v2.6.11^{}
954         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
955                 or return;
957         while (my $line = <$fd>) {
958                 chomp $line;
959                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?[^\^]+)/) {
960                         if (defined $refs{$1}) {
961                                 push @{$refs{$1}}, $2;
962                         } else {
963                                 $refs{$1} = [ $2 ];
964                         }
965                 }
966         }
967         close $fd or return;
968         return \%refs;
971 sub git_get_rev_name_tags {
972         my $hash = shift || return undef;
974         open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
975                 or return;
976         my $name_rev = <$fd>;
977         close $fd;
979         if ($name_rev =~ m|^$hash tags/(.*)$|) {
980                 return $1;
981         } else {
982                 # catches also '$hash undefined' output
983                 return undef;
984         }
987 ## ----------------------------------------------------------------------
988 ## parse to hash functions
990 sub parse_date {
991         my $epoch = shift;
992         my $tz = shift || "-0000";
994         my %date;
995         my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
996         my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
997         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
998         $date{'hour'} = $hour;
999         $date{'minute'} = $min;
1000         $date{'mday'} = $mday;
1001         $date{'day'} = $days[$wday];
1002         $date{'month'} = $months[$mon];
1003         $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1004                            $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1005         $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1006                              $mday, $months[$mon], $hour ,$min;
1008         $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1009         my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1010         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1011         $date{'hour_local'} = $hour;
1012         $date{'minute_local'} = $min;
1013         $date{'tz_local'} = $tz;
1014         return %date;
1017 sub parse_tag {
1018         my $tag_id = shift;
1019         my %tag;
1020         my @comment;
1022         open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1023         $tag{'id'} = $tag_id;
1024         while (my $line = <$fd>) {
1025                 chomp $line;
1026                 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1027                         $tag{'object'} = $1;
1028                 } elsif ($line =~ m/^type (.+)$/) {
1029                         $tag{'type'} = $1;
1030                 } elsif ($line =~ m/^tag (.+)$/) {
1031                         $tag{'name'} = $1;
1032                 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
1033                         $tag{'author'} = $1;
1034                         $tag{'epoch'} = $2;
1035                         $tag{'tz'} = $3;
1036                 } elsif ($line =~ m/--BEGIN/) {
1037                         push @comment, $line;
1038                         last;
1039                 } elsif ($line eq "") {
1040                         last;
1041                 }
1042         }
1043         push @comment, <$fd>;
1044         $tag{'comment'} = \@comment;
1045         close $fd or return;
1046         if (!defined $tag{'name'}) {
1047                 return
1048         };
1049         return %tag
1052 sub parse_commit {
1053         my $commit_id = shift;
1054         my $commit_text = shift;
1056         my @commit_lines;
1057         my %co;
1059         if (defined $commit_text) {
1060                 @commit_lines = @$commit_text;
1061         } else {
1062                 local $/ = "\0";
1063                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", "--max-count=1", $commit_id
1064                         or return;
1065                 @commit_lines = split '\n', <$fd>;
1066                 close $fd or return;
1067                 pop @commit_lines;
1068         }
1069         my $header = shift @commit_lines;
1070         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1071                 return;
1072         }
1073         ($co{'id'}, my @parents) = split ' ', $header;
1074         $co{'parents'} = \@parents;
1075         $co{'parent'} = $parents[0];
1076         while (my $line = shift @commit_lines) {
1077                 last if $line eq "\n";
1078                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1079                         $co{'tree'} = $1;
1080                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1081                         $co{'author'} = $1;
1082                         $co{'author_epoch'} = $2;
1083                         $co{'author_tz'} = $3;
1084                         if ($co{'author'} =~ m/^([^<]+) </) {
1085                                 $co{'author_name'} = $1;
1086                         } else {
1087                                 $co{'author_name'} = $co{'author'};
1088                         }
1089                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1090                         $co{'committer'} = $1;
1091                         $co{'committer_epoch'} = $2;
1092                         $co{'committer_tz'} = $3;
1093                         $co{'committer_name'} = $co{'committer'};
1094                         $co{'committer_name'} =~ s/ <.*//;
1095                 }
1096         }
1097         if (!defined $co{'tree'}) {
1098                 return;
1099         };
1101         foreach my $title (@commit_lines) {
1102                 $title =~ s/^    //;
1103                 if ($title ne "") {
1104                         $co{'title'} = chop_str($title, 80, 5);
1105                         # remove leading stuff of merges to make the interesting part visible
1106                         if (length($title) > 50) {
1107                                 $title =~ s/^Automatic //;
1108                                 $title =~ s/^merge (of|with) /Merge ... /i;
1109                                 if (length($title) > 50) {
1110                                         $title =~ s/(http|rsync):\/\///;
1111                                 }
1112                                 if (length($title) > 50) {
1113                                         $title =~ s/(master|www|rsync)\.//;
1114                                 }
1115                                 if (length($title) > 50) {
1116                                         $title =~ s/kernel.org:?//;
1117                                 }
1118                                 if (length($title) > 50) {
1119                                         $title =~ s/\/pub\/scm//;
1120                                 }
1121                         }
1122                         $co{'title_short'} = chop_str($title, 50, 5);
1123                         last;
1124                 }
1125         }
1126         if ($co{'title'} eq "") {
1127                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1128         }
1129         # remove added spaces
1130         foreach my $line (@commit_lines) {
1131                 $line =~ s/^    //;
1132         }
1133         $co{'comment'} = \@commit_lines;
1135         my $age = time - $co{'committer_epoch'};
1136         $co{'age'} = $age;
1137         $co{'age_string'} = age_string($age);
1138         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1139         if ($age > 60*60*24*7*2) {
1140                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1141                 $co{'age_string_age'} = $co{'age_string'};
1142         } else {
1143                 $co{'age_string_date'} = $co{'age_string'};
1144                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1145         }
1146         return %co;
1149 # parse ref from ref_file, given by ref_id, with given type
1150 sub parse_ref {
1151         my $ref_file = shift;
1152         my $ref_id = shift;
1153         my $type = shift || git_get_type($ref_id);
1154         my %ref_item;
1156         $ref_item{'type'} = $type;
1157         $ref_item{'id'} = $ref_id;
1158         $ref_item{'epoch'} = 0;
1159         $ref_item{'age'} = "unknown";
1160         if ($type eq "tag") {
1161                 my %tag = parse_tag($ref_id);
1162                 $ref_item{'comment'} = $tag{'comment'};
1163                 if ($tag{'type'} eq "commit") {
1164                         my %co = parse_commit($tag{'object'});
1165                         $ref_item{'epoch'} = $co{'committer_epoch'};
1166                         $ref_item{'age'} = $co{'age_string'};
1167                 } elsif (defined($tag{'epoch'})) {
1168                         my $age = time - $tag{'epoch'};
1169                         $ref_item{'epoch'} = $tag{'epoch'};
1170                         $ref_item{'age'} = age_string($age);
1171                 }
1172                 $ref_item{'reftype'} = $tag{'type'};
1173                 $ref_item{'name'} = $tag{'name'};
1174                 $ref_item{'refid'} = $tag{'object'};
1175         } elsif ($type eq "commit"){
1176                 my %co = parse_commit($ref_id);
1177                 $ref_item{'reftype'} = "commit";
1178                 $ref_item{'name'} = $ref_file;
1179                 $ref_item{'title'} = $co{'title'};
1180                 $ref_item{'refid'} = $ref_id;
1181                 $ref_item{'epoch'} = $co{'committer_epoch'};
1182                 $ref_item{'age'} = $co{'age_string'};
1183         } else {
1184                 $ref_item{'reftype'} = $type;
1185                 $ref_item{'name'} = $ref_file;
1186                 $ref_item{'refid'} = $ref_id;
1187         }
1189         return %ref_item;
1192 # parse line of git-diff-tree "raw" output
1193 sub parse_difftree_raw_line {
1194         my $line = shift;
1195         my %res;
1197         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1198         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1199         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1200                 $res{'from_mode'} = $1;
1201                 $res{'to_mode'} = $2;
1202                 $res{'from_id'} = $3;
1203                 $res{'to_id'} = $4;
1204                 $res{'status'} = $5;
1205                 $res{'similarity'} = $6;
1206                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1207                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1208                 } else {
1209                         $res{'file'} = unquote($7);
1210                 }
1211         }
1212         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1213         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1214                 $res{'commit'} = $1;
1215         }
1217         return wantarray ? %res : \%res;
1220 # parse line of git-ls-tree output
1221 sub parse_ls_tree_line ($;%) {
1222         my $line = shift;
1223         my %opts = @_;
1224         my %res;
1226         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1227         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1229         $res{'mode'} = $1;
1230         $res{'type'} = $2;
1231         $res{'hash'} = $3;
1232         if ($opts{'-z'}) {
1233                 $res{'name'} = $4;
1234         } else {
1235                 $res{'name'} = unquote($4);
1236         }
1238         return wantarray ? %res : \%res;
1241 ## ......................................................................
1242 ## parse to array of hashes functions
1244 sub git_get_refs_list {
1245         my $type = shift || "";
1246         my %refs;
1247         my @reflist;
1249         my @refs;
1250         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1251                 or return;
1252         while (my $line = <$fd>) {
1253                 chomp $line;
1254                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?([^\^]+))(\^\{\})?$/) {
1255                         if (defined $refs{$1}) {
1256                                 push @{$refs{$1}}, $2;
1257                         } else {
1258                                 $refs{$1} = [ $2 ];
1259                         }
1261                         if (! $4) { # unpeeled, direct reference
1262                                 push @refs, { hash => $1, name => $3 }; # without type
1263                         } elsif ($3 eq $refs[-1]{'name'}) {
1264                                 # most likely a tag is followed by its peeled
1265                                 # (deref) one, and when that happens we know the
1266                                 # previous one was of type 'tag'.
1267                                 $refs[-1]{'type'} = "tag";
1268                         }
1269                 }
1270         }
1271         close $fd;
1273         foreach my $ref (@refs) {
1274                 my $ref_file = $ref->{'name'};
1275                 my $ref_id   = $ref->{'hash'};
1277                 my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1278                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
1280                 push @reflist, \%ref_item;
1281         }
1282         # sort refs by age
1283         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1284         return (\@reflist, \%refs);
1287 ## ----------------------------------------------------------------------
1288 ## filesystem-related functions
1290 sub get_file_owner {
1291         my $path = shift;
1293         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1294         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1295         if (!defined $gcos) {
1296                 return undef;
1297         }
1298         my $owner = $gcos;
1299         $owner =~ s/[,;].*$//;
1300         return to_utf8($owner);
1303 ## ......................................................................
1304 ## mimetype related functions
1306 sub mimetype_guess_file {
1307         my $filename = shift;
1308         my $mimemap = shift;
1309         -r $mimemap or return undef;
1311         my %mimemap;
1312         open(MIME, $mimemap) or return undef;
1313         while (<MIME>) {
1314                 next if m/^#/; # skip comments
1315                 my ($mime, $exts) = split(/\t+/);
1316                 if (defined $exts) {
1317                         my @exts = split(/\s+/, $exts);
1318                         foreach my $ext (@exts) {
1319                                 $mimemap{$ext} = $mime;
1320                         }
1321                 }
1322         }
1323         close(MIME);
1325         $filename =~ /\.([^.]*)$/;
1326         return $mimemap{$1};
1329 sub mimetype_guess {
1330         my $filename = shift;
1331         my $mime;
1332         $filename =~ /\./ or return undef;
1334         if ($mimetypes_file) {
1335                 my $file = $mimetypes_file;
1336                 if ($file !~ m!^/!) { # if it is relative path
1337                         # it is relative to project
1338                         $file = "$projectroot/$project/$file";
1339                 }
1340                 $mime = mimetype_guess_file($filename, $file);
1341         }
1342         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1343         return $mime;
1346 sub blob_mimetype {
1347         my $fd = shift;
1348         my $filename = shift;
1350         if ($filename) {
1351                 my $mime = mimetype_guess($filename);
1352                 $mime and return $mime;
1353         }
1355         # just in case
1356         return $default_blob_plain_mimetype unless $fd;
1358         if (-T $fd) {
1359                 return 'text/plain' .
1360                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1361         } elsif (! $filename) {
1362                 return 'application/octet-stream';
1363         } elsif ($filename =~ m/\.png$/i) {
1364                 return 'image/png';
1365         } elsif ($filename =~ m/\.gif$/i) {
1366                 return 'image/gif';
1367         } elsif ($filename =~ m/\.jpe?g$/i) {
1368                 return 'image/jpeg';
1369         } else {
1370                 return 'application/octet-stream';
1371         }
1374 ## ======================================================================
1375 ## functions printing HTML: header, footer, error page
1377 sub git_header_html {
1378         my $status = shift || "200 OK";
1379         my $expires = shift;
1381         my $title = "$site_name git";
1382         if (defined $project) {
1383                 $title .= " - $project";
1384                 if (defined $action) {
1385                         $title .= "/$action";
1386                         if (defined $file_name) {
1387                                 $title .= " - " . esc_html($file_name);
1388                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1389                                         $title .= "/";
1390                                 }
1391                         }
1392                 }
1393         }
1394         my $content_type;
1395         # require explicit support from the UA if we are to send the page as
1396         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1397         # we have to do this because MSIE sometimes globs '*/*', pretending to
1398         # support xhtml+xml but choking when it gets what it asked for.
1399         if (defined $cgi->http('HTTP_ACCEPT') &&
1400             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1401             $cgi->Accept('application/xhtml+xml') != 0) {
1402                 $content_type = 'application/xhtml+xml';
1403         } else {
1404                 $content_type = 'text/html';
1405         }
1406         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1407                            -status=> $status, -expires => $expires);
1408         print <<EOF;
1409 <?xml version="1.0" encoding="utf-8"?>
1410 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1411 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1412 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1413 <!-- git core binaries version $git_version -->
1414 <head>
1415 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1416 <meta name="generator" content="gitweb/$version git/$git_version"/>
1417 <meta name="robots" content="index, nofollow"/>
1418 <title>$title</title>
1419 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1420 EOF
1421         if (defined $project) {
1422                 printf('<link rel="alternate" title="%s log" '.
1423                        'href="%s" type="application/rss+xml"/>'."\n",
1424                        esc_param($project), href(action=>"rss"));
1425         } else {
1426                 printf('<link rel="alternate" title="%s projects list" '.
1427                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1428                        $site_name, href(project=>undef, action=>"project_index"));
1429                 printf('<link rel="alternate" title="%s projects logs" '.
1430                        'href="%s" type="text/x-opml"/>'."\n",
1431                        $site_name, href(project=>undef, action=>"opml"));
1432         }
1433         if (defined $favicon) {
1434                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1435         }
1437         print "</head>\n" .
1438               "<body>\n" .
1439               "<div class=\"page_header\">\n" .
1440               $cgi->a({-href => esc_url($logo_url),
1441                        -title => $logo_label},
1442                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1443         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1444         if (defined $project) {
1445                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1446                 if (defined $action) {
1447                         print " / $action";
1448                 }
1449                 print "\n";
1450                 if (!defined $searchtext) {
1451                         $searchtext = "";
1452                 }
1453                 my $search_hash;
1454                 if (defined $hash_base) {
1455                         $search_hash = $hash_base;
1456                 } elsif (defined $hash) {
1457                         $search_hash = $hash;
1458                 } else {
1459                         $search_hash = "HEAD";
1460                 }
1461                 $cgi->param("a", "search");
1462                 $cgi->param("h", $search_hash);
1463                 $cgi->param("p", $project);
1464                 print $cgi->startform(-method => "get", -action => $my_uri) .
1465                       "<div class=\"search\">\n" .
1466                       $cgi->hidden(-name => "p") . "\n" .
1467                       $cgi->hidden(-name => "a") . "\n" .
1468                       $cgi->hidden(-name => "h") . "\n" .
1469                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1470                       "</div>" .
1471                       $cgi->end_form() . "\n";
1472         }
1473         print "</div>\n";
1476 sub git_footer_html {
1477         print "<div class=\"page_footer\">\n";
1478         if (defined $project) {
1479                 my $descr = git_get_project_description($project);
1480                 if (defined $descr) {
1481                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1482                 }
1483                 print $cgi->a({-href => href(action=>"rss"),
1484                               -class => "rss_logo"}, "RSS") . "\n";
1485         } else {
1486                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1487                               -class => "rss_logo"}, "OPML") . " ";
1488                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1489                               -class => "rss_logo"}, "TXT") . "\n";
1490         }
1491         print "</div>\n" .
1492               "</body>\n" .
1493               "</html>";
1496 sub die_error {
1497         my $status = shift || "403 Forbidden";
1498         my $error = shift || "Malformed query, file missing or permission denied";
1500         git_header_html($status);
1501         print <<EOF;
1502 <div class="page_body">
1503 <br /><br />
1504 $status - $error
1505 <br />
1506 </div>
1507 EOF
1508         git_footer_html();
1509         exit;
1512 ## ----------------------------------------------------------------------
1513 ## functions printing or outputting HTML: navigation
1515 sub git_print_page_nav {
1516         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1517         $extra = '' if !defined $extra; # pager or formats
1519         my @navs = qw(summary shortlog log commit commitdiff tree);
1520         if ($suppress) {
1521                 @navs = grep { $_ ne $suppress } @navs;
1522         }
1524         my %arg = map { $_ => {action=>$_} } @navs;
1525         if (defined $head) {
1526                 for (qw(commit commitdiff)) {
1527                         $arg{$_}{hash} = $head;
1528                 }
1529                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1530                         for (qw(shortlog log)) {
1531                                 $arg{$_}{hash} = $head;
1532                         }
1533                 }
1534         }
1535         $arg{tree}{hash} = $treehead if defined $treehead;
1536         $arg{tree}{hash_base} = $treebase if defined $treebase;
1538         print "<div class=\"page_nav\">\n" .
1539                 (join " | ",
1540                  map { $_ eq $current ?
1541                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1542                  } @navs);
1543         print "<br/>\n$extra<br/>\n" .
1544               "</div>\n";
1547 sub format_paging_nav {
1548         my ($action, $hash, $head, $page, $nrevs) = @_;
1549         my $paging_nav;
1552         if ($hash ne $head || $page) {
1553                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1554         } else {
1555                 $paging_nav .= "HEAD";
1556         }
1558         if ($page > 0) {
1559                 $paging_nav .= " &sdot; " .
1560                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1561                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1562         } else {
1563                 $paging_nav .= " &sdot; prev";
1564         }
1566         if ($nrevs >= (100 * ($page+1)-1)) {
1567                 $paging_nav .= " &sdot; " .
1568                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1569                                  -accesskey => "n", -title => "Alt-n"}, "next");
1570         } else {
1571                 $paging_nav .= " &sdot; next";
1572         }
1574         return $paging_nav;
1577 ## ......................................................................
1578 ## functions printing or outputting HTML: div
1580 sub git_print_header_div {
1581         my ($action, $title, $hash, $hash_base) = @_;
1582         my %args = ();
1584         $args{action} = $action;
1585         $args{hash} = $hash if $hash;
1586         $args{hash_base} = $hash_base if $hash_base;
1588         print "<div class=\"header\">\n" .
1589               $cgi->a({-href => href(%args), -class => "title"},
1590               $title ? $title : $action) .
1591               "\n</div>\n";
1594 #sub git_print_authorship (\%) {
1595 sub git_print_authorship {
1596         my $co = shift;
1598         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1599         print "<div class=\"author_date\">" .
1600               esc_html($co->{'author_name'}) .
1601               " [$ad{'rfc2822'}";
1602         if ($ad{'hour_local'} < 6) {
1603                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1604                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1605         } else {
1606                 printf(" (%02d:%02d %s)",
1607                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1608         }
1609         print "]</div>\n";
1612 sub git_print_page_path {
1613         my $name = shift;
1614         my $type = shift;
1615         my $hb = shift;
1618         print "<div class=\"page_path\">";
1619         print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1620                       -title => 'tree root'}, "[$project]");
1621         print " / ";
1622         if (defined $name) {
1623                 my @dirname = split '/', $name;
1624                 my $basename = pop @dirname;
1625                 my $fullname = '';
1627                 foreach my $dir (@dirname) {
1628                         $fullname .= ($fullname ? '/' : '') . $dir;
1629                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1630                                                      hash_base=>$hb),
1631                                       -title => $fullname}, esc_html($dir));
1632                         print " / ";
1633                 }
1634                 if (defined $type && $type eq 'blob') {
1635                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1636                                                      hash_base=>$hb),
1637                                       -title => $name}, esc_html($basename));
1638                 } elsif (defined $type && $type eq 'tree') {
1639                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1640                                                      hash_base=>$hb),
1641                                       -title => $name}, esc_html($basename));
1642                         print " / ";
1643                 } else {
1644                         print esc_html($basename);
1645                 }
1646         }
1647         print "<br/></div>\n";
1650 # sub git_print_log (\@;%) {
1651 sub git_print_log ($;%) {
1652         my $log = shift;
1653         my %opts = @_;
1655         if ($opts{'-remove_title'}) {
1656                 # remove title, i.e. first line of log
1657                 shift @$log;
1658         }
1659         # remove leading empty lines
1660         while (defined $log->[0] && $log->[0] eq "") {
1661                 shift @$log;
1662         }
1664         # print log
1665         my $signoff = 0;
1666         my $empty = 0;
1667         foreach my $line (@$log) {
1668                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1669                         $signoff = 1;
1670                         $empty = 0;
1671                         if (! $opts{'-remove_signoff'}) {
1672                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1673                                 next;
1674                         } else {
1675                                 # remove signoff lines
1676                                 next;
1677                         }
1678                 } else {
1679                         $signoff = 0;
1680                 }
1682                 # print only one empty line
1683                 # do not print empty line after signoff
1684                 if ($line eq "") {
1685                         next if ($empty || $signoff);
1686                         $empty = 1;
1687                 } else {
1688                         $empty = 0;
1689                 }
1691                 print format_log_line_html($line) . "<br/>\n";
1692         }
1694         if ($opts{'-final_empty_line'}) {
1695                 # end with single empty line
1696                 print "<br/>\n" unless $empty;
1697         }
1700 sub git_print_simplified_log {
1701         my $log = shift;
1702         my $remove_title = shift;
1704         git_print_log($log,
1705                 -final_empty_line=> 1,
1706                 -remove_title => $remove_title);
1709 # print tree entry (row of git_tree), but without encompassing <tr> element
1710 sub git_print_tree_entry {
1711         my ($t, $basedir, $hash_base, $have_blame) = @_;
1713         my %base_key = ();
1714         $base_key{hash_base} = $hash_base if defined $hash_base;
1716         # The format of a table row is: mode list link.  Where mode is
1717         # the mode of the entry, list is the name of the entry, an href,
1718         # and link is the action links of the entry.
1720         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1721         if ($t->{'type'} eq "blob") {
1722                 print "<td class=\"list\">" .
1723                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1724                                                file_name=>"$basedir$t->{'name'}", %base_key),
1725                                 -class => "list"}, esc_html($t->{'name'})) . "</td>\n";
1726                 print "<td class=\"link\">";
1727                 if ($have_blame) {
1728                         print $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1729                                                            file_name=>"$basedir$t->{'name'}", %base_key)},
1730                                             "blame");
1731                 }
1732                 if (defined $hash_base) {
1733                         if ($have_blame) {
1734                                 print " | ";
1735                         }
1736                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1737                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1738                                       "history");
1739                 }
1740                 print " | " .
1741                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
1742                                                file_name=>"$basedir$t->{'name'}")},
1743                                 "raw");
1744                 print "</td>\n";
1746         } elsif ($t->{'type'} eq "tree") {
1747                 print "<td class=\"list\">";
1748                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1749                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1750                               esc_html($t->{'name'}));
1751                 print "</td>\n";
1752                 print "<td class=\"link\">";
1753                 if (defined $hash_base) {
1754                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1755                                                      file_name=>"$basedir$t->{'name'}")},
1756                                       "history");
1757                 }
1758                 print "</td>\n";
1759         }
1762 ## ......................................................................
1763 ## functions printing large fragments of HTML
1765 sub git_difftree_body {
1766         my ($difftree, $hash, $parent) = @_;
1768         print "<div class=\"list_head\">\n";
1769         if ($#{$difftree} > 10) {
1770                 print(($#{$difftree} + 1) . " files changed:\n");
1771         }
1772         print "</div>\n";
1774         print "<table class=\"diff_tree\">\n";
1775         my $alternate = 1;
1776         my $patchno = 0;
1777         foreach my $line (@{$difftree}) {
1778                 my %diff = parse_difftree_raw_line($line);
1780                 if ($alternate) {
1781                         print "<tr class=\"dark\">\n";
1782                 } else {
1783                         print "<tr class=\"light\">\n";
1784                 }
1785                 $alternate ^= 1;
1787                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1788                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1789                 if ($diff{'to_mode'} ne ('0' x 6)) {
1790                         $to_mode_oct = oct $diff{'to_mode'};
1791                         if (S_ISREG($to_mode_oct)) { # only for regular file
1792                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1793                         }
1794                         $to_file_type = file_type($diff{'to_mode'});
1795                 }
1796                 if ($diff{'from_mode'} ne ('0' x 6)) {
1797                         $from_mode_oct = oct $diff{'from_mode'};
1798                         if (S_ISREG($to_mode_oct)) { # only for regular file
1799                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1800                         }
1801                         $from_file_type = file_type($diff{'from_mode'});
1802                 }
1804                 if ($diff{'status'} eq "A") { # created
1805                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1806                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1807                         $mode_chng   .= "]</span>";
1808                         print "<td>";
1809                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1810                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1811                                       -class => "list"}, esc_html($diff{'file'}));
1812                         print "</td>\n";
1813                         print "<td>$mode_chng</td>\n";
1814                         print "<td class=\"link\">";
1815                         if ($action eq 'commitdiff') {
1816                                 # link to patch
1817                                 $patchno++;
1818                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
1819                         }
1820                         print "</td>\n";
1822                 } elsif ($diff{'status'} eq "D") { # deleted
1823                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1824                         print "<td>";
1825                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1826                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1827                                        -class => "list"}, esc_html($diff{'file'}));
1828                         print "</td>\n";
1829                         print "<td>$mode_chng</td>\n";
1830                         print "<td class=\"link\">";
1831                         if ($action eq 'commitdiff') {
1832                                 # link to patch
1833                                 $patchno++;
1834                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
1835                                 print " | ";
1836                         }
1837                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1838                                                      file_name=>$diff{'file'})},
1839                                       "blame") . " | ";
1840                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1841                                                      file_name=>$diff{'file'})},
1842                                       "history");
1843                         print "</td>\n";
1845                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1846                         my $mode_chnge = "";
1847                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1848                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1849                                 if ($from_file_type != $to_file_type) {
1850                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1851                                 }
1852                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1853                                         if ($from_mode_str && $to_mode_str) {
1854                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1855                                         } elsif ($to_mode_str) {
1856                                                 $mode_chnge .= " mode: $to_mode_str";
1857                                         }
1858                                 }
1859                                 $mode_chnge .= "]</span>\n";
1860                         }
1861                         print "<td>";
1862                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1863                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1864                                       -class => "list"}, esc_html($diff{'file'}));
1865                         print "</td>\n";
1866                         print "<td>$mode_chnge</td>\n";
1867                         print "<td class=\"link\">";
1868                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1869                                 if ($action eq 'commitdiff') {
1870                                         # link to patch
1871                                         $patchno++;
1872                                         print $cgi->a({-href => "#patch$patchno"}, "patch");
1873                                 } else {
1874                                         print $cgi->a({-href => href(action=>"blobdiff",
1875                                                                      hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1876                                                                      hash_base=>$hash, hash_parent_base=>$parent,
1877                                                                      file_name=>$diff{'file'})},
1878                                                       "diff");
1879                                 }
1880                                 print " | ";
1881                         }
1882                         print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
1883                                                      file_name=>$diff{'file'})},
1884                                       "blame") . " | ";
1885                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
1886                                                      file_name=>$diff{'file'})},
1887                                       "history");
1888                         print "</td>\n";
1890                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1891                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1892                         my $nstatus = $status_name{$diff{'status'}};
1893                         my $mode_chng = "";
1894                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1895                                 # mode also for directories, so we cannot use $to_mode_str
1896                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1897                         }
1898                         print "<td>" .
1899                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1900                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1901                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1902                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1903                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1904                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1905                                       -class => "list"}, esc_html($diff{'from_file'})) .
1906                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1907                               "<td class=\"link\">";
1908                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1909                                 if ($action eq 'commitdiff') {
1910                                         # link to patch
1911                                         $patchno++;
1912                                         print $cgi->a({-href => "#patch$patchno"}, "patch");
1913                                 } else {
1914                                         print $cgi->a({-href => href(action=>"blobdiff",
1915                                                                      hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1916                                                                      hash_base=>$hash, hash_parent_base=>$parent,
1917                                                                      file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1918                                                       "diff");
1919                                 }
1920                                 print " | ";
1921                         }
1922                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1923                                                      file_name=>$diff{'from_file'})},
1924                                       "blame") . " | ";
1925                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1926                                                     file_name=>$diff{'from_file'})},
1927                                       "history");
1928                         print "</td>\n";
1930                 } # we should not encounter Unmerged (U) or Unknown (X) status
1931                 print "</tr>\n";
1932         }
1933         print "</table>\n";
1936 sub git_patchset_body {
1937         my ($fd, $difftree, $hash, $hash_parent) = @_;
1939         my $patch_idx = 0;
1940         my $in_header = 0;
1941         my $patch_found = 0;
1942         my $diffinfo;
1944         print "<div class=\"patchset\">\n";
1946         LINE:
1947         while (my $patch_line = <$fd>) {
1948                 chomp $patch_line;
1950                 if ($patch_line =~ m/^diff /) { # "git diff" header
1951                         # beginning of patch (in patchset)
1952                         if ($patch_found) {
1953                                 # close previous patch
1954                                 print "</div>\n"; # class="patch"
1955                         } else {
1956                                 # first patch in patchset
1957                                 $patch_found = 1;
1958                         }
1959                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1961                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1962                                 $diffinfo = $difftree->[$patch_idx];
1963                         } else {
1964                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1965                         }
1966                         $patch_idx++;
1968                         # for now, no extended header, hence we skip empty patches
1969                         # companion to  next LINE if $in_header;
1970                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1971                                 $in_header = 1;
1972                                 next LINE;
1973                         }
1975                         if ($diffinfo->{'status'} eq "A") { # added
1976                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1977                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1978                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1979                                               $diffinfo->{'to_id'}) . " (new)" .
1980                                       "</div>\n"; # class="diff_info"
1982                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1983                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1984                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1985                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1986                                               $diffinfo->{'from_id'}) . " (deleted)" .
1987                                       "</div>\n"; # class="diff_info"
1989                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1990                                  $diffinfo->{'status'} eq "C" || # copied
1991                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1992                                 print "<div class=\"diff_info\">" .
1993                                       file_type($diffinfo->{'from_mode'}) . ":" .
1994                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1995                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1996                                               $diffinfo->{'from_id'}) .
1997                                       " -> " .
1998                                       file_type($diffinfo->{'to_mode'}) . ":" .
1999                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2000                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
2001                                               $diffinfo->{'to_id'});
2002                                 print "</div>\n"; # class="diff_info"
2004                         } else { # modified, mode changed, ...
2005                                 print "<div class=\"diff_info\">" .
2006                                       file_type($diffinfo->{'from_mode'}) . ":" .
2007                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2008                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
2009                                               $diffinfo->{'from_id'}) .
2010                                       " -> " .
2011                                       file_type($diffinfo->{'to_mode'}) . ":" .
2012                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2013                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
2014                                               $diffinfo->{'to_id'});
2015                                 print "</div>\n"; # class="diff_info"
2016                         }
2018                         #print "<div class=\"diff extended_header\">\n";
2019                         $in_header = 1;
2020                         next LINE;
2021                 } # start of patch in patchset
2024                 if ($in_header && $patch_line =~ m/^---/) {
2025                         #print "</div>\n"; # class="diff extended_header"
2026                         $in_header = 0;
2028                         my $file = $diffinfo->{'from_file'};
2029                         $file  ||= $diffinfo->{'file'};
2030                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2031                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
2032                                         -class => "list"}, esc_html($file));
2033                         $patch_line =~ s|a/.*$|a/$file|g;
2034                         print "<div class=\"diff from_file\">$patch_line</div>\n";
2036                         $patch_line = <$fd>;
2037                         chomp $patch_line;
2039                         #$patch_line =~ m/^+++/;
2040                         $file    = $diffinfo->{'to_file'};
2041                         $file  ||= $diffinfo->{'file'};
2042                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2043                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
2044                                         -class => "list"}, esc_html($file));
2045                         $patch_line =~ s|b/.*|b/$file|g;
2046                         print "<div class=\"diff to_file\">$patch_line</div>\n";
2048                         next LINE;
2049                 }
2050                 next LINE if $in_header;
2052                 print format_diff_line($patch_line);
2053         }
2054         print "</div>\n" if $patch_found; # class="patch"
2056         print "</div>\n"; # class="patchset"
2059 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2061 sub git_shortlog_body {
2062         # uses global variable $project
2063         my ($revlist, $from, $to, $refs, $extra) = @_;
2065         $from = 0 unless defined $from;
2066         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2068         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2069         my $alternate = 1;
2070         for (my $i = $from; $i <= $to; $i++) {
2071                 my $commit = $revlist->[$i];
2072                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2073                 my $ref = format_ref_marker($refs, $commit);
2074                 my %co = parse_commit($commit);
2075                 if ($alternate) {
2076                         print "<tr class=\"dark\">\n";
2077                 } else {
2078                         print "<tr class=\"light\">\n";
2079                 }
2080                 $alternate ^= 1;
2081                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2082                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2083                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2084                       "<td>";
2085                 print format_subject_html($co{'title'}, $co{'title_short'},
2086                                           href(action=>"commit", hash=>$commit), $ref);
2087                 print "</td>\n" .
2088                       "<td class=\"link\">" .
2089                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2090                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2091                 if (gitweb_have_snapshot()) {
2092                         print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2093                 }
2094                 print "</td>\n" .
2095                       "</tr>\n";
2096         }
2097         if (defined $extra) {
2098                 print "<tr>\n" .
2099                       "<td colspan=\"4\">$extra</td>\n" .
2100                       "</tr>\n";
2101         }
2102         print "</table>\n";
2105 sub git_history_body {
2106         # Warning: assumes constant type (blob or tree) during history
2107         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2109         $from = 0 unless defined $from;
2110         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2112         print "<table class=\"history\" cellspacing=\"0\">\n";
2113         my $alternate = 1;
2114         for (my $i = $from; $i <= $to; $i++) {
2115                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2116                         next;
2117                 }
2119                 my $commit = $1;
2120                 my %co = parse_commit($commit);
2121                 if (!%co) {
2122                         next;
2123                 }
2125                 my $ref = format_ref_marker($refs, $commit);
2127                 if ($alternate) {
2128                         print "<tr class=\"dark\">\n";
2129                 } else {
2130                         print "<tr class=\"light\">\n";
2131                 }
2132                 $alternate ^= 1;
2133                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2134                       # shortlog uses      chop_str($co{'author_name'}, 10)
2135                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2136                       "<td>";
2137                 # originally git_history used chop_str($co{'title'}, 50)
2138                 print format_subject_html($co{'title'}, $co{'title_short'},
2139                                           href(action=>"commit", hash=>$commit), $ref);
2140                 print "</td>\n" .
2141                       "<td class=\"link\">" .
2142                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2143                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2145                 if ($ftype eq 'blob') {
2146                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2147                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2148                         if (defined $blob_current && defined $blob_parent &&
2149                                         $blob_current ne $blob_parent) {
2150                                 print " | " .
2151                                         $cgi->a({-href => href(action=>"blobdiff",
2152                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2153                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2154                                                                file_name=>$file_name)},
2155                                                 "diff to current");
2156                         }
2157                 }
2158                 print "</td>\n" .
2159                       "</tr>\n";
2160         }
2161         if (defined $extra) {
2162                 print "<tr>\n" .
2163                       "<td colspan=\"4\">$extra</td>\n" .
2164                       "</tr>\n";
2165         }
2166         print "</table>\n";
2169 sub git_tags_body {
2170         # uses global variable $project
2171         my ($taglist, $from, $to, $extra) = @_;
2172         $from = 0 unless defined $from;
2173         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2175         print "<table class=\"tags\" cellspacing=\"0\">\n";
2176         my $alternate = 1;
2177         for (my $i = $from; $i <= $to; $i++) {
2178                 my $entry = $taglist->[$i];
2179                 my %tag = %$entry;
2180                 my $comment_lines = $tag{'comment'};
2181                 my $comment = shift @$comment_lines;
2182                 my $comment_short;
2183                 if (defined $comment) {
2184                         $comment_short = chop_str($comment, 30, 5);
2185                 }
2186                 if ($alternate) {
2187                         print "<tr class=\"dark\">\n";
2188                 } else {
2189                         print "<tr class=\"light\">\n";
2190                 }
2191                 $alternate ^= 1;
2192                 print "<td><i>$tag{'age'}</i></td>\n" .
2193                       "<td>" .
2194                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2195                                -class => "list name"}, esc_html($tag{'name'})) .
2196                       "</td>\n" .
2197                       "<td>";
2198                 if (defined $comment) {
2199                         print format_subject_html($comment, $comment_short,
2200                                                   href(action=>"tag", hash=>$tag{'id'}));
2201                 }
2202                 print "</td>\n" .
2203                       "<td class=\"selflink\">";
2204                 if ($tag{'type'} eq "tag") {
2205                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2206                 } else {
2207                         print "&nbsp;";
2208                 }
2209                 print "</td>\n" .
2210                       "<td class=\"link\">" . " | " .
2211                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2212                 if ($tag{'reftype'} eq "commit") {
2213                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2214                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2215                 } elsif ($tag{'reftype'} eq "blob") {
2216                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2217                 }
2218                 print "</td>\n" .
2219                       "</tr>";
2220         }
2221         if (defined $extra) {
2222                 print "<tr>\n" .
2223                       "<td colspan=\"5\">$extra</td>\n" .
2224                       "</tr>\n";
2225         }
2226         print "</table>\n";
2229 sub git_heads_body {
2230         # uses global variable $project
2231         my ($headlist, $head, $from, $to, $extra) = @_;
2232         $from = 0 unless defined $from;
2233         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2235         print "<table class=\"heads\" cellspacing=\"0\">\n";
2236         my $alternate = 1;
2237         for (my $i = $from; $i <= $to; $i++) {
2238                 my $entry = $headlist->[$i];
2239                 my %tag = %$entry;
2240                 my $curr = $tag{'id'} eq $head;
2241                 if ($alternate) {
2242                         print "<tr class=\"dark\">\n";
2243                 } else {
2244                         print "<tr class=\"light\">\n";
2245                 }
2246                 $alternate ^= 1;
2247                 print "<td><i>$tag{'age'}</i></td>\n" .
2248                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2249                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2250                                -class => "list name"},esc_html($tag{'name'})) .
2251                       "</td>\n" .
2252                       "<td class=\"link\">" .
2253                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2254                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") . " | " .
2255                       $cgi->a({-href => href(action=>"tree", hash=>$tag{'name'}, hash_base=>$tag{'name'})}, "tree") .
2256                       "</td>\n" .
2257                       "</tr>";
2258         }
2259         if (defined $extra) {
2260                 print "<tr>\n" .
2261                       "<td colspan=\"3\">$extra</td>\n" .
2262                       "</tr>\n";
2263         }
2264         print "</table>\n";
2267 ## ======================================================================
2268 ## ======================================================================
2269 ## actions
2271 sub git_project_list {
2272         my $order = $cgi->param('o');
2273         if (defined $order && $order !~ m/project|descr|owner|age/) {
2274                 die_error(undef, "Unknown order parameter");
2275         }
2277         my @list = git_get_projects_list();
2278         my @projects;
2279         if (!@list) {
2280                 die_error(undef, "No projects found");
2281         }
2282         foreach my $pr (@list) {
2283                 my $head = git_get_head_hash($pr->{'path'});
2284                 if (!defined $head) {
2285                         next;
2286                 }
2287                 $git_dir = "$projectroot/$pr->{'path'}";
2288                 my %co = parse_commit($head);
2289                 if (!%co) {
2290                         next;
2291                 }
2292                 $pr->{'commit'} = \%co;
2293                 if (!defined $pr->{'descr'}) {
2294                         my $descr = git_get_project_description($pr->{'path'}) || "";
2295                         $pr->{'descr'} = chop_str($descr, 25, 5);
2296                 }
2297                 if (!defined $pr->{'owner'}) {
2298                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2299                 }
2300                 push @projects, $pr;
2301         }
2303         git_header_html();
2304         if (-f $home_text) {
2305                 print "<div class=\"index_include\">\n";
2306                 open (my $fd, $home_text);
2307                 print <$fd>;
2308                 close $fd;
2309                 print "</div>\n";
2310         }
2311         print "<table class=\"project_list\">\n" .
2312               "<tr>\n";
2313         $order ||= "project";
2314         if ($order eq "project") {
2315                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2316                 print "<th>Project</th>\n";
2317         } else {
2318                 print "<th>" .
2319                       $cgi->a({-href => href(project=>undef, order=>'project'),
2320                                -class => "header"}, "Project") .
2321                       "</th>\n";
2322         }
2323         if ($order eq "descr") {
2324                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2325                 print "<th>Description</th>\n";
2326         } else {
2327                 print "<th>" .
2328                       $cgi->a({-href => href(project=>undef, order=>'descr'),
2329                                -class => "header"}, "Description") .
2330                       "</th>\n";
2331         }
2332         if ($order eq "owner") {
2333                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2334                 print "<th>Owner</th>\n";
2335         } else {
2336                 print "<th>" .
2337                       $cgi->a({-href => href(project=>undef, order=>'owner'),
2338                                -class => "header"}, "Owner") .
2339                       "</th>\n";
2340         }
2341         if ($order eq "age") {
2342                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2343                 print "<th>Last Change</th>\n";
2344         } else {
2345                 print "<th>" .
2346                       $cgi->a({-href => href(project=>undef, order=>'age'),
2347                                -class => "header"}, "Last Change") .
2348                       "</th>\n";
2349         }
2350         print "<th></th>\n" .
2351               "</tr>\n";
2352         my $alternate = 1;
2353         foreach my $pr (@projects) {
2354                 if ($alternate) {
2355                         print "<tr class=\"dark\">\n";
2356                 } else {
2357                         print "<tr class=\"light\">\n";
2358                 }
2359                 $alternate ^= 1;
2360                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2361                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2362                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2363                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2364                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2365                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2366                       "<td class=\"link\">" .
2367                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2368                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2369                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2370                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2371                       "</td>\n" .
2372                       "</tr>\n";
2373         }
2374         print "</table>\n";
2375         git_footer_html();
2378 sub git_project_index {
2379         my @projects = git_get_projects_list();
2381         print $cgi->header(
2382                 -type => 'text/plain',
2383                 -charset => 'utf-8',
2384                 -content_disposition => 'inline; filename="index.aux"');
2386         foreach my $pr (@projects) {
2387                 if (!exists $pr->{'owner'}) {
2388                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2389                 }
2391                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2392                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2393                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2394                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2395                 $path  =~ s/ /\+/g;
2396                 $owner =~ s/ /\+/g;
2398                 print "$path $owner\n";
2399         }
2402 sub git_summary {
2403         my $descr = git_get_project_description($project) || "none";
2404         my $head = git_get_head_hash($project);
2405         my %co = parse_commit($head);
2406         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2408         my $owner = git_get_project_owner($project);
2410         my ($reflist, $refs) = git_get_refs_list();
2412         my @taglist;
2413         my @headlist;
2414         foreach my $ref (@$reflist) {
2415                 if ($ref->{'name'} =~ s!^heads/!!) {
2416                         push @headlist, $ref;
2417                 } else {
2418                         $ref->{'name'} =~ s!^tags/!!;
2419                         push @taglist, $ref;
2420                 }
2421         }
2423         git_header_html();
2424         git_print_page_nav('summary','', $head);
2426         print "<div class=\"title\">&nbsp;</div>\n";
2427         print "<table cellspacing=\"0\">\n" .
2428               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2429               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2430               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2431         # use per project git URL list in $projectroot/$project/cloneurl
2432         # or make project git URL from git base URL and project name
2433         my $url_tag = "URL";
2434         my @url_list = git_get_project_url_list($project);
2435         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2436         foreach my $git_url (@url_list) {
2437                 next unless $git_url;
2438                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2439                 $url_tag = "";
2440         }
2441         print "</table>\n";
2443         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2444                 git_get_head_hash($project)
2445                 or die_error(undef, "Open git-rev-list failed");
2446         my @revlist = map { chomp; $_ } <$fd>;
2447         close $fd;
2448         git_print_header_div('shortlog');
2449         git_shortlog_body(\@revlist, 0, 15, $refs,
2450                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2452         if (@taglist) {
2453                 git_print_header_div('tags');
2454                 git_tags_body(\@taglist, 0, 15,
2455                               $cgi->a({-href => href(action=>"tags")}, "..."));
2456         }
2458         if (@headlist) {
2459                 git_print_header_div('heads');
2460                 git_heads_body(\@headlist, $head, 0, 15,
2461                                $cgi->a({-href => href(action=>"heads")}, "..."));
2462         }
2464         git_footer_html();
2467 sub git_tag {
2468         my $head = git_get_head_hash($project);
2469         git_header_html();
2470         git_print_page_nav('','', $head,undef,$head);
2471         my %tag = parse_tag($hash);
2472         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2473         print "<div class=\"title_text\">\n" .
2474               "<table cellspacing=\"0\">\n" .
2475               "<tr>\n" .
2476               "<td>object</td>\n" .
2477               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2478                                $tag{'object'}) . "</td>\n" .
2479               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2480                                               $tag{'type'}) . "</td>\n" .
2481               "</tr>\n";
2482         if (defined($tag{'author'})) {
2483                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2484                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2485                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2486                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2487                         "</td></tr>\n";
2488         }
2489         print "</table>\n\n" .
2490               "</div>\n";
2491         print "<div class=\"page_body\">";
2492         my $comment = $tag{'comment'};
2493         foreach my $line (@$comment) {
2494                 print esc_html($line) . "<br/>\n";
2495         }
2496         print "</div>\n";
2497         git_footer_html();
2500 sub git_blame2 {
2501         my $fd;
2502         my $ftype;
2504         my ($have_blame) = gitweb_check_feature('blame');
2505         if (!$have_blame) {
2506                 die_error('403 Permission denied', "Permission denied");
2507         }
2508         die_error('404 Not Found', "File name not defined") if (!$file_name);
2509         $hash_base ||= git_get_head_hash($project);
2510         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2511         my %co = parse_commit($hash_base)
2512                 or die_error(undef, "Reading commit failed");
2513         if (!defined $hash) {
2514                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2515                         or die_error(undef, "Error looking up file");
2516         }
2517         $ftype = git_get_type($hash);
2518         if ($ftype !~ "blob") {
2519                 die_error("400 Bad Request", "Object is not a blob");
2520         }
2521         open ($fd, "-|", git_cmd(), "blame", '-l', '--', $file_name, $hash_base)
2522                 or die_error(undef, "Open git-blame failed");
2523         git_header_html();
2524         my $formats_nav =
2525                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2526                         "blob") .
2527                 " | " .
2528                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2529                         "history") .
2530                 " | " .
2531                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2532                         "HEAD");
2533         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2534         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2535         git_print_page_path($file_name, $ftype, $hash_base);
2536         my @rev_color = (qw(light2 dark2));
2537         my $num_colors = scalar(@rev_color);
2538         my $current_color = 0;
2539         my $last_rev;
2540         print <<HTML;
2541 <div class="page_body">
2542 <table class="blame">
2543 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2544 HTML
2545         while (<$fd>) {
2546                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2547                 my $full_rev = $1;
2548                 my $rev = substr($full_rev, 0, 8);
2549                 my $lineno = $2;
2550                 my $data = $3;
2552                 if (!defined $last_rev) {
2553                         $last_rev = $full_rev;
2554                 } elsif ($last_rev ne $full_rev) {
2555                         $last_rev = $full_rev;
2556                         $current_color = ++$current_color % $num_colors;
2557                 }
2558                 print "<tr class=\"$rev_color[$current_color]\">\n";
2559                 print "<td class=\"sha1\">" .
2560                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2561                                 esc_html($rev)) . "</td>\n";
2562                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2563                       esc_html($lineno) . "</a></td>\n";
2564                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2565                 print "</tr>\n";
2566         }
2567         print "</table>\n";
2568         print "</div>";
2569         close $fd
2570                 or print "Reading blob failed\n";
2571         git_footer_html();
2574 sub git_blame {
2575         my $fd;
2577         my ($have_blame) = gitweb_check_feature('blame');
2578         if (!$have_blame) {
2579                 die_error('403 Permission denied', "Permission denied");
2580         }
2581         die_error('404 Not Found', "File name not defined") if (!$file_name);
2582         $hash_base ||= git_get_head_hash($project);
2583         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2584         my %co = parse_commit($hash_base)
2585                 or die_error(undef, "Reading commit failed");
2586         if (!defined $hash) {
2587                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2588                         or die_error(undef, "Error lookup file");
2589         }
2590         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2591                 or die_error(undef, "Open git-annotate failed");
2592         git_header_html();
2593         my $formats_nav =
2594                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2595                         "blob") .
2596                 " | " .
2597                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2598                         "history") .
2599                 " | " .
2600                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2601                         "HEAD");
2602         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2603         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2604         git_print_page_path($file_name, 'blob', $hash_base);
2605         print "<div class=\"page_body\">\n";
2606         print <<HTML;
2607 <table class="blame">
2608   <tr>
2609     <th>Commit</th>
2610     <th>Age</th>
2611     <th>Author</th>
2612     <th>Line</th>
2613     <th>Data</th>
2614   </tr>
2615 HTML
2616         my @line_class = (qw(light dark));
2617         my $line_class_len = scalar (@line_class);
2618         my $line_class_num = $#line_class;
2619         while (my $line = <$fd>) {
2620                 my $long_rev;
2621                 my $short_rev;
2622                 my $author;
2623                 my $time;
2624                 my $lineno;
2625                 my $data;
2626                 my $age;
2627                 my $age_str;
2628                 my $age_class;
2630                 chomp $line;
2631                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2633                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2634                         $long_rev = $1;
2635                         $author   = $2;
2636                         $time     = $3;
2637                         $lineno   = $4;
2638                         $data     = $5;
2639                 } else {
2640                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2641                         next;
2642                 }
2643                 $short_rev  = substr ($long_rev, 0, 8);
2644                 $age        = time () - $time;
2645                 $age_str    = age_string ($age);
2646                 $age_str    =~ s/ /&nbsp;/g;
2647                 $age_class  = age_class($age);
2648                 $author     = esc_html ($author);
2649                 $author     =~ s/ /&nbsp;/g;
2651                 $data = untabify($data);
2652                 $data = esc_html ($data);
2654                 print <<HTML;
2655   <tr class="$line_class[$line_class_num]">
2656     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2657     <td class="$age_class">$age_str</td>
2658     <td>$author</td>
2659     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2660     <td class="pre">$data</td>
2661   </tr>
2662 HTML
2663         } # while (my $line = <$fd>)
2664         print "</table>\n\n";
2665         close $fd
2666                 or print "Reading blob failed.\n";
2667         print "</div>";
2668         git_footer_html();
2671 sub git_tags {
2672         my $head = git_get_head_hash($project);
2673         git_header_html();
2674         git_print_page_nav('','', $head,undef,$head);
2675         git_print_header_div('summary', $project);
2677         my ($taglist) = git_get_refs_list("tags");
2678         if (@$taglist) {
2679                 git_tags_body($taglist);
2680         }
2681         git_footer_html();
2684 sub git_heads {
2685         my $head = git_get_head_hash($project);
2686         git_header_html();
2687         git_print_page_nav('','', $head,undef,$head);
2688         git_print_header_div('summary', $project);
2690         my ($headlist) = git_get_refs_list("heads");
2691         if (@$headlist) {
2692                 git_heads_body($headlist, $head);
2693         }
2694         git_footer_html();
2697 sub git_blob_plain {
2698         my $expires;
2700         if (!defined $hash) {
2701                 if (defined $file_name) {
2702                         my $base = $hash_base || git_get_head_hash($project);
2703                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2704                                 or die_error(undef, "Error lookup file");
2705                 } else {
2706                         die_error(undef, "No file name defined");
2707                 }
2708         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2709                 # blobs defined by non-textual hash id's can be cached
2710                 $expires = "+1d";
2711         }
2713         my $type = shift;
2714         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2715                 or die_error(undef, "Couldn't cat $file_name, $hash");
2717         $type ||= blob_mimetype($fd, $file_name);
2719         # save as filename, even when no $file_name is given
2720         my $save_as = "$hash";
2721         if (defined $file_name) {
2722                 $save_as = $file_name;
2723         } elsif ($type =~ m/^text\//) {
2724                 $save_as .= '.txt';
2725         }
2727         print $cgi->header(
2728                 -type => "$type",
2729                 -expires=>$expires,
2730                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
2731         undef $/;
2732         binmode STDOUT, ':raw';
2733         print <$fd>;
2734         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2735         $/ = "\n";
2736         close $fd;
2739 sub git_blob {
2740         my $expires;
2742         if (!defined $hash) {
2743                 if (defined $file_name) {
2744                         my $base = $hash_base || git_get_head_hash($project);
2745                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2746                                 or die_error(undef, "Error lookup file");
2747                 } else {
2748                         die_error(undef, "No file name defined");
2749                 }
2750         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2751                 # blobs defined by non-textual hash id's can be cached
2752                 $expires = "+1d";
2753         }
2755         my ($have_blame) = gitweb_check_feature('blame');
2756         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2757                 or die_error(undef, "Couldn't cat $file_name, $hash");
2758         my $mimetype = blob_mimetype($fd, $file_name);
2759         if ($mimetype !~ m/^text\//) {
2760                 close $fd;
2761                 return git_blob_plain($mimetype);
2762         }
2763         git_header_html(undef, $expires);
2764         my $formats_nav = '';
2765         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2766                 if (defined $file_name) {
2767                         if ($have_blame) {
2768                                 $formats_nav .=
2769                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2770                                                                hash=>$hash, file_name=>$file_name)},
2771                                                 "blame") .
2772                                         " | ";
2773                         }
2774                         $formats_nav .=
2775                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2776                                                        hash=>$hash, file_name=>$file_name)},
2777                                         "history") .
2778                                 " | " .
2779                                 $cgi->a({-href => href(action=>"blob_plain",
2780                                                        hash=>$hash, file_name=>$file_name)},
2781                                         "raw") .
2782                                 " | " .
2783                                 $cgi->a({-href => href(action=>"blob",
2784                                                        hash_base=>"HEAD", file_name=>$file_name)},
2785                                         "HEAD");
2786                 } else {
2787                         $formats_nav .=
2788                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
2789                 }
2790                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2791                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2792         } else {
2793                 print "<div class=\"page_nav\">\n" .
2794                       "<br/><br/></div>\n" .
2795                       "<div class=\"title\">$hash</div>\n";
2796         }
2797         git_print_page_path($file_name, "blob", $hash_base);
2798         print "<div class=\"page_body\">\n";
2799         my $nr;
2800         while (my $line = <$fd>) {
2801                 chomp $line;
2802                 $nr++;
2803                 $line = untabify($line);
2804                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2805                        $nr, $nr, $nr, esc_html($line);
2806         }
2807         close $fd
2808                 or print "Reading blob failed.\n";
2809         print "</div>";
2810         git_footer_html();
2813 sub git_tree {
2814         my $have_snapshot = gitweb_have_snapshot();
2816         if (!defined $hash_base) {
2817                 $hash_base = "HEAD";
2818         }
2819         if (!defined $hash) {
2820                 if (defined $file_name) {
2821                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
2822                 } else {
2823                         $hash = $hash_base;
2824                 }
2825         }
2826         $/ = "\0";
2827         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2828                 or die_error(undef, "Open git-ls-tree failed");
2829         my @entries = map { chomp; $_ } <$fd>;
2830         close $fd or die_error(undef, "Reading tree failed");
2831         $/ = "\n";
2833         my $refs = git_get_references();
2834         my $ref = format_ref_marker($refs, $hash_base);
2835         git_header_html();
2836         my $basedir = '';
2837         my ($have_blame) = gitweb_check_feature('blame');
2838         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2839                 my @views_nav = ();
2840                 if (defined $file_name) {
2841                         push @views_nav,
2842                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2843                                                        hash=>$hash, file_name=>$file_name)},
2844                                         "history"),
2845                                 $cgi->a({-href => href(action=>"tree",
2846                                                        hash_base=>"HEAD", file_name=>$file_name)},
2847                                         "HEAD"),
2848                 }
2849                 if ($have_snapshot) {
2850                         # FIXME: Should be available when we have no hash base as well.
2851                         push @views_nav,
2852                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
2853                                         "snapshot");
2854                 }
2855                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
2856                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2857         } else {
2858                 undef $hash_base;
2859                 print "<div class=\"page_nav\">\n";
2860                 print "<br/><br/></div>\n";
2861                 print "<div class=\"title\">$hash</div>\n";
2862         }
2863         if (defined $file_name) {
2864                 $basedir = $file_name;
2865                 if ($basedir ne '' && substr($basedir, -1) ne '/') {
2866                         $basedir .= '/';
2867                 }
2868         }
2869         git_print_page_path($file_name, 'tree', $hash_base);
2870         print "<div class=\"page_body\">\n";
2871         print "<table cellspacing=\"0\">\n";
2872         my $alternate = 1;
2873         # '..' (top directory) link if possible
2874         if (defined $hash_base &&
2875             defined $file_name && $file_name =~ m![^/]+$!) {
2876                 if ($alternate) {
2877                         print "<tr class=\"dark\">\n";
2878                 } else {
2879                         print "<tr class=\"light\">\n";
2880                 }
2881                 $alternate ^= 1;
2883                 my $up = $file_name;
2884                 $up =~ s!/?[^/]+$!!;
2885                 undef $up unless $up;
2886                 # based on git_print_tree_entry
2887                 print '<td class="mode">' . mode_str('040000') . "</td>\n";
2888                 print '<td class="list">';
2889                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
2890                                              file_name=>$up)},
2891                               "..");
2892                 print "</td>\n";
2893                 print "<td class=\"link\"></td>\n";
2895                 print "</tr>\n";
2896         }
2897         foreach my $line (@entries) {
2898                 my %t = parse_ls_tree_line($line, -z => 1);
2900                 if ($alternate) {
2901                         print "<tr class=\"dark\">\n";
2902                 } else {
2903                         print "<tr class=\"light\">\n";
2904                 }
2905                 $alternate ^= 1;
2907                 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
2909                 print "</tr>\n";
2910         }
2911         print "</table>\n" .
2912               "</div>";
2913         git_footer_html();
2916 sub git_snapshot {
2917         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2918         my $have_snapshot = (defined $ctype && defined $suffix);
2919         if (!$have_snapshot) {
2920                 die_error('403 Permission denied', "Permission denied");
2921         }
2923         if (!defined $hash) {
2924                 $hash = git_get_head_hash($project);
2925         }
2927         my $filename = basename($project) . "-$hash.tar.$suffix";
2929         print $cgi->header(
2930                 -type => 'application/x-tar',
2931                 -content_encoding => $ctype,
2932                 -content_disposition => 'inline; filename="' . "$filename" . '"',
2933                 -status => '200 OK');
2935         my $git = git_cmd_str();
2936         my $name = $project;
2937         $name =~ s/\047/\047\\\047\047/g;
2938         open my $fd, "-|",
2939         "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
2940                 or die_error(undef, "Execute git-tar-tree failed.");
2941         binmode STDOUT, ':raw';
2942         print <$fd>;
2943         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2944         close $fd;
2948 sub git_log {
2949         my $head = git_get_head_hash($project);
2950         if (!defined $hash) {
2951                 $hash = $head;
2952         }
2953         if (!defined $page) {
2954                 $page = 0;
2955         }
2956         my $refs = git_get_references();
2958         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2959         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2960                 or die_error(undef, "Open git-rev-list failed");
2961         my @revlist = map { chomp; $_ } <$fd>;
2962         close $fd;
2964         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2966         git_header_html();
2967         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2969         if (!@revlist) {
2970                 my %co = parse_commit($hash);
2972                 git_print_header_div('summary', $project);
2973                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2974         }
2975         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2976                 my $commit = $revlist[$i];
2977                 my $ref = format_ref_marker($refs, $commit);
2978                 my %co = parse_commit($commit);
2979                 next if !%co;
2980                 my %ad = parse_date($co{'author_epoch'});
2981                 git_print_header_div('commit',
2982                                "<span class=\"age\">$co{'age_string'}</span>" .
2983                                esc_html($co{'title'}) . $ref,
2984                                $commit);
2985                 print "<div class=\"title_text\">\n" .
2986                       "<div class=\"log_link\">\n" .
2987                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2988                       " | " .
2989                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2990                       " | " .
2991                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
2992                       "<br/>\n" .
2993                       "</div>\n" .
2994                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2995                       "</div>\n";
2997                 print "<div class=\"log_body\">\n";
2998                 git_print_simplified_log($co{'comment'});
2999                 print "</div>\n";
3000         }
3001         git_footer_html();
3004 sub git_commit {
3005         my %co = parse_commit($hash);
3006         if (!%co) {
3007                 die_error(undef, "Unknown commit object");
3008         }
3009         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3010         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
3012         my $parent = $co{'parent'};
3013         if (!defined $parent) {
3014                 $parent = "--root";
3015         }
3016         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
3017                 or die_error(undef, "Open git-diff-tree failed");
3018         my @difftree = map { chomp; $_ } <$fd>;
3019         close $fd or die_error(undef, "Reading git-diff-tree failed");
3021         # non-textual hash id's can be cached
3022         my $expires;
3023         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3024                 $expires = "+1d";
3025         }
3026         my $refs = git_get_references();
3027         my $ref = format_ref_marker($refs, $co{'id'});
3029         my $have_snapshot = gitweb_have_snapshot();
3031         my @views_nav = ();
3032         if (defined $file_name && defined $co{'parent'}) {
3033                 push @views_nav,
3034                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
3035                                 "blame");
3036         }
3037         git_header_html(undef, $expires);
3038         git_print_page_nav('commit', '',
3039                            $hash, $co{'tree'}, $hash,
3040                            join (' | ', @views_nav));
3042         if (defined $co{'parent'}) {
3043                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3044         } else {
3045                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3046         }
3047         print "<div class=\"title_text\">\n" .
3048               "<table cellspacing=\"0\">\n";
3049         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3050               "<tr>" .
3051               "<td></td><td> $ad{'rfc2822'}";
3052         if ($ad{'hour_local'} < 6) {
3053                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3054                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3055         } else {
3056                 printf(" (%02d:%02d %s)",
3057                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3058         }
3059         print "</td>" .
3060               "</tr>\n";
3061         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3062         print "<tr><td></td><td> $cd{'rfc2822'}" .
3063               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3064               "</td></tr>\n";
3065         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3066         print "<tr>" .
3067               "<td>tree</td>" .
3068               "<td class=\"sha1\">" .
3069               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3070                        class => "list"}, $co{'tree'}) .
3071               "</td>" .
3072               "<td class=\"link\">" .
3073               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3074                       "tree");
3075         if ($have_snapshot) {
3076                 print " | " .
3077                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3078         }
3079         print "</td>" .
3080               "</tr>\n";
3081         my $parents = $co{'parents'};
3082         foreach my $par (@$parents) {
3083                 print "<tr>" .
3084                       "<td>parent</td>" .
3085                       "<td class=\"sha1\">" .
3086                       $cgi->a({-href => href(action=>"commit", hash=>$par),
3087                                class => "list"}, $par) .
3088                       "</td>" .
3089                       "<td class=\"link\">" .
3090                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3091                       " | " .
3092                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3093                       "</td>" .
3094                       "</tr>\n";
3095         }
3096         print "</table>".
3097               "</div>\n";
3099         print "<div class=\"page_body\">\n";
3100         git_print_log($co{'comment'});
3101         print "</div>\n";
3103         git_difftree_body(\@difftree, $hash, $parent);
3105         git_footer_html();
3108 sub git_blobdiff {
3109         my $format = shift || 'html';
3111         my $fd;
3112         my @difftree;
3113         my %diffinfo;
3114         my $expires;
3116         # preparing $fd and %diffinfo for git_patchset_body
3117         # new style URI
3118         if (defined $hash_base && defined $hash_parent_base) {
3119                 if (defined $file_name) {
3120                         # read raw output
3121                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
3122                                 "--", $file_name
3123                                 or die_error(undef, "Open git-diff-tree failed");
3124                         @difftree = map { chomp; $_ } <$fd>;
3125                         close $fd
3126                                 or die_error(undef, "Reading git-diff-tree failed");
3127                         @difftree
3128                                 or die_error('404 Not Found', "Blob diff not found");
3130                 } elsif (defined $hash &&
3131                          $hash =~ /[0-9a-fA-F]{40}/) {
3132                         # try to find filename from $hash
3134                         # read filtered raw output
3135                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
3136                                 or die_error(undef, "Open git-diff-tree failed");
3137                         @difftree =
3138                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3139                                 # $hash == to_id
3140                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3141                                 map { chomp; $_ } <$fd>;
3142                         close $fd
3143                                 or die_error(undef, "Reading git-diff-tree failed");
3144                         @difftree
3145                                 or die_error('404 Not Found', "Blob diff not found");
3147                 } else {
3148                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3149                 }
3151                 if (@difftree > 1) {
3152                         die_error('404 Not Found', "Ambiguous blob diff specification");
3153                 }
3155                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3156                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3157                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3159                 $hash_parent ||= $diffinfo{'from_id'};
3160                 $hash        ||= $diffinfo{'to_id'};
3162                 # non-textual hash id's can be cached
3163                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3164                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3165                         $expires = '+1d';
3166                 }
3168                 # open patch output
3169                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3170                         '-p', $hash_parent_base, $hash_base,
3171                         "--", $file_name
3172                         or die_error(undef, "Open git-diff-tree failed");
3173         }
3175         # old/legacy style URI
3176         if (!%diffinfo && # if new style URI failed
3177             defined $hash && defined $hash_parent) {
3178                 # fake git-diff-tree raw output
3179                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3180                 $diffinfo{'from_id'} = $hash_parent;
3181                 $diffinfo{'to_id'}   = $hash;
3182                 if (defined $file_name) {
3183                         if (defined $file_parent) {
3184                                 $diffinfo{'status'} = '2';
3185                                 $diffinfo{'from_file'} = $file_parent;
3186                                 $diffinfo{'to_file'}   = $file_name;
3187                         } else { # assume not renamed
3188                                 $diffinfo{'status'} = '1';
3189                                 $diffinfo{'from_file'} = $file_name;
3190                                 $diffinfo{'to_file'}   = $file_name;
3191                         }
3192                 } else { # no filename given
3193                         $diffinfo{'status'} = '2';
3194                         $diffinfo{'from_file'} = $hash_parent;
3195                         $diffinfo{'to_file'}   = $hash;
3196                 }
3198                 # non-textual hash id's can be cached
3199                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3200                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3201                         $expires = '+1d';
3202                 }
3204                 # open patch output
3205                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3206                         or die_error(undef, "Open git-diff failed");
3207         } else  {
3208                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3209                         unless %diffinfo;
3210         }
3212         # header
3213         if ($format eq 'html') {
3214                 my $formats_nav =
3215                         $cgi->a({-href => href(action=>"blobdiff_plain",
3216                                                hash=>$hash, hash_parent=>$hash_parent,
3217                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3218                                                file_name=>$file_name, file_parent=>$file_parent)},
3219                                 "raw");
3220                 git_header_html(undef, $expires);
3221                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3222                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3223                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3224                 } else {
3225                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3226                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3227                 }
3228                 if (defined $file_name) {
3229                         git_print_page_path($file_name, "blob", $hash_base);
3230                 } else {
3231                         print "<div class=\"page_path\"></div>\n";
3232                 }
3234         } elsif ($format eq 'plain') {
3235                 print $cgi->header(
3236                         -type => 'text/plain',
3237                         -charset => 'utf-8',
3238                         -expires => $expires,
3239                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
3241                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3243         } else {
3244                 die_error(undef, "Unknown blobdiff format");
3245         }
3247         # patch
3248         if ($format eq 'html') {
3249                 print "<div class=\"page_body\">\n";
3251                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3252                 close $fd;
3254                 print "</div>\n"; # class="page_body"
3255                 git_footer_html();
3257         } else {
3258                 while (my $line = <$fd>) {
3259                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_html($diffinfo{'from_file'})!eg;
3260                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_html($diffinfo{'to_file'})!eg;
3262                         print $line;
3264                         last if $line =~ m!^\+\+\+!;
3265                 }
3266                 local $/ = undef;
3267                 print <$fd>;
3268                 close $fd;
3269         }
3272 sub git_blobdiff_plain {
3273         git_blobdiff('plain');
3276 sub git_commitdiff {
3277         my $format = shift || 'html';
3278         my %co = parse_commit($hash);
3279         if (!%co) {
3280                 die_error(undef, "Unknown commit object");
3281         }
3282         if (!defined $hash_parent) {
3283                 $hash_parent = $co{'parent'} || '--root';
3284         }
3286         # read commitdiff
3287         my $fd;
3288         my @difftree;
3289         if ($format eq 'html') {
3290                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3291                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3292                         or die_error(undef, "Open git-diff-tree failed");
3294                 while (chomp(my $line = <$fd>)) {
3295                         # empty line ends raw part of diff-tree output
3296                         last unless $line;
3297                         push @difftree, $line;
3298                 }
3300         } elsif ($format eq 'plain') {
3301                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3302                         '-p', $hash_parent, $hash
3303                         or die_error(undef, "Open git-diff-tree failed");
3305         } else {
3306                 die_error(undef, "Unknown commitdiff format");
3307         }
3309         # non-textual hash id's can be cached
3310         my $expires;
3311         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3312                 $expires = "+1d";
3313         }
3315         # write commit message
3316         if ($format eq 'html') {
3317                 my $refs = git_get_references();
3318                 my $ref = format_ref_marker($refs, $co{'id'});
3319                 my $formats_nav =
3320                         $cgi->a({-href => href(action=>"commitdiff_plain",
3321                                                hash=>$hash, hash_parent=>$hash_parent)},
3322                                 "raw");
3324                 git_header_html(undef, $expires);
3325                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3326                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3327                 git_print_authorship(\%co);
3328                 print "<div class=\"page_body\">\n";
3329                 print "<div class=\"log\">\n";
3330                 git_print_simplified_log($co{'comment'}, 1); # skip title
3331                 print "</div>\n"; # class="log"
3333         } elsif ($format eq 'plain') {
3334                 my $refs = git_get_references("tags");
3335                 my $tagname = git_get_rev_name_tags($hash);
3336                 my $filename = basename($project) . "-$hash.patch";
3338                 print $cgi->header(
3339                         -type => 'text/plain',
3340                         -charset => 'utf-8',
3341                         -expires => $expires,
3342                         -content_disposition => 'inline; filename="' . "$filename" . '"');
3343                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3344                 print <<TEXT;
3345 From: $co{'author'}
3346 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3347 Subject: $co{'title'}
3348 TEXT
3349                 print "X-Git-Tag: $tagname\n" if $tagname;
3350                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3352                 foreach my $line (@{$co{'comment'}}) {
3353                         print "$line\n";
3354                 }
3355                 print "---\n\n";
3356         }
3358         # write patch
3359         if ($format eq 'html') {
3360                 git_difftree_body(\@difftree, $hash, $hash_parent);
3361                 print "<br/>\n";
3363                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3364                 close $fd;
3365                 print "</div>\n"; # class="page_body"
3366                 git_footer_html();
3368         } elsif ($format eq 'plain') {
3369                 local $/ = undef;
3370                 print <$fd>;
3371                 close $fd
3372                         or print "Reading git-diff-tree failed\n";
3373         }
3376 sub git_commitdiff_plain {
3377         git_commitdiff('plain');
3380 sub git_history {
3381         if (!defined $hash_base) {
3382                 $hash_base = git_get_head_hash($project);
3383         }
3384         if (!defined $page) {
3385                 $page = 0;
3386         }
3387         my $ftype;
3388         my %co = parse_commit($hash_base);
3389         if (!%co) {
3390                 die_error(undef, "Unknown commit object");
3391         }
3393         my $refs = git_get_references();
3394         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3396         if (!defined $hash && defined $file_name) {
3397                 $hash = git_get_hash_by_path($hash_base, $file_name);
3398         }
3399         if (defined $hash) {
3400                 $ftype = git_get_type($hash);
3401         }
3403         open my $fd, "-|",
3404                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3405                         or die_error(undef, "Open git-rev-list-failed");
3406         my @revlist = map { chomp; $_ } <$fd>;
3407         close $fd
3408                 or die_error(undef, "Reading git-rev-list failed");
3410         my $paging_nav = '';
3411         if ($page > 0) {
3412                 $paging_nav .=
3413                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3414                                                file_name=>$file_name)},
3415                                 "first");
3416                 $paging_nav .= " &sdot; " .
3417                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3418                                                file_name=>$file_name, page=>$page-1),
3419                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3420         } else {
3421                 $paging_nav .= "first";
3422                 $paging_nav .= " &sdot; prev";
3423         }
3424         if ($#revlist >= (100 * ($page+1)-1)) {
3425                 $paging_nav .= " &sdot; " .
3426                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3427                                                file_name=>$file_name, page=>$page+1),
3428                                  -accesskey => "n", -title => "Alt-n"}, "next");
3429         } else {
3430                 $paging_nav .= " &sdot; next";
3431         }
3432         my $next_link = '';
3433         if ($#revlist >= (100 * ($page+1)-1)) {
3434                 $next_link =
3435                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3436                                                file_name=>$file_name, page=>$page+1),
3437                                  -title => "Alt-n"}, "next");
3438         }
3440         git_header_html();
3441         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3442         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3443         git_print_page_path($file_name, $ftype, $hash_base);
3445         git_history_body(\@revlist, ($page * 100), $#revlist,
3446                          $refs, $hash_base, $ftype, $next_link);
3448         git_footer_html();
3451 sub git_search {
3452         if (!defined $searchtext) {
3453                 die_error(undef, "Text field empty");
3454         }
3455         if (!defined $hash) {
3456                 $hash = git_get_head_hash($project);
3457         }
3458         my %co = parse_commit($hash);
3459         if (!%co) {
3460                 die_error(undef, "Unknown commit object");
3461         }
3463         my $commit_search = 1;
3464         my $author_search = 0;
3465         my $committer_search = 0;
3466         my $pickaxe_search = 0;
3467         if ($searchtext =~ s/^author\\://i) {
3468                 $author_search = 1;
3469         } elsif ($searchtext =~ s/^committer\\://i) {
3470                 $committer_search = 1;
3471         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3472                 $commit_search = 0;
3473                 $pickaxe_search = 1;
3475                 # pickaxe may take all resources of your box and run for several minutes
3476                 # with every query - so decide by yourself how public you make this feature
3477                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3478                 if (!$have_pickaxe) {
3479                         die_error('403 Permission denied', "Permission denied");
3480                 }
3481         }
3482         git_header_html();
3483         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3484         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3486         print "<table cellspacing=\"0\">\n";
3487         my $alternate = 1;
3488         if ($commit_search) {
3489                 $/ = "\0";
3490                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3491                 while (my $commit_text = <$fd>) {
3492                         if (!grep m/$searchtext/i, $commit_text) {
3493                                 next;
3494                         }
3495                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3496                                 next;
3497                         }
3498                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3499                                 next;
3500                         }
3501                         my @commit_lines = split "\n", $commit_text;
3502                         my %co = parse_commit(undef, \@commit_lines);
3503                         if (!%co) {
3504                                 next;
3505                         }
3506                         if ($alternate) {
3507                                 print "<tr class=\"dark\">\n";
3508                         } else {
3509                                 print "<tr class=\"light\">\n";
3510                         }
3511                         $alternate ^= 1;
3512                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3513                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3514                               "<td>" .
3515                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3516                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3517                         my $comment = $co{'comment'};
3518                         foreach my $line (@$comment) {
3519                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3520                                         my $lead = esc_html($1) || "";
3521                                         $lead = chop_str($lead, 30, 10);
3522                                         my $match = esc_html($2) || "";
3523                                         my $trail = esc_html($3) || "";
3524                                         $trail = chop_str($trail, 30, 10);
3525                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3526                                         print chop_str($text, 80, 5) . "<br/>\n";
3527                                 }
3528                         }
3529                         print "</td>\n" .
3530                               "<td class=\"link\">" .
3531                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3532                               " | " .
3533                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3534                         print "</td>\n" .
3535                               "</tr>\n";
3536                 }
3537                 close $fd;
3538         }
3540         if ($pickaxe_search) {
3541                 $/ = "\n";
3542                 my $git_command = git_cmd_str();
3543                 open my $fd, "-|", "$git_command rev-list $hash | " .
3544                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3545                 undef %co;
3546                 my @files;
3547                 while (my $line = <$fd>) {
3548                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3549                                 my %set;
3550                                 $set{'file'} = $6;
3551                                 $set{'from_id'} = $3;
3552                                 $set{'to_id'} = $4;
3553                                 $set{'id'} = $set{'to_id'};
3554                                 if ($set{'id'} =~ m/0{40}/) {
3555                                         $set{'id'} = $set{'from_id'};
3556                                 }
3557                                 if ($set{'id'} =~ m/0{40}/) {
3558                                         next;
3559                                 }
3560                                 push @files, \%set;
3561                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3562                                 if (%co) {
3563                                         if ($alternate) {
3564                                                 print "<tr class=\"dark\">\n";
3565                                         } else {
3566                                                 print "<tr class=\"light\">\n";
3567                                         }
3568                                         $alternate ^= 1;
3569                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3570                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3571                                               "<td>" .
3572                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3573                                                       -class => "list subject"},
3574                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3575                                         while (my $setref = shift @files) {
3576                                                 my %set = %$setref;
3577                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3578                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3579                                                               -class => "list"},
3580                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3581                                                       "<br/>\n";
3582                                         }
3583                                         print "</td>\n" .
3584                                               "<td class=\"link\">" .
3585                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3586                                               " | " .
3587                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3588                                         print "</td>\n" .
3589                                               "</tr>\n";
3590                                 }
3591                                 %co = parse_commit($1);
3592                         }
3593                 }
3594                 close $fd;
3595         }
3596         print "</table>\n";
3597         git_footer_html();
3600 sub git_shortlog {
3601         my $head = git_get_head_hash($project);
3602         if (!defined $hash) {
3603                 $hash = $head;
3604         }
3605         if (!defined $page) {
3606                 $page = 0;
3607         }
3608         my $refs = git_get_references();
3610         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3611         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3612                 or die_error(undef, "Open git-rev-list failed");
3613         my @revlist = map { chomp; $_ } <$fd>;
3614         close $fd;
3616         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3617         my $next_link = '';
3618         if ($#revlist >= (100 * ($page+1)-1)) {
3619                 $next_link =
3620                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3621                                  -title => "Alt-n"}, "next");
3622         }
3625         git_header_html();
3626         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3627         git_print_header_div('summary', $project);
3629         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3631         git_footer_html();
3634 ## ......................................................................
3635 ## feeds (RSS, OPML)
3637 sub git_rss {
3638         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3639         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3640                 or die_error(undef, "Open git-rev-list failed");
3641         my @revlist = map { chomp; $_ } <$fd>;
3642         close $fd or die_error(undef, "Reading git-rev-list failed");
3643         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3644         print <<XML;
3645 <?xml version="1.0" encoding="utf-8"?>
3646 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3647 <channel>
3648 <title>$project $my_uri $my_url</title>
3649 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3650 <description>$project log</description>
3651 <language>en</language>
3652 XML
3654         for (my $i = 0; $i <= $#revlist; $i++) {
3655                 my $commit = $revlist[$i];
3656                 my %co = parse_commit($commit);
3657                 # we read 150, we always show 30 and the ones more recent than 48 hours
3658                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3659                         last;
3660                 }
3661                 my %cd = parse_date($co{'committer_epoch'});
3662                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3663                         $co{'parent'}, $co{'id'}
3664                         or next;
3665                 my @difftree = map { chomp; $_ } <$fd>;
3666                 close $fd
3667                         or next;
3668                 print "<item>\n" .
3669                       "<title>" .
3670                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3671                       "</title>\n" .
3672                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3673                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3674                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3675                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3676                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3677                       "<content:encoded>" .
3678                       "<![CDATA[\n";
3679                 my $comment = $co{'comment'};
3680                 foreach my $line (@$comment) {
3681                         $line = to_utf8($line);
3682                         print "$line<br/>\n";
3683                 }
3684                 print "<br/>\n";
3685                 foreach my $line (@difftree) {
3686                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3687                                 next;
3688                         }
3689                         my $file = esc_html(unquote($7));
3690                         $file = to_utf8($file);
3691                         print "$file<br/>\n";
3692                 }
3693                 print "]]>\n" .
3694                       "</content:encoded>\n" .
3695                       "</item>\n";
3696         }
3697         print "</channel></rss>";
3700 sub git_opml {
3701         my @list = git_get_projects_list();
3703         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3704         print <<XML;
3705 <?xml version="1.0" encoding="utf-8"?>
3706 <opml version="1.0">
3707 <head>
3708   <title>$site_name Git OPML Export</title>
3709 </head>
3710 <body>
3711 <outline text="git RSS feeds">
3712 XML
3714         foreach my $pr (@list) {
3715                 my %proj = %$pr;
3716                 my $head = git_get_head_hash($proj{'path'});
3717                 if (!defined $head) {
3718                         next;
3719                 }
3720                 $git_dir = "$projectroot/$proj{'path'}";
3721                 my %co = parse_commit($head);
3722                 if (!%co) {
3723                         next;
3724                 }
3726                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3727                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3728                 my $html = "$my_url?p=$proj{'path'};a=summary";
3729                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3730         }
3731         print <<XML;
3732 </outline>
3733 </body>
3734 </opml>
3735 XML