Code

Merge branch 'mw/pathinfo'
[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                 $/ = "\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                 $/ = "\n";
1068                 pop @commit_lines;
1069         }
1070         my $header = shift @commit_lines;
1071         if (!($header =~ m/^[0-9a-fA-F]{40}/)) {
1072                 return;
1073         }
1074         ($co{'id'}, my @parents) = split ' ', $header;
1075         $co{'parents'} = \@parents;
1076         $co{'parent'} = $parents[0];
1077         while (my $line = shift @commit_lines) {
1078                 last if $line eq "\n";
1079                 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
1080                         $co{'tree'} = $1;
1081                 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
1082                         $co{'author'} = $1;
1083                         $co{'author_epoch'} = $2;
1084                         $co{'author_tz'} = $3;
1085                         if ($co{'author'} =~ m/^([^<]+) </) {
1086                                 $co{'author_name'} = $1;
1087                         } else {
1088                                 $co{'author_name'} = $co{'author'};
1089                         }
1090                 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
1091                         $co{'committer'} = $1;
1092                         $co{'committer_epoch'} = $2;
1093                         $co{'committer_tz'} = $3;
1094                         $co{'committer_name'} = $co{'committer'};
1095                         $co{'committer_name'} =~ s/ <.*//;
1096                 }
1097         }
1098         if (!defined $co{'tree'}) {
1099                 return;
1100         };
1102         foreach my $title (@commit_lines) {
1103                 $title =~ s/^    //;
1104                 if ($title ne "") {
1105                         $co{'title'} = chop_str($title, 80, 5);
1106                         # remove leading stuff of merges to make the interesting part visible
1107                         if (length($title) > 50) {
1108                                 $title =~ s/^Automatic //;
1109                                 $title =~ s/^merge (of|with) /Merge ... /i;
1110                                 if (length($title) > 50) {
1111                                         $title =~ s/(http|rsync):\/\///;
1112                                 }
1113                                 if (length($title) > 50) {
1114                                         $title =~ s/(master|www|rsync)\.//;
1115                                 }
1116                                 if (length($title) > 50) {
1117                                         $title =~ s/kernel.org:?//;
1118                                 }
1119                                 if (length($title) > 50) {
1120                                         $title =~ s/\/pub\/scm//;
1121                                 }
1122                         }
1123                         $co{'title_short'} = chop_str($title, 50, 5);
1124                         last;
1125                 }
1126         }
1127         if ($co{'title'} eq "") {
1128                 $co{'title'} = $co{'title_short'} = '(no commit message)';
1129         }
1130         # remove added spaces
1131         foreach my $line (@commit_lines) {
1132                 $line =~ s/^    //;
1133         }
1134         $co{'comment'} = \@commit_lines;
1136         my $age = time - $co{'committer_epoch'};
1137         $co{'age'} = $age;
1138         $co{'age_string'} = age_string($age);
1139         my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
1140         if ($age > 60*60*24*7*2) {
1141                 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1142                 $co{'age_string_age'} = $co{'age_string'};
1143         } else {
1144                 $co{'age_string_date'} = $co{'age_string'};
1145                 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
1146         }
1147         return %co;
1150 # parse ref from ref_file, given by ref_id, with given type
1151 sub parse_ref {
1152         my $ref_file = shift;
1153         my $ref_id = shift;
1154         my $type = shift || git_get_type($ref_id);
1155         my %ref_item;
1157         $ref_item{'type'} = $type;
1158         $ref_item{'id'} = $ref_id;
1159         $ref_item{'epoch'} = 0;
1160         $ref_item{'age'} = "unknown";
1161         if ($type eq "tag") {
1162                 my %tag = parse_tag($ref_id);
1163                 $ref_item{'comment'} = $tag{'comment'};
1164                 if ($tag{'type'} eq "commit") {
1165                         my %co = parse_commit($tag{'object'});
1166                         $ref_item{'epoch'} = $co{'committer_epoch'};
1167                         $ref_item{'age'} = $co{'age_string'};
1168                 } elsif (defined($tag{'epoch'})) {
1169                         my $age = time - $tag{'epoch'};
1170                         $ref_item{'epoch'} = $tag{'epoch'};
1171                         $ref_item{'age'} = age_string($age);
1172                 }
1173                 $ref_item{'reftype'} = $tag{'type'};
1174                 $ref_item{'name'} = $tag{'name'};
1175                 $ref_item{'refid'} = $tag{'object'};
1176         } elsif ($type eq "commit"){
1177                 my %co = parse_commit($ref_id);
1178                 $ref_item{'reftype'} = "commit";
1179                 $ref_item{'name'} = $ref_file;
1180                 $ref_item{'title'} = $co{'title'};
1181                 $ref_item{'refid'} = $ref_id;
1182                 $ref_item{'epoch'} = $co{'committer_epoch'};
1183                 $ref_item{'age'} = $co{'age_string'};
1184         } else {
1185                 $ref_item{'reftype'} = $type;
1186                 $ref_item{'name'} = $ref_file;
1187                 $ref_item{'refid'} = $ref_id;
1188         }
1190         return %ref_item;
1193 # parse line of git-diff-tree "raw" output
1194 sub parse_difftree_raw_line {
1195         my $line = shift;
1196         my %res;
1198         # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M   ls-files.c'
1199         # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M   rev-tree.c'
1200         if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
1201                 $res{'from_mode'} = $1;
1202                 $res{'to_mode'} = $2;
1203                 $res{'from_id'} = $3;
1204                 $res{'to_id'} = $4;
1205                 $res{'status'} = $5;
1206                 $res{'similarity'} = $6;
1207                 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
1208                         ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
1209                 } else {
1210                         $res{'file'} = unquote($7);
1211                 }
1212         }
1213         # 'c512b523472485aef4fff9e57b229d9d243c967f'
1214         elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
1215                 $res{'commit'} = $1;
1216         }
1218         return wantarray ? %res : \%res;
1221 # parse line of git-ls-tree output
1222 sub parse_ls_tree_line ($;%) {
1223         my $line = shift;
1224         my %opts = @_;
1225         my %res;
1227         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
1228         $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/;
1230         $res{'mode'} = $1;
1231         $res{'type'} = $2;
1232         $res{'hash'} = $3;
1233         if ($opts{'-z'}) {
1234                 $res{'name'} = $4;
1235         } else {
1236                 $res{'name'} = unquote($4);
1237         }
1239         return wantarray ? %res : \%res;
1242 ## ......................................................................
1243 ## parse to array of hashes functions
1245 sub git_get_refs_list {
1246         my $type = shift || "";
1247         my %refs;
1248         my @reflist;
1250         my @refs;
1251         open my $fd, "-|", $GIT, "peek-remote", "$projectroot/$project/"
1252                 or return;
1253         while (my $line = <$fd>) {
1254                 chomp $line;
1255                 if ($line =~ m/^([0-9a-fA-F]{40})\trefs\/($type\/?([^\^]+))(\^\{\})?$/) {
1256                         if (defined $refs{$1}) {
1257                                 push @{$refs{$1}}, $2;
1258                         } else {
1259                                 $refs{$1} = [ $2 ];
1260                         }
1262                         if (! $4) { # unpeeled, direct reference
1263                                 push @refs, { hash => $1, name => $3 }; # without type
1264                         } elsif ($3 eq $refs[-1]{'name'}) {
1265                                 # most likely a tag is followed by its peeled
1266                                 # (deref) one, and when that happens we know the
1267                                 # previous one was of type 'tag'.
1268                                 $refs[-1]{'type'} = "tag";
1269                         }
1270                 }
1271         }
1272         close $fd;
1274         foreach my $ref (@refs) {
1275                 my $ref_file = $ref->{'name'};
1276                 my $ref_id   = $ref->{'hash'};
1278                 my $type = $ref->{'type'} || git_get_type($ref_id) || next;
1279                 my %ref_item = parse_ref($ref_file, $ref_id, $type);
1281                 push @reflist, \%ref_item;
1282         }
1283         # sort refs by age
1284         @reflist = sort {$b->{'epoch'} <=> $a->{'epoch'}} @reflist;
1285         return (\@reflist, \%refs);
1288 ## ----------------------------------------------------------------------
1289 ## filesystem-related functions
1291 sub get_file_owner {
1292         my $path = shift;
1294         my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
1295         my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
1296         if (!defined $gcos) {
1297                 return undef;
1298         }
1299         my $owner = $gcos;
1300         $owner =~ s/[,;].*$//;
1301         return to_utf8($owner);
1304 ## ......................................................................
1305 ## mimetype related functions
1307 sub mimetype_guess_file {
1308         my $filename = shift;
1309         my $mimemap = shift;
1310         -r $mimemap or return undef;
1312         my %mimemap;
1313         open(MIME, $mimemap) or return undef;
1314         while (<MIME>) {
1315                 next if m/^#/; # skip comments
1316                 my ($mime, $exts) = split(/\t+/);
1317                 if (defined $exts) {
1318                         my @exts = split(/\s+/, $exts);
1319                         foreach my $ext (@exts) {
1320                                 $mimemap{$ext} = $mime;
1321                         }
1322                 }
1323         }
1324         close(MIME);
1326         $filename =~ /\.([^.]*)$/;
1327         return $mimemap{$1};
1330 sub mimetype_guess {
1331         my $filename = shift;
1332         my $mime;
1333         $filename =~ /\./ or return undef;
1335         if ($mimetypes_file) {
1336                 my $file = $mimetypes_file;
1337                 if ($file !~ m!^/!) { # if it is relative path
1338                         # it is relative to project
1339                         $file = "$projectroot/$project/$file";
1340                 }
1341                 $mime = mimetype_guess_file($filename, $file);
1342         }
1343         $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
1344         return $mime;
1347 sub blob_mimetype {
1348         my $fd = shift;
1349         my $filename = shift;
1351         if ($filename) {
1352                 my $mime = mimetype_guess($filename);
1353                 $mime and return $mime;
1354         }
1356         # just in case
1357         return $default_blob_plain_mimetype unless $fd;
1359         if (-T $fd) {
1360                 return 'text/plain' .
1361                        ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
1362         } elsif (! $filename) {
1363                 return 'application/octet-stream';
1364         } elsif ($filename =~ m/\.png$/i) {
1365                 return 'image/png';
1366         } elsif ($filename =~ m/\.gif$/i) {
1367                 return 'image/gif';
1368         } elsif ($filename =~ m/\.jpe?g$/i) {
1369                 return 'image/jpeg';
1370         } else {
1371                 return 'application/octet-stream';
1372         }
1375 ## ======================================================================
1376 ## functions printing HTML: header, footer, error page
1378 sub git_header_html {
1379         my $status = shift || "200 OK";
1380         my $expires = shift;
1382         my $title = "$site_name git";
1383         if (defined $project) {
1384                 $title .= " - $project";
1385                 if (defined $action) {
1386                         $title .= "/$action";
1387                         if (defined $file_name) {
1388                                 $title .= " - " . esc_html($file_name);
1389                                 if ($action eq "tree" && $file_name !~ m|/$|) {
1390                                         $title .= "/";
1391                                 }
1392                         }
1393                 }
1394         }
1395         my $content_type;
1396         # require explicit support from the UA if we are to send the page as
1397         # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
1398         # we have to do this because MSIE sometimes globs '*/*', pretending to
1399         # support xhtml+xml but choking when it gets what it asked for.
1400         if (defined $cgi->http('HTTP_ACCEPT') &&
1401             $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
1402             $cgi->Accept('application/xhtml+xml') != 0) {
1403                 $content_type = 'application/xhtml+xml';
1404         } else {
1405                 $content_type = 'text/html';
1406         }
1407         print $cgi->header(-type=>$content_type, -charset => 'utf-8',
1408                            -status=> $status, -expires => $expires);
1409         print <<EOF;
1410 <?xml version="1.0" encoding="utf-8"?>
1411 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1412 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
1413 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
1414 <!-- git core binaries version $git_version -->
1415 <head>
1416 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
1417 <meta name="generator" content="gitweb/$version git/$git_version"/>
1418 <meta name="robots" content="index, nofollow"/>
1419 <title>$title</title>
1420 <link rel="stylesheet" type="text/css" href="$stylesheet"/>
1421 EOF
1422         if (defined $project) {
1423                 printf('<link rel="alternate" title="%s log" '.
1424                        'href="%s" type="application/rss+xml"/>'."\n",
1425                        esc_param($project), href(action=>"rss"));
1426         } else {
1427                 printf('<link rel="alternate" title="%s projects list" '.
1428                        'href="%s" type="text/plain; charset=utf-8"/>'."\n",
1429                        $site_name, href(project=>undef, action=>"project_index"));
1430                 printf('<link rel="alternate" title="%s projects logs" '.
1431                        'href="%s" type="text/x-opml"/>'."\n",
1432                        $site_name, href(project=>undef, action=>"opml"));
1433         }
1434         if (defined $favicon) {
1435                 print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
1436         }
1438         print "</head>\n" .
1439               "<body>\n" .
1440               "<div class=\"page_header\">\n" .
1441               $cgi->a({-href => esc_url($logo_url),
1442                        -title => $logo_label},
1443                       qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
1444         print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
1445         if (defined $project) {
1446                 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
1447                 if (defined $action) {
1448                         print " / $action";
1449                 }
1450                 print "\n";
1451                 if (!defined $searchtext) {
1452                         $searchtext = "";
1453                 }
1454                 my $search_hash;
1455                 if (defined $hash_base) {
1456                         $search_hash = $hash_base;
1457                 } elsif (defined $hash) {
1458                         $search_hash = $hash;
1459                 } else {
1460                         $search_hash = "HEAD";
1461                 }
1462                 $cgi->param("a", "search");
1463                 $cgi->param("h", $search_hash);
1464                 $cgi->param("p", $project);
1465                 print $cgi->startform(-method => "get", -action => $my_uri) .
1466                       "<div class=\"search\">\n" .
1467                       $cgi->hidden(-name => "p") . "\n" .
1468                       $cgi->hidden(-name => "a") . "\n" .
1469                       $cgi->hidden(-name => "h") . "\n" .
1470                       $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
1471                       "</div>" .
1472                       $cgi->end_form() . "\n";
1473         }
1474         print "</div>\n";
1477 sub git_footer_html {
1478         print "<div class=\"page_footer\">\n";
1479         if (defined $project) {
1480                 my $descr = git_get_project_description($project);
1481                 if (defined $descr) {
1482                         print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
1483                 }
1484                 print $cgi->a({-href => href(action=>"rss"),
1485                               -class => "rss_logo"}, "RSS") . "\n";
1486         } else {
1487                 print $cgi->a({-href => href(project=>undef, action=>"opml"),
1488                               -class => "rss_logo"}, "OPML") . " ";
1489                 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
1490                               -class => "rss_logo"}, "TXT") . "\n";
1491         }
1492         print "</div>\n" .
1493               "</body>\n" .
1494               "</html>";
1497 sub die_error {
1498         my $status = shift || "403 Forbidden";
1499         my $error = shift || "Malformed query, file missing or permission denied";
1501         git_header_html($status);
1502         print <<EOF;
1503 <div class="page_body">
1504 <br /><br />
1505 $status - $error
1506 <br />
1507 </div>
1508 EOF
1509         git_footer_html();
1510         exit;
1513 ## ----------------------------------------------------------------------
1514 ## functions printing or outputting HTML: navigation
1516 sub git_print_page_nav {
1517         my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
1518         $extra = '' if !defined $extra; # pager or formats
1520         my @navs = qw(summary shortlog log commit commitdiff tree);
1521         if ($suppress) {
1522                 @navs = grep { $_ ne $suppress } @navs;
1523         }
1525         my %arg = map { $_ => {action=>$_} } @navs;
1526         if (defined $head) {
1527                 for (qw(commit commitdiff)) {
1528                         $arg{$_}{hash} = $head;
1529                 }
1530                 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
1531                         for (qw(shortlog log)) {
1532                                 $arg{$_}{hash} = $head;
1533                         }
1534                 }
1535         }
1536         $arg{tree}{hash} = $treehead if defined $treehead;
1537         $arg{tree}{hash_base} = $treebase if defined $treebase;
1539         print "<div class=\"page_nav\">\n" .
1540                 (join " | ",
1541                  map { $_ eq $current ?
1542                        $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
1543                  } @navs);
1544         print "<br/>\n$extra<br/>\n" .
1545               "</div>\n";
1548 sub format_paging_nav {
1549         my ($action, $hash, $head, $page, $nrevs) = @_;
1550         my $paging_nav;
1553         if ($hash ne $head || $page) {
1554                 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
1555         } else {
1556                 $paging_nav .= "HEAD";
1557         }
1559         if ($page > 0) {
1560                 $paging_nav .= " &sdot; " .
1561                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
1562                                  -accesskey => "p", -title => "Alt-p"}, "prev");
1563         } else {
1564                 $paging_nav .= " &sdot; prev";
1565         }
1567         if ($nrevs >= (100 * ($page+1)-1)) {
1568                 $paging_nav .= " &sdot; " .
1569                         $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
1570                                  -accesskey => "n", -title => "Alt-n"}, "next");
1571         } else {
1572                 $paging_nav .= " &sdot; next";
1573         }
1575         return $paging_nav;
1578 ## ......................................................................
1579 ## functions printing or outputting HTML: div
1581 sub git_print_header_div {
1582         my ($action, $title, $hash, $hash_base) = @_;
1583         my %args = ();
1585         $args{action} = $action;
1586         $args{hash} = $hash if $hash;
1587         $args{hash_base} = $hash_base if $hash_base;
1589         print "<div class=\"header\">\n" .
1590               $cgi->a({-href => href(%args), -class => "title"},
1591               $title ? $title : $action) .
1592               "\n</div>\n";
1595 #sub git_print_authorship (\%) {
1596 sub git_print_authorship {
1597         my $co = shift;
1599         my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
1600         print "<div class=\"author_date\">" .
1601               esc_html($co->{'author_name'}) .
1602               " [$ad{'rfc2822'}";
1603         if ($ad{'hour_local'} < 6) {
1604                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
1605                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1606         } else {
1607                 printf(" (%02d:%02d %s)",
1608                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
1609         }
1610         print "]</div>\n";
1613 sub git_print_page_path {
1614         my $name = shift;
1615         my $type = shift;
1616         my $hb = shift;
1618         if (!defined $name) {
1619                 print "<div class=\"page_path\">/</div>\n";
1620         } else {
1621                 my @dirname = split '/', $name;
1622                 my $basename = pop @dirname;
1623                 my $fullname = '';
1625                 print "<div class=\"page_path\">";
1626                 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
1627                               -title => 'tree root'}, "[$project]");
1628                 print " / ";
1629                 foreach my $dir (@dirname) {
1630                         $fullname .= ($fullname ? '/' : '') . $dir;
1631                         print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
1632                                                      hash_base=>$hb),
1633                                       -title => $fullname}, esc_html($dir));
1634                         print " / ";
1635                 }
1636                 if (defined $type && $type eq 'blob') {
1637                         print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
1638                                                      hash_base=>$hb),
1639                                       -title => $name}, esc_html($basename));
1640                 } elsif (defined $type && $type eq 'tree') {
1641                         print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
1642                                                      hash_base=>$hb),
1643                                       -title => $name}, esc_html($basename));
1644                 } else {
1645                         print esc_html($basename);
1646                 }
1647                 print "<br/></div>\n";
1648         }
1651 # sub git_print_log (\@;%) {
1652 sub git_print_log ($;%) {
1653         my $log = shift;
1654         my %opts = @_;
1656         if ($opts{'-remove_title'}) {
1657                 # remove title, i.e. first line of log
1658                 shift @$log;
1659         }
1660         # remove leading empty lines
1661         while (defined $log->[0] && $log->[0] eq "") {
1662                 shift @$log;
1663         }
1665         # print log
1666         my $signoff = 0;
1667         my $empty = 0;
1668         foreach my $line (@$log) {
1669                 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
1670                         $signoff = 1;
1671                         $empty = 0;
1672                         if (! $opts{'-remove_signoff'}) {
1673                                 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
1674                                 next;
1675                         } else {
1676                                 # remove signoff lines
1677                                 next;
1678                         }
1679                 } else {
1680                         $signoff = 0;
1681                 }
1683                 # print only one empty line
1684                 # do not print empty line after signoff
1685                 if ($line eq "") {
1686                         next if ($empty || $signoff);
1687                         $empty = 1;
1688                 } else {
1689                         $empty = 0;
1690                 }
1692                 print format_log_line_html($line) . "<br/>\n";
1693         }
1695         if ($opts{'-final_empty_line'}) {
1696                 # end with single empty line
1697                 print "<br/>\n" unless $empty;
1698         }
1701 sub git_print_simplified_log {
1702         my $log = shift;
1703         my $remove_title = shift;
1705         git_print_log($log,
1706                 -final_empty_line=> 1,
1707                 -remove_title => $remove_title);
1710 # print tree entry (row of git_tree), but without encompassing <tr> element
1711 sub git_print_tree_entry {
1712         my ($t, $basedir, $hash_base, $have_blame) = @_;
1714         my %base_key = ();
1715         $base_key{hash_base} = $hash_base if defined $hash_base;
1717         # The format of a table row is: mode list link.  Where mode is
1718         # the mode of the entry, list is the name of the entry, an href,
1719         # and link is the action links of the entry.
1721         print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
1722         if ($t->{'type'} eq "blob") {
1723                 print "<td class=\"list\">" .
1724                         $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
1725                                                file_name=>"$basedir$t->{'name'}", %base_key),
1726                                  -class => "list"}, esc_html($t->{'name'})) . "</td>\n";
1727                 print "<td class=\"link\">";
1728                 if ($have_blame) {
1729                         print $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
1730                                                      file_name=>"$basedir$t->{'name'}", %base_key)},
1731                                       "blame");
1732                 }
1733                 if (defined $hash_base) {
1734                         if ($have_blame) {
1735                                 print " | ";
1736                         }
1737                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1738                                                      hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
1739                                       "history");
1740                 }
1741                 print " | " .
1742                         $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
1743                                                file_name=>"$basedir$t->{'name'}")},
1744                                 "raw");
1745                 print "</td>\n";
1747         } elsif ($t->{'type'} eq "tree") {
1748                 print "<td class=\"list\">";
1749                 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
1750                                              file_name=>"$basedir$t->{'name'}", %base_key)},
1751                               esc_html($t->{'name'}));
1752                 print "</td>\n";
1753                 print "<td class=\"link\">";
1754                 if (defined $hash_base) {
1755                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
1756                                                      file_name=>"$basedir$t->{'name'}")},
1757                                       "history");
1758                 }
1759                 print "</td>\n";
1760         }
1763 ## ......................................................................
1764 ## functions printing large fragments of HTML
1766 sub git_difftree_body {
1767         my ($difftree, $hash, $parent) = @_;
1769         print "<div class=\"list_head\">\n";
1770         if ($#{$difftree} > 10) {
1771                 print(($#{$difftree} + 1) . " files changed:\n");
1772         }
1773         print "</div>\n";
1775         print "<table class=\"diff_tree\">\n";
1776         my $alternate = 1;
1777         my $patchno = 0;
1778         foreach my $line (@{$difftree}) {
1779                 my %diff = parse_difftree_raw_line($line);
1781                 if ($alternate) {
1782                         print "<tr class=\"dark\">\n";
1783                 } else {
1784                         print "<tr class=\"light\">\n";
1785                 }
1786                 $alternate ^= 1;
1788                 my ($to_mode_oct, $to_mode_str, $to_file_type);
1789                 my ($from_mode_oct, $from_mode_str, $from_file_type);
1790                 if ($diff{'to_mode'} ne ('0' x 6)) {
1791                         $to_mode_oct = oct $diff{'to_mode'};
1792                         if (S_ISREG($to_mode_oct)) { # only for regular file
1793                                 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
1794                         }
1795                         $to_file_type = file_type($diff{'to_mode'});
1796                 }
1797                 if ($diff{'from_mode'} ne ('0' x 6)) {
1798                         $from_mode_oct = oct $diff{'from_mode'};
1799                         if (S_ISREG($to_mode_oct)) { # only for regular file
1800                                 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
1801                         }
1802                         $from_file_type = file_type($diff{'from_mode'});
1803                 }
1805                 if ($diff{'status'} eq "A") { # created
1806                         my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
1807                         $mode_chng   .= " with mode: $to_mode_str" if $to_mode_str;
1808                         $mode_chng   .= "]</span>";
1809                         print "<td>";
1810                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1811                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1812                                        -class => "list"}, esc_html($diff{'file'}));
1813                         print "</td>\n";
1814                         print "<td>$mode_chng</td>\n";
1815                         print "<td class=\"link\">";
1816                         if ($action eq 'commitdiff') {
1817                                 # link to patch
1818                                 $patchno++;
1819                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
1820                         }
1821                         print "</td>\n";
1823                 } elsif ($diff{'status'} eq "D") { # deleted
1824                         my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
1825                         print "<td>";
1826                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'from_id'},
1827                                                      hash_base=>$parent, file_name=>$diff{'file'}),
1828                                        -class => "list"}, esc_html($diff{'file'}));
1829                         print "</td>\n";
1830                         print "<td>$mode_chng</td>\n";
1831                         print "<td class=\"link\">";
1832                         if ($action eq 'commitdiff') {
1833                                 # link to patch
1834                                 $patchno++;
1835                                 print $cgi->a({-href => "#patch$patchno"}, "patch");
1836                                 print " | ";
1837                         }
1838                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1839                                                      file_name=>$diff{'file'})},
1840                                       "blame") . " | ";
1841                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1842                                                      file_name=>$diff{'file'})},
1843                                       "history");
1844                         print "</td>\n";
1846                 } elsif ($diff{'status'} eq "M" || $diff{'status'} eq "T") { # modified, or type changed
1847                         my $mode_chnge = "";
1848                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1849                                 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
1850                                 if ($from_file_type != $to_file_type) {
1851                                         $mode_chnge .= " from $from_file_type to $to_file_type";
1852                                 }
1853                                 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
1854                                         if ($from_mode_str && $to_mode_str) {
1855                                                 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
1856                                         } elsif ($to_mode_str) {
1857                                                 $mode_chnge .= " mode: $to_mode_str";
1858                                         }
1859                                 }
1860                                 $mode_chnge .= "]</span>\n";
1861                         }
1862                         print "<td>";
1863                         print $cgi->a({-href => href(action=>"blob", hash=>$diff{'to_id'},
1864                                                      hash_base=>$hash, file_name=>$diff{'file'}),
1865                                        -class => "list"}, esc_html($diff{'file'}));
1866                         print "</td>\n";
1867                         print "<td>$mode_chnge</td>\n";
1868                         print "<td class=\"link\">";
1869                         if ($diff{'to_id'} ne $diff{'from_id'}) { # modified
1870                                 if ($action eq 'commitdiff') {
1871                                         # link to patch
1872                                         $patchno++;
1873                                         print $cgi->a({-href => "#patch$patchno"}, "patch");
1874                                 } else {
1875                                         print $cgi->a({-href => href(action=>"blobdiff",
1876                                                                      hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1877                                                                      hash_base=>$hash, hash_parent_base=>$parent,
1878                                                                      file_name=>$diff{'file'})},
1879                                                       "diff");
1880                                 }
1881                                 print " | ";
1882                         }
1883                         print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
1884                                                      file_name=>$diff{'file'})},
1885                                       "blame") . " | ";
1886                         print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
1887                                                      file_name=>$diff{'file'})},
1888                                       "history");
1889                         print "</td>\n";
1891                 } elsif ($diff{'status'} eq "R" || $diff{'status'} eq "C") { # renamed or copied
1892                         my %status_name = ('R' => 'moved', 'C' => 'copied');
1893                         my $nstatus = $status_name{$diff{'status'}};
1894                         my $mode_chng = "";
1895                         if ($diff{'from_mode'} != $diff{'to_mode'}) {
1896                                 # mode also for directories, so we cannot use $to_mode_str
1897                                 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
1898                         }
1899                         print "<td>" .
1900                               $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1901                                                      hash=>$diff{'to_id'}, file_name=>$diff{'to_file'}),
1902                                       -class => "list"}, esc_html($diff{'to_file'})) . "</td>\n" .
1903                               "<td><span class=\"file_status $nstatus\">[$nstatus from " .
1904                               $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
1905                                                      hash=>$diff{'from_id'}, file_name=>$diff{'from_file'}),
1906                                       -class => "list"}, esc_html($diff{'from_file'})) .
1907                               " with " . (int $diff{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
1908                               "<td class=\"link\">";
1909                         if ($diff{'to_id'} ne $diff{'from_id'}) {
1910                                 if ($action eq 'commitdiff') {
1911                                         # link to patch
1912                                         $patchno++;
1913                                         print $cgi->a({-href => "#patch$patchno"}, "patch");
1914                                 } else {
1915                                         print $cgi->a({-href => href(action=>"blobdiff",
1916                                                                      hash=>$diff{'to_id'}, hash_parent=>$diff{'from_id'},
1917                                                                      hash_base=>$hash, hash_parent_base=>$parent,
1918                                                                      file_name=>$diff{'to_file'}, file_parent=>$diff{'from_file'})},
1919                                                       "diff");
1920                                 }
1921                                 print " | ";
1922                         }
1923                         print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
1924                                                      file_name=>$diff{'from_file'})},
1925                                       "blame") . " | ";
1926                         print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
1927                                                      file_name=>$diff{'from_file'})},
1928                                       "history");
1929                         print "</td>\n";
1931                 } # we should not encounter Unmerged (U) or Unknown (X) status
1932                 print "</tr>\n";
1933         }
1934         print "</table>\n";
1937 sub git_patchset_body {
1938         my ($fd, $difftree, $hash, $hash_parent) = @_;
1940         my $patch_idx = 0;
1941         my $in_header = 0;
1942         my $patch_found = 0;
1943         my $diffinfo;
1945         print "<div class=\"patchset\">\n";
1947         LINE:
1948         while (my $patch_line = <$fd>) {
1949                 chomp $patch_line;
1951                 if ($patch_line =~ m/^diff /) { # "git diff" header
1952                         # beginning of patch (in patchset)
1953                         if ($patch_found) {
1954                                 # close previous patch
1955                                 print "</div>\n"; # class="patch"
1956                         } else {
1957                                 # first patch in patchset
1958                                 $patch_found = 1;
1959                         }
1960                         print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
1962                         if (ref($difftree->[$patch_idx]) eq "HASH") {
1963                                 $diffinfo = $difftree->[$patch_idx];
1964                         } else {
1965                                 $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
1966                         }
1967                         $patch_idx++;
1969                         # for now, no extended header, hence we skip empty patches
1970                         # companion to  next LINE if $in_header;
1971                         if ($diffinfo->{'from_id'} eq $diffinfo->{'to_id'}) { # no change
1972                                 $in_header = 1;
1973                                 next LINE;
1974                         }
1976                         if ($diffinfo->{'status'} eq "A") { # added
1977                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'to_mode'}) . ":" .
1978                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
1979                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
1980                                               $diffinfo->{'to_id'}) . " (new)" .
1981                                       "</div>\n"; # class="diff_info"
1983                         } elsif ($diffinfo->{'status'} eq "D") { # deleted
1984                                 print "<div class=\"diff_info\">" . file_type($diffinfo->{'from_mode'}) . ":" .
1985                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1986                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
1987                                               $diffinfo->{'from_id'}) . " (deleted)" .
1988                                       "</div>\n"; # class="diff_info"
1990                         } elsif ($diffinfo->{'status'} eq "R" || # renamed
1991                                  $diffinfo->{'status'} eq "C" || # copied
1992                                  $diffinfo->{'status'} eq "2") { # with two filenames (from git_blobdiff)
1993                                 print "<div class=\"diff_info\">" .
1994                                       file_type($diffinfo->{'from_mode'}) . ":" .
1995                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
1996                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'from_file'})},
1997                                               $diffinfo->{'from_id'}) .
1998                                       " -> " .
1999                                       file_type($diffinfo->{'to_mode'}) . ":" .
2000                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2001                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'to_file'})},
2002                                               $diffinfo->{'to_id'});
2003                                 print "</div>\n"; # class="diff_info"
2005                         } else { # modified, mode changed, ...
2006                                 print "<div class=\"diff_info\">" .
2007                                       file_type($diffinfo->{'from_mode'}) . ":" .
2008                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2009                                                              hash=>$diffinfo->{'from_id'}, file_name=>$diffinfo->{'file'})},
2010                                               $diffinfo->{'from_id'}) .
2011                                       " -> " .
2012                                       file_type($diffinfo->{'to_mode'}) . ":" .
2013                                       $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2014                                                              hash=>$diffinfo->{'to_id'}, file_name=>$diffinfo->{'file'})},
2015                                               $diffinfo->{'to_id'});
2016                                 print "</div>\n"; # class="diff_info"
2017                         }
2019                         #print "<div class=\"diff extended_header\">\n";
2020                         $in_header = 1;
2021                         next LINE;
2022                 } # start of patch in patchset
2025                 if ($in_header && $patch_line =~ m/^---/) {
2026                         #print "</div>\n"; # class="diff extended_header"
2027                         $in_header = 0;
2029                         my $file = $diffinfo->{'from_file'};
2030                         $file  ||= $diffinfo->{'file'};
2031                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash_parent,
2032                                                        hash=>$diffinfo->{'from_id'}, file_name=>$file),
2033                                         -class => "list"}, esc_html($file));
2034                         $patch_line =~ s|a/.*$|a/$file|g;
2035                         print "<div class=\"diff from_file\">$patch_line</div>\n";
2037                         $patch_line = <$fd>;
2038                         chomp $patch_line;
2040                         #$patch_line =~ m/^+++/;
2041                         $file    = $diffinfo->{'to_file'};
2042                         $file  ||= $diffinfo->{'file'};
2043                         $file = $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
2044                                                        hash=>$diffinfo->{'to_id'}, file_name=>$file),
2045                                         -class => "list"}, esc_html($file));
2046                         $patch_line =~ s|b/.*|b/$file|g;
2047                         print "<div class=\"diff to_file\">$patch_line</div>\n";
2049                         next LINE;
2050                 }
2051                 next LINE if $in_header;
2053                 print format_diff_line($patch_line);
2054         }
2055         print "</div>\n" if $patch_found; # class="patch"
2057         print "</div>\n"; # class="patchset"
2060 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2062 sub git_shortlog_body {
2063         # uses global variable $project
2064         my ($revlist, $from, $to, $refs, $extra) = @_;
2066         $from = 0 unless defined $from;
2067         $to = $#{$revlist} if (!defined $to || $#{$revlist} < $to);
2069         print "<table class=\"shortlog\" cellspacing=\"0\">\n";
2070         my $alternate = 1;
2071         for (my $i = $from; $i <= $to; $i++) {
2072                 my $commit = $revlist->[$i];
2073                 #my $ref = defined $refs ? format_ref_marker($refs, $commit) : '';
2074                 my $ref = format_ref_marker($refs, $commit);
2075                 my %co = parse_commit($commit);
2076                 if ($alternate) {
2077                         print "<tr class=\"dark\">\n";
2078                 } else {
2079                         print "<tr class=\"light\">\n";
2080                 }
2081                 $alternate ^= 1;
2082                 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
2083                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2084                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
2085                       "<td>";
2086                 print format_subject_html($co{'title'}, $co{'title_short'},
2087                                           href(action=>"commit", hash=>$commit), $ref);
2088                 print "</td>\n" .
2089                       "<td class=\"link\">" .
2090                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
2091                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
2092                 if (gitweb_have_snapshot()) {
2093                         print " | " . $cgi->a({-href => href(action=>"snapshot", hash=>$commit)}, "snapshot");
2094                 }
2095                 print "</td>\n" .
2096                       "</tr>\n";
2097         }
2098         if (defined $extra) {
2099                 print "<tr>\n" .
2100                       "<td colspan=\"4\">$extra</td>\n" .
2101                       "</tr>\n";
2102         }
2103         print "</table>\n";
2106 sub git_history_body {
2107         # Warning: assumes constant type (blob or tree) during history
2108         my ($revlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
2110         $from = 0 unless defined $from;
2111         $to = $#{$revlist} unless (defined $to && $to <= $#{$revlist});
2113         print "<table class=\"history\" cellspacing=\"0\">\n";
2114         my $alternate = 1;
2115         for (my $i = $from; $i <= $to; $i++) {
2116                 if ($revlist->[$i] !~ m/^([0-9a-fA-F]{40})/) {
2117                         next;
2118                 }
2120                 my $commit = $1;
2121                 my %co = parse_commit($commit);
2122                 if (!%co) {
2123                         next;
2124                 }
2126                 my $ref = format_ref_marker($refs, $commit);
2128                 if ($alternate) {
2129                         print "<tr class=\"dark\">\n";
2130                 } else {
2131                         print "<tr class=\"light\">\n";
2132                 }
2133                 $alternate ^= 1;
2134                 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
2135                       # shortlog uses      chop_str($co{'author_name'}, 10)
2136                       "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
2137                       "<td>";
2138                 # originally git_history used chop_str($co{'title'}, 50)
2139                 print format_subject_html($co{'title'}, $co{'title_short'},
2140                                           href(action=>"commit", hash=>$commit), $ref);
2141                 print "</td>\n" .
2142                       "<td class=\"link\">" .
2143                       $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
2144                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
2146                 if ($ftype eq 'blob') {
2147                         my $blob_current = git_get_hash_by_path($hash_base, $file_name);
2148                         my $blob_parent  = git_get_hash_by_path($commit, $file_name);
2149                         if (defined $blob_current && defined $blob_parent &&
2150                                         $blob_current ne $blob_parent) {
2151                                 print " | " .
2152                                         $cgi->a({-href => href(action=>"blobdiff",
2153                                                                hash=>$blob_current, hash_parent=>$blob_parent,
2154                                                                hash_base=>$hash_base, hash_parent_base=>$commit,
2155                                                                file_name=>$file_name)},
2156                                                 "diff to current");
2157                         }
2158                 }
2159                 print "</td>\n" .
2160                       "</tr>\n";
2161         }
2162         if (defined $extra) {
2163                 print "<tr>\n" .
2164                       "<td colspan=\"4\">$extra</td>\n" .
2165                       "</tr>\n";
2166         }
2167         print "</table>\n";
2170 sub git_tags_body {
2171         # uses global variable $project
2172         my ($taglist, $from, $to, $extra) = @_;
2173         $from = 0 unless defined $from;
2174         $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
2176         print "<table class=\"tags\" cellspacing=\"0\">\n";
2177         my $alternate = 1;
2178         for (my $i = $from; $i <= $to; $i++) {
2179                 my $entry = $taglist->[$i];
2180                 my %tag = %$entry;
2181                 my $comment_lines = $tag{'comment'};
2182                 my $comment = shift @$comment_lines;
2183                 my $comment_short;
2184                 if (defined $comment) {
2185                         $comment_short = chop_str($comment, 30, 5);
2186                 }
2187                 if ($alternate) {
2188                         print "<tr class=\"dark\">\n";
2189                 } else {
2190                         print "<tr class=\"light\">\n";
2191                 }
2192                 $alternate ^= 1;
2193                 print "<td><i>$tag{'age'}</i></td>\n" .
2194                       "<td>" .
2195                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
2196                                -class => "list name"}, esc_html($tag{'name'})) .
2197                       "</td>\n" .
2198                       "<td>";
2199                 if (defined $comment) {
2200                         print format_subject_html($comment, $comment_short,
2201                                                   href(action=>"tag", hash=>$tag{'id'}));
2202                 }
2203                 print "</td>\n" .
2204                       "<td class=\"selflink\">";
2205                 if ($tag{'type'} eq "tag") {
2206                         print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
2207                 } else {
2208                         print "&nbsp;";
2209                 }
2210                 print "</td>\n" .
2211                       "<td class=\"link\">" . " | " .
2212                       $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
2213                 if ($tag{'reftype'} eq "commit") {
2214                         print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
2215                               " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'refid'})}, "log");
2216                 } elsif ($tag{'reftype'} eq "blob") {
2217                         print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
2218                 }
2219                 print "</td>\n" .
2220                       "</tr>";
2221         }
2222         if (defined $extra) {
2223                 print "<tr>\n" .
2224                       "<td colspan=\"5\">$extra</td>\n" .
2225                       "</tr>\n";
2226         }
2227         print "</table>\n";
2230 sub git_heads_body {
2231         # uses global variable $project
2232         my ($headlist, $head, $from, $to, $extra) = @_;
2233         $from = 0 unless defined $from;
2234         $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
2236         print "<table class=\"heads\" cellspacing=\"0\">\n";
2237         my $alternate = 1;
2238         for (my $i = $from; $i <= $to; $i++) {
2239                 my $entry = $headlist->[$i];
2240                 my %tag = %$entry;
2241                 my $curr = $tag{'id'} eq $head;
2242                 if ($alternate) {
2243                         print "<tr class=\"dark\">\n";
2244                 } else {
2245                         print "<tr class=\"light\">\n";
2246                 }
2247                 $alternate ^= 1;
2248                 print "<td><i>$tag{'age'}</i></td>\n" .
2249                       ($tag{'id'} eq $head ? "<td class=\"current_head\">" : "<td>") .
2250                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'}),
2251                                -class => "list name"},esc_html($tag{'name'})) .
2252                       "</td>\n" .
2253                       "<td class=\"link\">" .
2254                       $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") . " | " .
2255                       $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log") . " | " .
2256                       $cgi->a({-href => href(action=>"tree", hash=>$tag{'name'}, hash_base=>$tag{'name'})}, "tree") .
2257                       "</td>\n" .
2258                       "</tr>";
2259         }
2260         if (defined $extra) {
2261                 print "<tr>\n" .
2262                       "<td colspan=\"3\">$extra</td>\n" .
2263                       "</tr>\n";
2264         }
2265         print "</table>\n";
2268 ## ======================================================================
2269 ## ======================================================================
2270 ## actions
2272 sub git_project_list {
2273         my $order = $cgi->param('o');
2274         if (defined $order && $order !~ m/project|descr|owner|age/) {
2275                 die_error(undef, "Unknown order parameter");
2276         }
2278         my @list = git_get_projects_list();
2279         my @projects;
2280         if (!@list) {
2281                 die_error(undef, "No projects found");
2282         }
2283         foreach my $pr (@list) {
2284                 my $head = git_get_head_hash($pr->{'path'});
2285                 if (!defined $head) {
2286                         next;
2287                 }
2288                 $git_dir = "$projectroot/$pr->{'path'}";
2289                 my %co = parse_commit($head);
2290                 if (!%co) {
2291                         next;
2292                 }
2293                 $pr->{'commit'} = \%co;
2294                 if (!defined $pr->{'descr'}) {
2295                         my $descr = git_get_project_description($pr->{'path'}) || "";
2296                         $pr->{'descr'} = chop_str($descr, 25, 5);
2297                 }
2298                 if (!defined $pr->{'owner'}) {
2299                         $pr->{'owner'} = get_file_owner("$projectroot/$pr->{'path'}") || "";
2300                 }
2301                 push @projects, $pr;
2302         }
2304         git_header_html();
2305         if (-f $home_text) {
2306                 print "<div class=\"index_include\">\n";
2307                 open (my $fd, $home_text);
2308                 print <$fd>;
2309                 close $fd;
2310                 print "</div>\n";
2311         }
2312         print "<table class=\"project_list\">\n" .
2313               "<tr>\n";
2314         $order ||= "project";
2315         if ($order eq "project") {
2316                 @projects = sort {$a->{'path'} cmp $b->{'path'}} @projects;
2317                 print "<th>Project</th>\n";
2318         } else {
2319                 print "<th>" .
2320                       $cgi->a({-href => href(project=>undef, order=>'project'),
2321                                -class => "header"}, "Project") .
2322                       "</th>\n";
2323         }
2324         if ($order eq "descr") {
2325                 @projects = sort {$a->{'descr'} cmp $b->{'descr'}} @projects;
2326                 print "<th>Description</th>\n";
2327         } else {
2328                 print "<th>" .
2329                       $cgi->a({-href => href(project=>undef, order=>'descr'),
2330                                -class => "header"}, "Description") .
2331                       "</th>\n";
2332         }
2333         if ($order eq "owner") {
2334                 @projects = sort {$a->{'owner'} cmp $b->{'owner'}} @projects;
2335                 print "<th>Owner</th>\n";
2336         } else {
2337                 print "<th>" .
2338                       $cgi->a({-href => href(project=>undef, order=>'owner'),
2339                                -class => "header"}, "Owner") .
2340                       "</th>\n";
2341         }
2342         if ($order eq "age") {
2343                 @projects = sort {$a->{'commit'}{'age'} <=> $b->{'commit'}{'age'}} @projects;
2344                 print "<th>Last Change</th>\n";
2345         } else {
2346                 print "<th>" .
2347                       $cgi->a({-href => href(project=>undef, order=>'age'),
2348                                -class => "header"}, "Last Change") .
2349                       "</th>\n";
2350         }
2351         print "<th></th>\n" .
2352               "</tr>\n";
2353         my $alternate = 1;
2354         foreach my $pr (@projects) {
2355                 if ($alternate) {
2356                         print "<tr class=\"dark\">\n";
2357                 } else {
2358                         print "<tr class=\"light\">\n";
2359                 }
2360                 $alternate ^= 1;
2361                 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
2362                                         -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
2363                       "<td>" . esc_html($pr->{'descr'}) . "</td>\n" .
2364                       "<td><i>" . chop_str($pr->{'owner'}, 15) . "</i></td>\n";
2365                 print "<td class=\"". age_class($pr->{'commit'}{'age'}) . "\">" .
2366                       $pr->{'commit'}{'age_string'} . "</td>\n" .
2367                       "<td class=\"link\">" .
2368                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary")   . " | " .
2369                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
2370                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
2371                       $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
2372                       "</td>\n" .
2373                       "</tr>\n";
2374         }
2375         print "</table>\n";
2376         git_footer_html();
2379 sub git_project_index {
2380         my @projects = git_get_projects_list();
2382         print $cgi->header(
2383                 -type => 'text/plain',
2384                 -charset => 'utf-8',
2385                 -content_disposition => 'inline; filename="index.aux"');
2387         foreach my $pr (@projects) {
2388                 if (!exists $pr->{'owner'}) {
2389                         $pr->{'owner'} = get_file_owner("$projectroot/$project");
2390                 }
2392                 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
2393                 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
2394                 $path  =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2395                 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
2396                 $path  =~ s/ /\+/g;
2397                 $owner =~ s/ /\+/g;
2399                 print "$path $owner\n";
2400         }
2403 sub git_summary {
2404         my $descr = git_get_project_description($project) || "none";
2405         my $head = git_get_head_hash($project);
2406         my %co = parse_commit($head);
2407         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2409         my $owner = git_get_project_owner($project);
2411         my ($reflist, $refs) = git_get_refs_list();
2413         my @taglist;
2414         my @headlist;
2415         foreach my $ref (@$reflist) {
2416                 if ($ref->{'name'} =~ s!^heads/!!) {
2417                         push @headlist, $ref;
2418                 } else {
2419                         $ref->{'name'} =~ s!^tags/!!;
2420                         push @taglist, $ref;
2421                 }
2422         }
2424         git_header_html();
2425         git_print_page_nav('summary','', $head);
2427         print "<div class=\"title\">&nbsp;</div>\n";
2428         print "<table cellspacing=\"0\">\n" .
2429               "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
2430               "<tr><td>owner</td><td>$owner</td></tr>\n" .
2431               "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
2432         # use per project git URL list in $projectroot/$project/cloneurl
2433         # or make project git URL from git base URL and project name
2434         my $url_tag = "URL";
2435         my @url_list = git_get_project_url_list($project);
2436         @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
2437         foreach my $git_url (@url_list) {
2438                 next unless $git_url;
2439                 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
2440                 $url_tag = "";
2441         }
2442         print "</table>\n";
2444         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=17",
2445                 git_get_head_hash($project)
2446                 or die_error(undef, "Open git-rev-list failed");
2447         my @revlist = map { chomp; $_ } <$fd>;
2448         close $fd;
2449         git_print_header_div('shortlog');
2450         git_shortlog_body(\@revlist, 0, 15, $refs,
2451                           $cgi->a({-href => href(action=>"shortlog")}, "..."));
2453         if (@taglist) {
2454                 git_print_header_div('tags');
2455                 git_tags_body(\@taglist, 0, 15,
2456                               $cgi->a({-href => href(action=>"tags")}, "..."));
2457         }
2459         if (@headlist) {
2460                 git_print_header_div('heads');
2461                 git_heads_body(\@headlist, $head, 0, 15,
2462                                $cgi->a({-href => href(action=>"heads")}, "..."));
2463         }
2465         git_footer_html();
2468 sub git_tag {
2469         my $head = git_get_head_hash($project);
2470         git_header_html();
2471         git_print_page_nav('','', $head,undef,$head);
2472         my %tag = parse_tag($hash);
2473         git_print_header_div('commit', esc_html($tag{'name'}), $hash);
2474         print "<div class=\"title_text\">\n" .
2475               "<table cellspacing=\"0\">\n" .
2476               "<tr>\n" .
2477               "<td>object</td>\n" .
2478               "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2479                                $tag{'object'}) . "</td>\n" .
2480               "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
2481                                               $tag{'type'}) . "</td>\n" .
2482               "</tr>\n";
2483         if (defined($tag{'author'})) {
2484                 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
2485                 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
2486                 print "<tr><td></td><td>" . $ad{'rfc2822'} .
2487                         sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
2488                         "</td></tr>\n";
2489         }
2490         print "</table>\n\n" .
2491               "</div>\n";
2492         print "<div class=\"page_body\">";
2493         my $comment = $tag{'comment'};
2494         foreach my $line (@$comment) {
2495                 print esc_html($line) . "<br/>\n";
2496         }
2497         print "</div>\n";
2498         git_footer_html();
2501 sub git_blame2 {
2502         my $fd;
2503         my $ftype;
2505         my ($have_blame) = gitweb_check_feature('blame');
2506         if (!$have_blame) {
2507                 die_error('403 Permission denied', "Permission denied");
2508         }
2509         die_error('404 Not Found', "File name not defined") if (!$file_name);
2510         $hash_base ||= git_get_head_hash($project);
2511         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2512         my %co = parse_commit($hash_base)
2513                 or die_error(undef, "Reading commit failed");
2514         if (!defined $hash) {
2515                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2516                         or die_error(undef, "Error looking up file");
2517         }
2518         $ftype = git_get_type($hash);
2519         if ($ftype !~ "blob") {
2520                 die_error("400 Bad Request", "Object is not a blob");
2521         }
2522         open ($fd, "-|", git_cmd(), "blame", '-l', '--', $file_name, $hash_base)
2523                 or die_error(undef, "Open git-blame failed");
2524         git_header_html();
2525         my $formats_nav =
2526                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2527                         "blob") .
2528                 " | " .
2529                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2530                         "history") .
2531                 " | " .
2532                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2533                         "HEAD");
2534         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2535         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2536         git_print_page_path($file_name, $ftype, $hash_base);
2537         my @rev_color = (qw(light2 dark2));
2538         my $num_colors = scalar(@rev_color);
2539         my $current_color = 0;
2540         my $last_rev;
2541         print <<HTML;
2542 <div class="page_body">
2543 <table class="blame">
2544 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
2545 HTML
2546         while (<$fd>) {
2547                 /^([0-9a-fA-F]{40}).*?(\d+)\)\s{1}(\s*.*)/;
2548                 my $full_rev = $1;
2549                 my $rev = substr($full_rev, 0, 8);
2550                 my $lineno = $2;
2551                 my $data = $3;
2553                 if (!defined $last_rev) {
2554                         $last_rev = $full_rev;
2555                 } elsif ($last_rev ne $full_rev) {
2556                         $last_rev = $full_rev;
2557                         $current_color = ++$current_color % $num_colors;
2558                 }
2559                 print "<tr class=\"$rev_color[$current_color]\">\n";
2560                 print "<td class=\"sha1\">" .
2561                         $cgi->a({-href => href(action=>"commit", hash=>$full_rev, file_name=>$file_name)},
2562                                 esc_html($rev)) . "</td>\n";
2563                 print "<td class=\"linenr\"><a id=\"l$lineno\" href=\"#l$lineno\" class=\"linenr\">" .
2564                       esc_html($lineno) . "</a></td>\n";
2565                 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
2566                 print "</tr>\n";
2567         }
2568         print "</table>\n";
2569         print "</div>";
2570         close $fd
2571                 or print "Reading blob failed\n";
2572         git_footer_html();
2575 sub git_blame {
2576         my $fd;
2578         my ($have_blame) = gitweb_check_feature('blame');
2579         if (!$have_blame) {
2580                 die_error('403 Permission denied', "Permission denied");
2581         }
2582         die_error('404 Not Found', "File name not defined") if (!$file_name);
2583         $hash_base ||= git_get_head_hash($project);
2584         die_error(undef, "Couldn't find base commit") unless ($hash_base);
2585         my %co = parse_commit($hash_base)
2586                 or die_error(undef, "Reading commit failed");
2587         if (!defined $hash) {
2588                 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
2589                         or die_error(undef, "Error lookup file");
2590         }
2591         open ($fd, "-|", git_cmd(), "annotate", '-l', '-t', '-r', $file_name, $hash_base)
2592                 or die_error(undef, "Open git-annotate failed");
2593         git_header_html();
2594         my $formats_nav =
2595                 $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2596                         "blob") .
2597                 " | " .
2598                 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
2599                         "history") .
2600                 " | " .
2601                 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
2602                         "HEAD");
2603         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2604         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2605         git_print_page_path($file_name, 'blob', $hash_base);
2606         print "<div class=\"page_body\">\n";
2607         print <<HTML;
2608 <table class="blame">
2609   <tr>
2610     <th>Commit</th>
2611     <th>Age</th>
2612     <th>Author</th>
2613     <th>Line</th>
2614     <th>Data</th>
2615   </tr>
2616 HTML
2617         my @line_class = (qw(light dark));
2618         my $line_class_len = scalar (@line_class);
2619         my $line_class_num = $#line_class;
2620         while (my $line = <$fd>) {
2621                 my $long_rev;
2622                 my $short_rev;
2623                 my $author;
2624                 my $time;
2625                 my $lineno;
2626                 my $data;
2627                 my $age;
2628                 my $age_str;
2629                 my $age_class;
2631                 chomp $line;
2632                 $line_class_num = ($line_class_num + 1) % $line_class_len;
2634                 if ($line =~ m/^([0-9a-fA-F]{40})\t\(\s*([^\t]+)\t(\d+) [+-]\d\d\d\d\t(\d+)\)(.*)$/) {
2635                         $long_rev = $1;
2636                         $author   = $2;
2637                         $time     = $3;
2638                         $lineno   = $4;
2639                         $data     = $5;
2640                 } else {
2641                         print qq(  <tr><td colspan="5" class="error">Unable to parse: $line</td></tr>\n);
2642                         next;
2643                 }
2644                 $short_rev  = substr ($long_rev, 0, 8);
2645                 $age        = time () - $time;
2646                 $age_str    = age_string ($age);
2647                 $age_str    =~ s/ /&nbsp;/g;
2648                 $age_class  = age_class($age);
2649                 $author     = esc_html ($author);
2650                 $author     =~ s/ /&nbsp;/g;
2652                 $data = untabify($data);
2653                 $data = esc_html ($data);
2655                 print <<HTML;
2656   <tr class="$line_class[$line_class_num]">
2657     <td class="sha1"><a href="${\href (action=>"commit", hash=>$long_rev)}" class="text">$short_rev..</a></td>
2658     <td class="$age_class">$age_str</td>
2659     <td>$author</td>
2660     <td class="linenr"><a id="$lineno" href="#$lineno" class="linenr">$lineno</a></td>
2661     <td class="pre">$data</td>
2662   </tr>
2663 HTML
2664         } # while (my $line = <$fd>)
2665         print "</table>\n\n";
2666         close $fd
2667                 or print "Reading blob failed.\n";
2668         print "</div>";
2669         git_footer_html();
2672 sub git_tags {
2673         my $head = git_get_head_hash($project);
2674         git_header_html();
2675         git_print_page_nav('','', $head,undef,$head);
2676         git_print_header_div('summary', $project);
2678         my ($taglist) = git_get_refs_list("tags");
2679         if (@$taglist) {
2680                 git_tags_body($taglist);
2681         }
2682         git_footer_html();
2685 sub git_heads {
2686         my $head = git_get_head_hash($project);
2687         git_header_html();
2688         git_print_page_nav('','', $head,undef,$head);
2689         git_print_header_div('summary', $project);
2691         my ($headlist) = git_get_refs_list("heads");
2692         if (@$headlist) {
2693                 git_heads_body($headlist, $head);
2694         }
2695         git_footer_html();
2698 sub git_blob_plain {
2699         my $expires;
2701         if (!defined $hash) {
2702                 if (defined $file_name) {
2703                         my $base = $hash_base || git_get_head_hash($project);
2704                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2705                                 or die_error(undef, "Error lookup file");
2706                 } else {
2707                         die_error(undef, "No file name defined");
2708                 }
2709         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2710                 # blobs defined by non-textual hash id's can be cached
2711                 $expires = "+1d";
2712         }
2714         my $type = shift;
2715         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2716                 or die_error(undef, "Couldn't cat $file_name, $hash");
2718         $type ||= blob_mimetype($fd, $file_name);
2720         # save as filename, even when no $file_name is given
2721         my $save_as = "$hash";
2722         if (defined $file_name) {
2723                 $save_as = $file_name;
2724         } elsif ($type =~ m/^text\//) {
2725                 $save_as .= '.txt';
2726         }
2728         print $cgi->header(
2729                 -type => "$type",
2730                 -expires=>$expires,
2731                 -content_disposition => 'inline; filename="' . "$save_as" . '"');
2732         undef $/;
2733         binmode STDOUT, ':raw';
2734         print <$fd>;
2735         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2736         $/ = "\n";
2737         close $fd;
2740 sub git_blob {
2741         my $expires;
2743         if (!defined $hash) {
2744                 if (defined $file_name) {
2745                         my $base = $hash_base || git_get_head_hash($project);
2746                         $hash = git_get_hash_by_path($base, $file_name, "blob")
2747                                 or die_error(undef, "Error lookup file");
2748                 } else {
2749                         die_error(undef, "No file name defined");
2750                 }
2751         } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2752                 # blobs defined by non-textual hash id's can be cached
2753                 $expires = "+1d";
2754         }
2756         my ($have_blame) = gitweb_check_feature('blame');
2757         open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2758                 or die_error(undef, "Couldn't cat $file_name, $hash");
2759         my $mimetype = blob_mimetype($fd, $file_name);
2760         if ($mimetype !~ m/^text\//) {
2761                 close $fd;
2762                 return git_blob_plain($mimetype);
2763         }
2764         git_header_html(undef, $expires);
2765         my $formats_nav = '';
2766         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2767                 if (defined $file_name) {
2768                         if ($have_blame) {
2769                                 $formats_nav .=
2770                                         $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
2771                                                                hash=>$hash, file_name=>$file_name)},
2772                                                 "blame") .
2773                                         " | ";
2774                         }
2775                         $formats_nav .=
2776                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2777                                                        hash=>$hash, file_name=>$file_name)},
2778                                         "history") .
2779                                 " | " .
2780                                 $cgi->a({-href => href(action=>"blob_plain",
2781                                                        hash=>$hash, file_name=>$file_name)},
2782                                         "raw") .
2783                                 " | " .
2784                                 $cgi->a({-href => href(action=>"blob",
2785                                                        hash_base=>"HEAD", file_name=>$file_name)},
2786                                         "HEAD");
2787                 } else {
2788                         $formats_nav .=
2789                                 $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
2790                 }
2791                 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
2792                 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
2793         } else {
2794                 print "<div class=\"page_nav\">\n" .
2795                       "<br/><br/></div>\n" .
2796                       "<div class=\"title\">$hash</div>\n";
2797         }
2798         git_print_page_path($file_name, "blob", $hash_base);
2799         print "<div class=\"page_body\">\n";
2800         my $nr;
2801         while (my $line = <$fd>) {
2802                 chomp $line;
2803                 $nr++;
2804                 $line = untabify($line);
2805                 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
2806                        $nr, $nr, $nr, esc_html($line);
2807         }
2808         close $fd
2809                 or print "Reading blob failed.\n";
2810         print "</div>";
2811         git_footer_html();
2814 sub git_tree {
2815         my $have_snapshot = gitweb_have_snapshot();
2817         if (!defined $hash_base) {
2818                 $hash_base = "HEAD";
2819         }
2820         if (!defined $hash) {
2821                 if (defined $file_name) {
2822                         $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
2823                 } else {
2824                         $hash = $hash_base;
2825                 }
2826         }
2827         $/ = "\0";
2828         open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
2829                 or die_error(undef, "Open git-ls-tree failed");
2830         my @entries = map { chomp; $_ } <$fd>;
2831         close $fd or die_error(undef, "Reading tree failed");
2832         $/ = "\n";
2834         my $refs = git_get_references();
2835         my $ref = format_ref_marker($refs, $hash_base);
2836         git_header_html();
2837         my $base = "";
2838         my ($have_blame) = gitweb_check_feature('blame');
2839         if (defined $hash_base && (my %co = parse_commit($hash_base))) {
2840                 my @views_nav = ();
2841                 if (defined $file_name) {
2842                         push @views_nav,
2843                                 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
2844                                                        hash=>$hash, file_name=>$file_name)},
2845                                         "history"),
2846                                 $cgi->a({-href => href(action=>"tree",
2847                                                        hash_base=>"HEAD", file_name=>$file_name)},
2848                                         "HEAD"),
2849                 }
2850                 if ($have_snapshot) {
2851                         # FIXME: Should be available when we have no hash base as well.
2852                         push @views_nav,
2853                                 $cgi->a({-href => href(action=>"snapshot", hash=>$hash)},
2854                                         "snapshot");
2855                 }
2856                 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
2857                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
2858         } else {
2859                 undef $hash_base;
2860                 print "<div class=\"page_nav\">\n";
2861                 print "<br/><br/></div>\n";
2862                 print "<div class=\"title\">$hash</div>\n";
2863         }
2864         if (defined $file_name) {
2865                 $base = esc_html("$file_name/");
2866         }
2867         git_print_page_path($file_name, 'tree', $hash_base);
2868         print "<div class=\"page_body\">\n";
2869         print "<table cellspacing=\"0\">\n";
2870         my $alternate = 1;
2871         foreach my $line (@entries) {
2872                 my %t = parse_ls_tree_line($line, -z => 1);
2874                 if ($alternate) {
2875                         print "<tr class=\"dark\">\n";
2876                 } else {
2877                         print "<tr class=\"light\">\n";
2878                 }
2879                 $alternate ^= 1;
2881                 git_print_tree_entry(\%t, $base, $hash_base, $have_blame);
2883                 print "</tr>\n";
2884         }
2885         print "</table>\n" .
2886               "</div>";
2887         git_footer_html();
2890 sub git_snapshot {
2891         my ($ctype, $suffix, $command) = gitweb_check_feature('snapshot');
2892         my $have_snapshot = (defined $ctype && defined $suffix);
2893         if (!$have_snapshot) {
2894                 die_error('403 Permission denied', "Permission denied");
2895         }
2897         if (!defined $hash) {
2898                 $hash = git_get_head_hash($project);
2899         }
2901         my $filename = basename($project) . "-$hash.tar.$suffix";
2903         print $cgi->header(
2904                 -type => 'application/x-tar',
2905                 -content_encoding => $ctype,
2906                 -content_disposition => 'inline; filename="' . "$filename" . '"',
2907                 -status => '200 OK');
2909         my $git = git_cmd_str();
2910         my $name = $project;
2911         $name =~ s/\047/\047\\\047\047/g;
2912         open my $fd, "-|",
2913         "$git archive --format=tar --prefix=\'$name\'/ $hash | $command"
2914                 or die_error(undef, "Execute git-tar-tree failed.");
2915         binmode STDOUT, ':raw';
2916         print <$fd>;
2917         binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
2918         close $fd;
2922 sub git_log {
2923         my $head = git_get_head_hash($project);
2924         if (!defined $hash) {
2925                 $hash = $head;
2926         }
2927         if (!defined $page) {
2928                 $page = 0;
2929         }
2930         my $refs = git_get_references();
2932         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
2933         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
2934                 or die_error(undef, "Open git-rev-list failed");
2935         my @revlist = map { chomp; $_ } <$fd>;
2936         close $fd;
2938         my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#revlist);
2940         git_header_html();
2941         git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
2943         if (!@revlist) {
2944                 my %co = parse_commit($hash);
2946                 git_print_header_div('summary', $project);
2947                 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
2948         }
2949         for (my $i = ($page * 100); $i <= $#revlist; $i++) {
2950                 my $commit = $revlist[$i];
2951                 my $ref = format_ref_marker($refs, $commit);
2952                 my %co = parse_commit($commit);
2953                 next if !%co;
2954                 my %ad = parse_date($co{'author_epoch'});
2955                 git_print_header_div('commit',
2956                                "<span class=\"age\">$co{'age_string'}</span>" .
2957                                esc_html($co{'title'}) . $ref,
2958                                $commit);
2959                 print "<div class=\"title_text\">\n" .
2960                       "<div class=\"log_link\">\n" .
2961                       $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
2962                       " | " .
2963                       $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
2964                       " | " .
2965                       $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
2966                       "<br/>\n" .
2967                       "</div>\n" .
2968                       "<i>" . esc_html($co{'author_name'}) .  " [$ad{'rfc2822'}]</i><br/>\n" .
2969                       "</div>\n";
2971                 print "<div class=\"log_body\">\n";
2972                 git_print_simplified_log($co{'comment'});
2973                 print "</div>\n";
2974         }
2975         git_footer_html();
2978 sub git_commit {
2979         my %co = parse_commit($hash);
2980         if (!%co) {
2981                 die_error(undef, "Unknown commit object");
2982         }
2983         my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
2984         my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
2986         my $parent = $co{'parent'};
2987         if (!defined $parent) {
2988                 $parent = "--root";
2989         }
2990         open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $parent, $hash
2991                 or die_error(undef, "Open git-diff-tree failed");
2992         my @difftree = map { chomp; $_ } <$fd>;
2993         close $fd or die_error(undef, "Reading git-diff-tree failed");
2995         # non-textual hash id's can be cached
2996         my $expires;
2997         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
2998                 $expires = "+1d";
2999         }
3000         my $refs = git_get_references();
3001         my $ref = format_ref_marker($refs, $co{'id'});
3003         my $have_snapshot = gitweb_have_snapshot();
3005         my @views_nav = ();
3006         if (defined $file_name && defined $co{'parent'}) {
3007                 push @views_nav,
3008                         $cgi->a({-href => href(action=>"blame", hash_parent=>$parent, file_name=>$file_name)},
3009                                 "blame");
3010         }
3011         git_header_html(undef, $expires);
3012         git_print_page_nav('commit', '',
3013                            $hash, $co{'tree'}, $hash,
3014                            join (' | ', @views_nav));
3016         if (defined $co{'parent'}) {
3017                 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
3018         } else {
3019                 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
3020         }
3021         print "<div class=\"title_text\">\n" .
3022               "<table cellspacing=\"0\">\n";
3023         print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
3024               "<tr>" .
3025               "<td></td><td> $ad{'rfc2822'}";
3026         if ($ad{'hour_local'} < 6) {
3027                 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3028                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3029         } else {
3030                 printf(" (%02d:%02d %s)",
3031                        $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
3032         }
3033         print "</td>" .
3034               "</tr>\n";
3035         print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
3036         print "<tr><td></td><td> $cd{'rfc2822'}" .
3037               sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
3038               "</td></tr>\n";
3039         print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
3040         print "<tr>" .
3041               "<td>tree</td>" .
3042               "<td class=\"sha1\">" .
3043               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
3044                        class => "list"}, $co{'tree'}) .
3045               "</td>" .
3046               "<td class=\"link\">" .
3047               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
3048                       "tree");
3049         if ($have_snapshot) {
3050                 print " | " .
3051                       $cgi->a({-href => href(action=>"snapshot", hash=>$hash)}, "snapshot");
3052         }
3053         print "</td>" .
3054               "</tr>\n";
3055         my $parents = $co{'parents'};
3056         foreach my $par (@$parents) {
3057                 print "<tr>" .
3058                       "<td>parent</td>" .
3059                       "<td class=\"sha1\">" .
3060                       $cgi->a({-href => href(action=>"commit", hash=>$par),
3061                                class => "list"}, $par) .
3062                       "</td>" .
3063                       "<td class=\"link\">" .
3064                       $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
3065                       " | " .
3066                       $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
3067                       "</td>" .
3068                       "</tr>\n";
3069         }
3070         print "</table>".
3071               "</div>\n";
3073         print "<div class=\"page_body\">\n";
3074         git_print_log($co{'comment'});
3075         print "</div>\n";
3077         git_difftree_body(\@difftree, $hash, $parent);
3079         git_footer_html();
3082 sub git_blobdiff {
3083         my $format = shift || 'html';
3085         my $fd;
3086         my @difftree;
3087         my %diffinfo;
3088         my $expires;
3090         # preparing $fd and %diffinfo for git_patchset_body
3091         # new style URI
3092         if (defined $hash_base && defined $hash_parent_base) {
3093                 if (defined $file_name) {
3094                         # read raw output
3095                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base,
3096                                 "--", $file_name
3097                                 or die_error(undef, "Open git-diff-tree failed");
3098                         @difftree = map { chomp; $_ } <$fd>;
3099                         close $fd
3100                                 or die_error(undef, "Reading git-diff-tree failed");
3101                         @difftree
3102                                 or die_error('404 Not Found', "Blob diff not found");
3104                 } elsif (defined $hash &&
3105                          $hash =~ /[0-9a-fA-F]{40}/) {
3106                         # try to find filename from $hash
3108                         # read filtered raw output
3109                         open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts, $hash_parent_base, $hash_base
3110                                 or die_error(undef, "Open git-diff-tree failed");
3111                         @difftree =
3112                                 # ':100644 100644 03b21826... 3b93d5e7... M     ls-files.c'
3113                                 # $hash == to_id
3114                                 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
3115                                 map { chomp; $_ } <$fd>;
3116                         close $fd
3117                                 or die_error(undef, "Reading git-diff-tree failed");
3118                         @difftree
3119                                 or die_error('404 Not Found', "Blob diff not found");
3121                 } else {
3122                         die_error('404 Not Found', "Missing one of the blob diff parameters");
3123                 }
3125                 if (@difftree > 1) {
3126                         die_error('404 Not Found', "Ambiguous blob diff specification");
3127                 }
3129                 %diffinfo = parse_difftree_raw_line($difftree[0]);
3130                 $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
3131                 $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
3133                 $hash_parent ||= $diffinfo{'from_id'};
3134                 $hash        ||= $diffinfo{'to_id'};
3136                 # non-textual hash id's can be cached
3137                 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
3138                     $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
3139                         $expires = '+1d';
3140                 }
3142                 # open patch output
3143                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3144                         '-p', $hash_parent_base, $hash_base,
3145                         "--", $file_name
3146                         or die_error(undef, "Open git-diff-tree failed");
3147         }
3149         # old/legacy style URI
3150         if (!%diffinfo && # if new style URI failed
3151             defined $hash && defined $hash_parent) {
3152                 # fake git-diff-tree raw output
3153                 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
3154                 $diffinfo{'from_id'} = $hash_parent;
3155                 $diffinfo{'to_id'}   = $hash;
3156                 if (defined $file_name) {
3157                         if (defined $file_parent) {
3158                                 $diffinfo{'status'} = '2';
3159                                 $diffinfo{'from_file'} = $file_parent;
3160                                 $diffinfo{'to_file'}   = $file_name;
3161                         } else { # assume not renamed
3162                                 $diffinfo{'status'} = '1';
3163                                 $diffinfo{'from_file'} = $file_name;
3164                                 $diffinfo{'to_file'}   = $file_name;
3165                         }
3166                 } else { # no filename given
3167                         $diffinfo{'status'} = '2';
3168                         $diffinfo{'from_file'} = $hash_parent;
3169                         $diffinfo{'to_file'}   = $hash;
3170                 }
3172                 # non-textual hash id's can be cached
3173                 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
3174                     $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
3175                         $expires = '+1d';
3176                 }
3178                 # open patch output
3179                 open $fd, "-|", git_cmd(), "diff", '-p', @diff_opts, $hash_parent, $hash
3180                         or die_error(undef, "Open git-diff failed");
3181         } else  {
3182                 die_error('404 Not Found', "Missing one of the blob diff parameters")
3183                         unless %diffinfo;
3184         }
3186         # header
3187         if ($format eq 'html') {
3188                 my $formats_nav =
3189                         $cgi->a({-href => href(action=>"blobdiff_plain",
3190                                                hash=>$hash, hash_parent=>$hash_parent,
3191                                                hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
3192                                                file_name=>$file_name, file_parent=>$file_parent)},
3193                                 "raw");
3194                 git_header_html(undef, $expires);
3195                 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
3196                         git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
3197                         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3198                 } else {
3199                         print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
3200                         print "<div class=\"title\">$hash vs $hash_parent</div>\n";
3201                 }
3202                 if (defined $file_name) {
3203                         git_print_page_path($file_name, "blob", $hash_base);
3204                 } else {
3205                         print "<div class=\"page_path\"></div>\n";
3206                 }
3208         } elsif ($format eq 'plain') {
3209                 print $cgi->header(
3210                         -type => 'text/plain',
3211                         -charset => 'utf-8',
3212                         -expires => $expires,
3213                         -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
3215                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3217         } else {
3218                 die_error(undef, "Unknown blobdiff format");
3219         }
3221         # patch
3222         if ($format eq 'html') {
3223                 print "<div class=\"page_body\">\n";
3225                 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
3226                 close $fd;
3228                 print "</div>\n"; # class="page_body"
3229                 git_footer_html();
3231         } else {
3232                 while (my $line = <$fd>) {
3233                         $line =~ s!a/($hash|$hash_parent)!'a/'.esc_html($diffinfo{'from_file'})!eg;
3234                         $line =~ s!b/($hash|$hash_parent)!'b/'.esc_html($diffinfo{'to_file'})!eg;
3236                         print $line;
3238                         last if $line =~ m!^\+\+\+!;
3239                 }
3240                 local $/ = undef;
3241                 print <$fd>;
3242                 close $fd;
3243         }
3246 sub git_blobdiff_plain {
3247         git_blobdiff('plain');
3250 sub git_commitdiff {
3251         my $format = shift || 'html';
3252         my %co = parse_commit($hash);
3253         if (!%co) {
3254                 die_error(undef, "Unknown commit object");
3255         }
3256         if (!defined $hash_parent) {
3257                 $hash_parent = $co{'parent'} || '--root';
3258         }
3260         # read commitdiff
3261         my $fd;
3262         my @difftree;
3263         if ($format eq 'html') {
3264                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3265                         "--patch-with-raw", "--full-index", $hash_parent, $hash
3266                         or die_error(undef, "Open git-diff-tree failed");
3268                 while (chomp(my $line = <$fd>)) {
3269                         # empty line ends raw part of diff-tree output
3270                         last unless $line;
3271                         push @difftree, $line;
3272                 }
3274         } elsif ($format eq 'plain') {
3275                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3276                         '-p', $hash_parent, $hash
3277                         or die_error(undef, "Open git-diff-tree failed");
3279         } else {
3280                 die_error(undef, "Unknown commitdiff format");
3281         }
3283         # non-textual hash id's can be cached
3284         my $expires;
3285         if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
3286                 $expires = "+1d";
3287         }
3289         # write commit message
3290         if ($format eq 'html') {
3291                 my $refs = git_get_references();
3292                 my $ref = format_ref_marker($refs, $co{'id'});
3293                 my $formats_nav =
3294                         $cgi->a({-href => href(action=>"commitdiff_plain",
3295                                                hash=>$hash, hash_parent=>$hash_parent)},
3296                                 "raw");
3298                 git_header_html(undef, $expires);
3299                 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
3300                 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
3301                 git_print_authorship(\%co);
3302                 print "<div class=\"page_body\">\n";
3303                 print "<div class=\"log\">\n";
3304                 git_print_simplified_log($co{'comment'}, 1); # skip title
3305                 print "</div>\n"; # class="log"
3307         } elsif ($format eq 'plain') {
3308                 my $refs = git_get_references("tags");
3309                 my $tagname = git_get_rev_name_tags($hash);
3310                 my $filename = basename($project) . "-$hash.patch";
3312                 print $cgi->header(
3313                         -type => 'text/plain',
3314                         -charset => 'utf-8',
3315                         -expires => $expires,
3316                         -content_disposition => 'inline; filename="' . "$filename" . '"');
3317                 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
3318                 print <<TEXT;
3319 From: $co{'author'}
3320 Date: $ad{'rfc2822'} ($ad{'tz_local'})
3321 Subject: $co{'title'}
3322 TEXT
3323                 print "X-Git-Tag: $tagname\n" if $tagname;
3324                 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
3326                 foreach my $line (@{$co{'comment'}}) {
3327                         print "$line\n";
3328                 }
3329                 print "---\n\n";
3330         }
3332         # write patch
3333         if ($format eq 'html') {
3334                 git_difftree_body(\@difftree, $hash, $hash_parent);
3335                 print "<br/>\n";
3337                 git_patchset_body($fd, \@difftree, $hash, $hash_parent);
3338                 close $fd;
3339                 print "</div>\n"; # class="page_body"
3340                 git_footer_html();
3342         } elsif ($format eq 'plain') {
3343                 local $/ = undef;
3344                 print <$fd>;
3345                 close $fd
3346                         or print "Reading git-diff-tree failed\n";
3347         }
3350 sub git_commitdiff_plain {
3351         git_commitdiff('plain');
3354 sub git_history {
3355         if (!defined $hash_base) {
3356                 $hash_base = git_get_head_hash($project);
3357         }
3358         if (!defined $page) {
3359                 $page = 0;
3360         }
3361         my $ftype;
3362         my %co = parse_commit($hash_base);
3363         if (!%co) {
3364                 die_error(undef, "Unknown commit object");
3365         }
3367         my $refs = git_get_references();
3368         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3370         if (!defined $hash && defined $file_name) {
3371                 $hash = git_get_hash_by_path($hash_base, $file_name);
3372         }
3373         if (defined $hash) {
3374                 $ftype = git_get_type($hash);
3375         }
3377         open my $fd, "-|",
3378                 git_cmd(), "rev-list", $limit, "--full-history", $hash_base, "--", $file_name
3379                         or die_error(undef, "Open git-rev-list-failed");
3380         my @revlist = map { chomp; $_ } <$fd>;
3381         close $fd
3382                 or die_error(undef, "Reading git-rev-list failed");
3384         my $paging_nav = '';
3385         if ($page > 0) {
3386                 $paging_nav .=
3387                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3388                                                file_name=>$file_name)},
3389                                 "first");
3390                 $paging_nav .= " &sdot; " .
3391                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3392                                                file_name=>$file_name, page=>$page-1),
3393                                  -accesskey => "p", -title => "Alt-p"}, "prev");
3394         } else {
3395                 $paging_nav .= "first";
3396                 $paging_nav .= " &sdot; prev";
3397         }
3398         if ($#revlist >= (100 * ($page+1)-1)) {
3399                 $paging_nav .= " &sdot; " .
3400                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3401                                                file_name=>$file_name, page=>$page+1),
3402                                  -accesskey => "n", -title => "Alt-n"}, "next");
3403         } else {
3404                 $paging_nav .= " &sdot; next";
3405         }
3406         my $next_link = '';
3407         if ($#revlist >= (100 * ($page+1)-1)) {
3408                 $next_link =
3409                         $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
3410                                                file_name=>$file_name, page=>$page+1),
3411                                  -title => "Alt-n"}, "next");
3412         }
3414         git_header_html();
3415         git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
3416         git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
3417         git_print_page_path($file_name, $ftype, $hash_base);
3419         git_history_body(\@revlist, ($page * 100), $#revlist,
3420                          $refs, $hash_base, $ftype, $next_link);
3422         git_footer_html();
3425 sub git_search {
3426         if (!defined $searchtext) {
3427                 die_error(undef, "Text field empty");
3428         }
3429         if (!defined $hash) {
3430                 $hash = git_get_head_hash($project);
3431         }
3432         my %co = parse_commit($hash);
3433         if (!%co) {
3434                 die_error(undef, "Unknown commit object");
3435         }
3437         my $commit_search = 1;
3438         my $author_search = 0;
3439         my $committer_search = 0;
3440         my $pickaxe_search = 0;
3441         if ($searchtext =~ s/^author\\://i) {
3442                 $author_search = 1;
3443         } elsif ($searchtext =~ s/^committer\\://i) {
3444                 $committer_search = 1;
3445         } elsif ($searchtext =~ s/^pickaxe\\://i) {
3446                 $commit_search = 0;
3447                 $pickaxe_search = 1;
3449                 # pickaxe may take all resources of your box and run for several minutes
3450                 # with every query - so decide by yourself how public you make this feature
3451                 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
3452                 if (!$have_pickaxe) {
3453                         die_error('403 Permission denied', "Permission denied");
3454                 }
3455         }
3456         git_header_html();
3457         git_print_page_nav('','', $hash,$co{'tree'},$hash);
3458         git_print_header_div('commit', esc_html($co{'title'}), $hash);
3460         print "<table cellspacing=\"0\">\n";
3461         my $alternate = 1;
3462         if ($commit_search) {
3463                 $/ = "\0";
3464                 open my $fd, "-|", git_cmd(), "rev-list", "--header", "--parents", $hash or next;
3465                 while (my $commit_text = <$fd>) {
3466                         if (!grep m/$searchtext/i, $commit_text) {
3467                                 next;
3468                         }
3469                         if ($author_search && !grep m/\nauthor .*$searchtext/i, $commit_text) {
3470                                 next;
3471                         }
3472                         if ($committer_search && !grep m/\ncommitter .*$searchtext/i, $commit_text) {
3473                                 next;
3474                         }
3475                         my @commit_lines = split "\n", $commit_text;
3476                         my %co = parse_commit(undef, \@commit_lines);
3477                         if (!%co) {
3478                                 next;
3479                         }
3480                         if ($alternate) {
3481                                 print "<tr class=\"dark\">\n";
3482                         } else {
3483                                 print "<tr class=\"light\">\n";
3484                         }
3485                         $alternate ^= 1;
3486                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3487                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3488                               "<td>" .
3489                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
3490                                        esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3491                         my $comment = $co{'comment'};
3492                         foreach my $line (@$comment) {
3493                                 if ($line =~ m/^(.*)($searchtext)(.*)$/i) {
3494                                         my $lead = esc_html($1) || "";
3495                                         $lead = chop_str($lead, 30, 10);
3496                                         my $match = esc_html($2) || "";
3497                                         my $trail = esc_html($3) || "";
3498                                         $trail = chop_str($trail, 30, 10);
3499                                         my $text = "$lead<span class=\"match\">$match</span>$trail";
3500                                         print chop_str($text, 80, 5) . "<br/>\n";
3501                                 }
3502                         }
3503                         print "</td>\n" .
3504                               "<td class=\"link\">" .
3505                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3506                               " | " .
3507                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3508                         print "</td>\n" .
3509                               "</tr>\n";
3510                 }
3511                 close $fd;
3512         }
3514         if ($pickaxe_search) {
3515                 $/ = "\n";
3516                 my $git_command = git_cmd_str();
3517                 open my $fd, "-|", "$git_command rev-list $hash | " .
3518                         "$git_command diff-tree -r --stdin -S\'$searchtext\'";
3519                 undef %co;
3520                 my @files;
3521                 while (my $line = <$fd>) {
3522                         if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
3523                                 my %set;
3524                                 $set{'file'} = $6;
3525                                 $set{'from_id'} = $3;
3526                                 $set{'to_id'} = $4;
3527                                 $set{'id'} = $set{'to_id'};
3528                                 if ($set{'id'} =~ m/0{40}/) {
3529                                         $set{'id'} = $set{'from_id'};
3530                                 }
3531                                 if ($set{'id'} =~ m/0{40}/) {
3532                                         next;
3533                                 }
3534                                 push @files, \%set;
3535                         } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
3536                                 if (%co) {
3537                                         if ($alternate) {
3538                                                 print "<tr class=\"dark\">\n";
3539                                         } else {
3540                                                 print "<tr class=\"light\">\n";
3541                                         }
3542                                         $alternate ^= 1;
3543                                         print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3544                                               "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
3545                                               "<td>" .
3546                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3547                                                       -class => "list subject"},
3548                                                       esc_html(chop_str($co{'title'}, 50)) . "<br/>");
3549                                         while (my $setref = shift @files) {
3550                                                 my %set = %$setref;
3551                                                 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
3552                                                                              hash=>$set{'id'}, file_name=>$set{'file'}),
3553                                                               -class => "list"},
3554                                                               "<span class=\"match\">" . esc_html($set{'file'}) . "</span>") .
3555                                                       "<br/>\n";
3556                                         }
3557                                         print "</td>\n" .
3558                                               "<td class=\"link\">" .
3559                                               $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3560                                               " | " .
3561                                               $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3562                                         print "</td>\n" .
3563                                               "</tr>\n";
3564                                 }
3565                                 %co = parse_commit($1);
3566                         }
3567                 }
3568                 close $fd;
3569         }
3570         print "</table>\n";
3571         git_footer_html();
3574 sub git_shortlog {
3575         my $head = git_get_head_hash($project);
3576         if (!defined $hash) {
3577                 $hash = $head;
3578         }
3579         if (!defined $page) {
3580                 $page = 0;
3581         }
3582         my $refs = git_get_references();
3584         my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
3585         open my $fd, "-|", git_cmd(), "rev-list", $limit, $hash
3586                 or die_error(undef, "Open git-rev-list failed");
3587         my @revlist = map { chomp; $_ } <$fd>;
3588         close $fd;
3590         my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#revlist);
3591         my $next_link = '';
3592         if ($#revlist >= (100 * ($page+1)-1)) {
3593                 $next_link =
3594                         $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
3595                                  -title => "Alt-n"}, "next");
3596         }
3599         git_header_html();
3600         git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
3601         git_print_header_div('summary', $project);
3603         git_shortlog_body(\@revlist, ($page * 100), $#revlist, $refs, $next_link);
3605         git_footer_html();
3608 ## ......................................................................
3609 ## feeds (RSS, OPML)
3611 sub git_rss {
3612         # http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
3613         open my $fd, "-|", git_cmd(), "rev-list", "--max-count=150", git_get_head_hash($project)
3614                 or die_error(undef, "Open git-rev-list failed");
3615         my @revlist = map { chomp; $_ } <$fd>;
3616         close $fd or die_error(undef, "Reading git-rev-list failed");
3617         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3618         print <<XML;
3619 <?xml version="1.0" encoding="utf-8"?>
3620 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
3621 <channel>
3622 <title>$project $my_uri $my_url</title>
3623 <link>${\esc_html("$my_url?p=$project;a=summary")}</link>
3624 <description>$project log</description>
3625 <language>en</language>
3626 XML
3628         for (my $i = 0; $i <= $#revlist; $i++) {
3629                 my $commit = $revlist[$i];
3630                 my %co = parse_commit($commit);
3631                 # we read 150, we always show 30 and the ones more recent than 48 hours
3632                 if (($i >= 20) && ((time - $co{'committer_epoch'}) > 48*60*60)) {
3633                         last;
3634                 }
3635                 my %cd = parse_date($co{'committer_epoch'});
3636                 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
3637                         $co{'parent'}, $co{'id'}
3638                         or next;
3639                 my @difftree = map { chomp; $_ } <$fd>;
3640                 close $fd
3641                         or next;
3642                 print "<item>\n" .
3643                       "<title>" .
3644                       sprintf("%d %s %02d:%02d", $cd{'mday'}, $cd{'month'}, $cd{'hour'}, $cd{'minute'}) . " - " . esc_html($co{'title'}) .
3645                       "</title>\n" .
3646                       "<author>" . esc_html($co{'author'}) . "</author>\n" .
3647                       "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
3648                       "<guid isPermaLink=\"true\">" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</guid>\n" .
3649                       "<link>" . esc_html("$my_url?p=$project;a=commit;h=$commit") . "</link>\n" .
3650                       "<description>" . esc_html($co{'title'}) . "</description>\n" .
3651                       "<content:encoded>" .
3652                       "<![CDATA[\n";
3653                 my $comment = $co{'comment'};
3654                 foreach my $line (@$comment) {
3655                         $line = to_utf8($line);
3656                         print "$line<br/>\n";
3657                 }
3658                 print "<br/>\n";
3659                 foreach my $line (@difftree) {
3660                         if (!($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/)) {
3661                                 next;
3662                         }
3663                         my $file = esc_html(unquote($7));
3664                         $file = to_utf8($file);
3665                         print "$file<br/>\n";
3666                 }
3667                 print "]]>\n" .
3668                       "</content:encoded>\n" .
3669                       "</item>\n";
3670         }
3671         print "</channel></rss>";
3674 sub git_opml {
3675         my @list = git_get_projects_list();
3677         print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
3678         print <<XML;
3679 <?xml version="1.0" encoding="utf-8"?>
3680 <opml version="1.0">
3681 <head>
3682   <title>$site_name Git OPML Export</title>
3683 </head>
3684 <body>
3685 <outline text="git RSS feeds">
3686 XML
3688         foreach my $pr (@list) {
3689                 my %proj = %$pr;
3690                 my $head = git_get_head_hash($proj{'path'});
3691                 if (!defined $head) {
3692                         next;
3693                 }
3694                 $git_dir = "$projectroot/$proj{'path'}";
3695                 my %co = parse_commit($head);
3696                 if (!%co) {
3697                         next;
3698                 }
3700                 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
3701                 my $rss  = "$my_url?p=$proj{'path'};a=rss";
3702                 my $html = "$my_url?p=$proj{'path'};a=summary";
3703                 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
3704         }
3705         print <<XML;
3706 </outline>
3707 </body>
3708 </opml>
3709 XML