Cleanup - Fixing insert_file so that it properly returns a string
[git/gitweb-warthdog9.git] / gitweb / gitweb.perl
blob3eb44f8eb1df2ab5220820b75f3325e25905f080
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
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::Path qw(make_path remove_tree);
19 use File::Basename qw(basename);
20 use Digest::MD5 qw(md5 md5_hex md5_base64);
21 use Fcntl ':flock';
22 use IPC::Open2;
23 binmode STDOUT, ':utf8';
25 BEGIN {
26 CGI->compile() if $ENV{'MOD_PERL'};
29 our $cgi = new CGI;
30 our $version = "++GIT_VERSION++";
31 our $my_url = $cgi->url();
32 our $my_uri = $cgi->url(-absolute => 1);
35 # Define and than setup our configuration
37 our(
38 $VERSION,
39 $GIT,
40 $projectroot,
41 $home_link,
42 $home_link_str,
43 $site_name,
44 $site_header,
45 $home_text,
46 $site_footer,
47 @stylesheets,
48 $stylesheet,
49 $logo,
50 $favicon,
51 $logo_url,
52 $logo_label,
53 $projects_list,
54 $export_ok,
55 $strict_export,
56 @git_base_url_list,
57 $default_blob_plain_mimetype,
58 $default_text_plain_charset,
59 $mimetypes_file,
60 $missmatch_git,
61 $gitlinkurl,
62 $maxload,
63 $minCacheTime,
64 $maxCacheTime,
65 $cachedir,
66 $backgroundCache,
67 $fullhashpath,
68 $fullhashbinpath,
69 $export_auth_hook,
70 %known_snapshot_format_aliases,
71 %known_snapshot_formats,
72 $path_info,
73 $fallback_encoding,
74 %avatar_size,
75 $project_maxdepth,
76 $headerRefresh,
77 $base_url,
78 $projects_list_description_width,
79 $default_projects_order,
80 $prevent_xss,
81 @diff_opts,
82 %feature
85 do 'gitweb_defaults.pl';
87 sub gitweb_get_feature {
88 my ($name) = @_;
89 return unless exists $feature{$name};
90 my ($sub, $override, @defaults) = (
91 $feature{$name}{'sub'},
92 $feature{$name}{'override'},
93 @{$feature{$name}{'default'}});
94 if (!$override) { return @defaults; }
95 if (!defined $sub) {
96 warn "feature $name is not overridable";
97 return @defaults;
99 return $sub->(@defaults);
102 # A wrapper to check if a given feature is enabled.
103 # With this, you can say
105 # my $bool_feat = gitweb_check_feature('bool_feat');
106 # gitweb_check_feature('bool_feat') or somecode;
108 # instead of
110 # my ($bool_feat) = gitweb_get_feature('bool_feat');
111 # (gitweb_get_feature('bool_feat'))[0] or somecode;
113 sub gitweb_check_feature {
114 return (gitweb_get_feature(@_))[0];
118 sub feature_bool {
119 my $key = shift;
120 my ($val) = git_get_project_config($key, '--bool');
122 if (!defined $val) {
123 return ($_[0]);
124 } elsif ($val eq 'true') {
125 return (1);
126 } elsif ($val eq 'false') {
127 return (0);
131 sub feature_snapshot {
132 my (@fmts) = @_;
134 my ($val) = git_get_project_config('snapshot');
136 if ($val) {
137 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
140 return @fmts;
143 sub feature_patches {
144 my @val = (git_get_project_config('patches', '--int'));
146 if (@val) {
147 return @val;
150 return ($_[0]);
153 sub feature_avatar {
154 my @val = (git_get_project_config('avatar'));
156 return @val ? @val : @_;
159 # checking HEAD file with -e is fragile if the repository was
160 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
161 # and then pruned.
162 sub check_head_link {
163 my ($dir) = @_;
164 my $headfile = "$dir/HEAD";
165 return ((-e $headfile) ||
166 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
169 sub check_export_ok {
170 my ($dir) = @_;
171 return (check_head_link($dir) &&
172 (!$export_ok || -e "$dir/$export_ok") &&
173 (!$export_auth_hook || $export_auth_hook->($dir)));
176 # process alternate names for backward compatibility
177 # filter out unsupported (unknown) snapshot formats
178 sub filter_snapshot_fmts {
179 my @fmts = @_;
181 @fmts = map {
182 exists $known_snapshot_format_aliases{$_} ?
183 $known_snapshot_format_aliases{$_} : $_} @fmts;
184 @fmts = grep {
185 exists $known_snapshot_formats{$_} &&
186 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
189 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
190 if (-e $GITWEB_CONFIG) {
191 do $GITWEB_CONFIG;
192 } else {
193 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
194 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
197 # loadavg throttle
198 sub get_loadavg() {
199 my $load;
200 my @loads;
202 open($load, '<', '/proc/loadavg') or return 0;
203 @loads = split(/\s+/, scalar <$load>);
204 close($load);
205 return $loads[0];
208 if (get_loadavg() > $maxload) {
209 print "Content-Type: text/plain\n";
210 print "Status: 503 Excessive load on server\n";
211 print "\n";
212 print "The load average on the server is too high\n";
213 exit 0;
217 # Includes
219 do 'cache.pm';
221 # version of the core git binary
222 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
224 # There's a pretty serious flaw that we silently fail if git doesn't find something it needs
225 # a quick and simple check is to have gitweb do a simple check - are we running on the same
226 # version of git that we shipped with - if not, throw up an error so that people doing
227 # first installs don't have to debug perl to figure out whats going on
228 if (
229 $git_version ne $version
231 $missmatch_git eq ''
233 git_header_html();
234 print "<p><b>*** Warning ***</b></p>\n";
235 print "<p>\n";
236 print "This version of gitweb was compiled for <b>$version</b> however git version <b>$git_version</b> was found<br/>\n";
237 print "If you are sure this version of git works with this version of gitweb - please define <b>\$missmatch_git</b> to a non empty string in your git config file.\n";
238 print "</p>\n";
239 git_footer_html();
240 exit;
243 $projects_list ||= $projectroot;
245 # ======================================================================
246 # input validation and dispatch
248 # input parameters can be collected from a variety of sources (presently, CGI
249 # and PATH_INFO), so we define an %input_params hash that collects them all
250 # together during validation: this allows subsequent uses (e.g. href()) to be
251 # agnostic of the parameter origin
253 our %input_params = ();
255 # input parameters are stored with the long parameter name as key. This will
256 # also be used in the href subroutine to convert parameters to their CGI
257 # equivalent, and since the href() usage is the most frequent one, we store
258 # the name -> CGI key mapping here, instead of the reverse.
260 # XXX: Warning: If you touch this, check the search form for updating,
261 # too.
263 our @cgi_param_mapping = (
264 project => "p",
265 action => "a",
266 file_name => "f",
267 file_parent => "fp",
268 hash => "h",
269 hash_parent => "hp",
270 hash_base => "hb",
271 hash_parent_base => "hpb",
272 page => "pg",
273 order => "o",
274 searchtext => "s",
275 searchtype => "st",
276 snapshot_format => "sf",
277 extra_options => "opt",
278 search_use_regexp => "sr",
280 our %cgi_param_mapping = @cgi_param_mapping;
282 # we will also need to know the possible actions, for validation
283 our %actions = (
284 "blame" => \&git_blame,
285 "blobdiff" => \&git_blobdiff,
286 "blobdiff_plain" => \&git_blobdiff_plain,
287 "blob" => \&git_blob,
288 "blob_plain" => \&git_blob_plain,
289 "commitdiff" => \&git_commitdiff,
290 "commitdiff_plain" => \&git_commitdiff_plain,
291 "commit" => \&git_commit,
292 "forks" => \&git_forks,
293 "heads" => \&git_heads,
294 "history" => \&git_history,
295 "log" => \&git_log,
296 "patch" => \&git_patch,
297 "patches" => \&git_patches,
298 "rss" => \&git_rss,
299 "atom" => \&git_atom,
300 "search" => \&git_search,
301 "search_help" => \&git_search_help,
302 "shortlog" => \&git_shortlog,
303 "summary" => \&git_summary,
304 "tag" => \&git_tag,
305 "tags" => \&git_tags,
306 "tree" => \&git_tree,
307 "snapshot" => \&git_snapshot,
308 "object" => \&git_object,
309 # those below don't need $project
310 "opml" => \&git_opml,
311 "project_list" => \&git_project_list,
312 "project_index" => \&git_project_index,
315 # finally, we have the hash of allowed extra_options for the commands that
316 # allow them
317 our %allowed_options = (
318 "--no-merges" => [ qw(rss atom log shortlog history) ],
321 # fill %input_params with the CGI parameters. All values except for 'opt'
322 # should be single values, but opt can be an array. We should probably
323 # build an array of parameters that can be multi-valued, but since for the time
324 # being it's only this one, we just single it out
325 while (my ($name, $symbol) = each %cgi_param_mapping) {
326 if ($symbol eq 'opt') {
327 $input_params{$name} = [ $cgi->param($symbol) ];
328 } else {
329 $input_params{$name} = $cgi->param($symbol);
333 # now read PATH_INFO and update the parameter list for missing parameters
334 sub evaluate_path_info {
335 return if defined $input_params{'project'};
336 return if !$path_info;
337 $path_info =~ s,^/+,,;
338 return if !$path_info;
340 # find which part of PATH_INFO is project
341 my $project = $path_info;
342 $project =~ s,/+$,,;
343 while ($project && !check_head_link("$projectroot/$project")) {
344 $project =~ s,/*[^/]*$,,;
346 return unless $project;
347 $input_params{'project'} = $project;
349 # do not change any parameters if an action is given using the query string
350 return if $input_params{'action'};
351 $path_info =~ s,^\Q$project\E/*,,;
353 # next, check if we have an action
354 my $action = $path_info;
355 $action =~ s,/.*$,,;
356 if (exists $actions{$action}) {
357 $path_info =~ s,^$action/*,,;
358 $input_params{'action'} = $action;
361 # list of actions that want hash_base instead of hash, but can have no
362 # pathname (f) parameter
363 my @wants_base = (
364 'tree',
365 'history',
368 # we want to catch
369 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
370 my ($parentrefname, $parentpathname, $refname, $pathname) =
371 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
373 # first, analyze the 'current' part
374 if (defined $pathname) {
375 # we got "branch:filename" or "branch:dir/"
376 # we could use git_get_type(branch:pathname), but:
377 # - it needs $git_dir
378 # - it does a git() call
379 # - the convention of terminating directories with a slash
380 # makes it superfluous
381 # - embedding the action in the PATH_INFO would make it even
382 # more superfluous
383 $pathname =~ s,^/+,,;
384 if (!$pathname || substr($pathname, -1) eq "/") {
385 $input_params{'action'} ||= "tree";
386 $pathname =~ s,/$,,;
387 } else {
388 # the default action depends on whether we had parent info
389 # or not
390 if ($parentrefname) {
391 $input_params{'action'} ||= "blobdiff_plain";
392 } else {
393 $input_params{'action'} ||= "blob_plain";
396 $input_params{'hash_base'} ||= $refname;
397 $input_params{'file_name'} ||= $pathname;
398 } elsif (defined $refname) {
399 # we got "branch". In this case we have to choose if we have to
400 # set hash or hash_base.
402 # Most of the actions without a pathname only want hash to be
403 # set, except for the ones specified in @wants_base that want
404 # hash_base instead. It should also be noted that hand-crafted
405 # links having 'history' as an action and no pathname or hash
406 # set will fail, but that happens regardless of PATH_INFO.
407 $input_params{'action'} ||= "shortlog";
408 if (grep { $_ eq $input_params{'action'} } @wants_base) {
409 $input_params{'hash_base'} ||= $refname;
410 } else {
411 $input_params{'hash'} ||= $refname;
415 # next, handle the 'parent' part, if present
416 if (defined $parentrefname) {
417 # a missing pathspec defaults to the 'current' filename, allowing e.g.
418 # someproject/blobdiff/oldrev..newrev:/filename
419 if ($parentpathname) {
420 $parentpathname =~ s,^/+,,;
421 $parentpathname =~ s,/$,,;
422 $input_params{'file_parent'} ||= $parentpathname;
423 } else {
424 $input_params{'file_parent'} ||= $input_params{'file_name'};
426 # we assume that hash_parent_base is wanted if a path was specified,
427 # or if the action wants hash_base instead of hash
428 if (defined $input_params{'file_parent'} ||
429 grep { $_ eq $input_params{'action'} } @wants_base) {
430 $input_params{'hash_parent_base'} ||= $parentrefname;
431 } else {
432 $input_params{'hash_parent'} ||= $parentrefname;
436 # for the snapshot action, we allow URLs in the form
437 # $project/snapshot/$hash.ext
438 # where .ext determines the snapshot and gets removed from the
439 # passed $refname to provide the $hash.
441 # To be able to tell that $refname includes the format extension, we
442 # require the following two conditions to be satisfied:
443 # - the hash input parameter MUST have been set from the $refname part
444 # of the URL (i.e. they must be equal)
445 # - the snapshot format MUST NOT have been defined already (e.g. from
446 # CGI parameter sf)
447 # It's also useless to try any matching unless $refname has a dot,
448 # so we check for that too
449 if (defined $input_params{'action'} &&
450 $input_params{'action'} eq 'snapshot' &&
451 defined $refname && index($refname, '.') != -1 &&
452 $refname eq $input_params{'hash'} &&
453 !defined $input_params{'snapshot_format'}) {
454 # We loop over the known snapshot formats, checking for
455 # extensions. Allowed extensions are both the defined suffix
456 # (which includes the initial dot already) and the snapshot
457 # format key itself, with a prepended dot
458 while (my ($fmt, $opt) = each %known_snapshot_formats) {
459 my $hash = $refname;
460 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
461 next;
463 my $sfx = $1;
464 # a valid suffix was found, so set the snapshot format
465 # and reset the hash parameter
466 $input_params{'snapshot_format'} = $fmt;
467 $input_params{'hash'} = $hash;
468 # we also set the format suffix to the one requested
469 # in the URL: this way a request for e.g. .tgz returns
470 # a .tgz instead of a .tar.gz
471 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
472 last;
476 evaluate_path_info();
478 our $action = $input_params{'action'};
479 if (defined $action) {
480 if (!validate_action($action)) {
481 die_error(400, "Invalid action parameter");
485 # parameters which are pathnames
486 our $project = $input_params{'project'};
487 if (defined $project) {
488 if (!validate_project($project)) {
489 undef $project;
490 die_error(404, "No such project");
494 our $file_name = $input_params{'file_name'};
495 if (defined $file_name) {
496 if (!validate_pathname($file_name)) {
497 die_error(400, "Invalid file parameter");
501 our $file_parent = $input_params{'file_parent'};
502 if (defined $file_parent) {
503 if (!validate_pathname($file_parent)) {
504 die_error(400, "Invalid file parent parameter");
508 # parameters which are refnames
509 our $hash = $input_params{'hash'};
510 if (defined $hash) {
511 if (!validate_refname($hash)) {
512 die_error(400, "Invalid hash parameter");
516 our $hash_parent = $input_params{'hash_parent'};
517 if (defined $hash_parent) {
518 if (!validate_refname($hash_parent)) {
519 die_error(400, "Invalid hash parent parameter");
523 our $hash_base = $input_params{'hash_base'};
524 if (defined $hash_base) {
525 if (!validate_refname($hash_base)) {
526 die_error(400, "Invalid hash base parameter");
530 our @extra_options = @{$input_params{'extra_options'}};
531 # @extra_options is always defined, since it can only be (currently) set from
532 # CGI, and $cgi->param() returns the empty array in array context if the param
533 # is not set
534 foreach my $opt (@extra_options) {
535 if (not exists $allowed_options{$opt}) {
536 die_error(400, "Invalid option parameter");
538 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
539 die_error(400, "Invalid option parameter for this action");
543 our $hash_parent_base = $input_params{'hash_parent_base'};
544 if (defined $hash_parent_base) {
545 if (!validate_refname($hash_parent_base)) {
546 die_error(400, "Invalid hash parent base parameter");
550 # other parameters
551 our $page = $input_params{'page'};
552 if (defined $page) {
553 if ($page =~ m/[^0-9]/) {
554 die_error(400, "Invalid page parameter");
558 our $searchtype = $input_params{'searchtype'};
559 if (defined $searchtype) {
560 if ($searchtype =~ m/[^a-z]/) {
561 die_error(400, "Invalid searchtype parameter");
565 our $search_use_regexp = $input_params{'search_use_regexp'};
567 our $searchtext = $input_params{'searchtext'};
568 our $search_regexp;
569 if (defined $searchtext) {
570 if (length($searchtext) < 2) {
571 die_error(403, "At least two characters are required for search parameter");
573 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
576 # path to the current git repository
577 our $git_dir;
578 $git_dir = "$projectroot/$project" if $project;
580 # list of supported snapshot formats
581 our @snapshot_fmts = gitweb_get_feature('snapshot');
582 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
584 # check that the avatar feature is set to a known provider name,
585 # and for each provider check if the dependencies are satisfied.
586 # if the provider name is invalid or the dependencies are not met,
587 # reset $git_avatar to the empty string.
588 our ($git_avatar) = gitweb_get_feature('avatar');
589 if ($git_avatar eq 'gravatar') {
590 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
591 } elsif ($git_avatar eq 'picon') {
592 # no dependencies
593 } else {
594 $git_avatar = '';
597 # dispatch
598 if (!defined $action) {
599 if (defined $hash) {
600 $action = git_get_type($hash);
601 } elsif (defined $hash_base && defined $file_name) {
602 $action = git_get_type("$hash_base:$file_name");
603 } elsif (defined $project) {
604 $action = 'summary';
605 } else {
606 $action = 'project_list';
609 if (!defined($actions{$action})) {
610 die_error(400, "Unknown action");
612 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
613 !$project) {
614 die_error(400, "Project needed");
616 cache_fetch($action);
617 exit;
619 ## ======================================================================
620 ## action links
622 sub href {
623 my %params = @_;
624 # default is to use -absolute url() i.e. $my_uri
625 my $href = $params{-full} ? $my_url : $my_uri;
627 $params{'project'} = $project unless exists $params{'project'};
629 if ($params{-replay}) {
630 while (my ($name, $symbol) = each %cgi_param_mapping) {
631 if (!exists $params{$name}) {
632 $params{$name} = $input_params{$name};
637 my $use_pathinfo = gitweb_check_feature('pathinfo');
638 if ($use_pathinfo and defined $params{'project'}) {
639 # try to put as many parameters as possible in PATH_INFO:
640 # - project name
641 # - action
642 # - hash_parent or hash_parent_base:/file_parent
643 # - hash or hash_base:/filename
644 # - the snapshot_format as an appropriate suffix
646 # When the script is the root DirectoryIndex for the domain,
647 # $href here would be something like http://gitweb.example.com/
648 # Thus, we strip any trailing / from $href, to spare us double
649 # slashes in the final URL
650 $href =~ s,/$,,;
652 # Then add the project name, if present
653 $href .= "/".esc_url($params{'project'});
654 delete $params{'project'};
656 # since we destructively absorb parameters, we keep this
657 # boolean that remembers if we're handling a snapshot
658 my $is_snapshot = $params{'action'} eq 'snapshot';
660 # Summary just uses the project path URL, any other action is
661 # added to the URL
662 if (defined $params{'action'}) {
663 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
664 delete $params{'action'};
667 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
668 # stripping nonexistent or useless pieces
669 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
670 || $params{'hash_parent'} || $params{'hash'});
671 if (defined $params{'hash_base'}) {
672 if (defined $params{'hash_parent_base'}) {
673 $href .= esc_url($params{'hash_parent_base'});
674 # skip the file_parent if it's the same as the file_name
675 if (defined $params{'file_parent'}) {
676 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
677 delete $params{'file_parent'};
678 } elsif ($params{'file_parent'} !~ /\.\./) {
679 $href .= ":/".esc_url($params{'file_parent'});
680 delete $params{'file_parent'};
683 $href .= "..";
684 delete $params{'hash_parent'};
685 delete $params{'hash_parent_base'};
686 } elsif (defined $params{'hash_parent'}) {
687 $href .= esc_url($params{'hash_parent'}). "..";
688 delete $params{'hash_parent'};
691 $href .= esc_url($params{'hash_base'});
692 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
693 $href .= ":/".esc_url($params{'file_name'});
694 delete $params{'file_name'};
696 delete $params{'hash'};
697 delete $params{'hash_base'};
698 } elsif (defined $params{'hash'}) {
699 $href .= esc_url($params{'hash'});
700 delete $params{'hash'};
703 # If the action was a snapshot, we can absorb the
704 # snapshot_format parameter too
705 if ($is_snapshot) {
706 my $fmt = $params{'snapshot_format'};
707 # snapshot_format should always be defined when href()
708 # is called, but just in case some code forgets, we
709 # fall back to the default
710 $fmt ||= $snapshot_fmts[0];
711 $href .= $known_snapshot_formats{$fmt}{'suffix'};
712 delete $params{'snapshot_format'};
716 # now encode the parameters explicitly
717 my @result = ();
718 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
719 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
720 if (defined $params{$name}) {
721 if (ref($params{$name}) eq "ARRAY") {
722 foreach my $par (@{$params{$name}}) {
723 push @result, $symbol . "=" . esc_param($par);
725 } else {
726 push @result, $symbol . "=" . esc_param($params{$name});
730 $href .= "?" . join(';', @result) if scalar @result;
732 return $href;
736 ## ======================================================================
737 ## validation, quoting/unquoting and escaping
739 sub validate_action {
740 my $input = shift || return undef;
741 return undef unless exists $actions{$input};
742 return $input;
745 sub validate_project {
746 my $input = shift || return undef;
747 if (!validate_pathname($input) ||
748 !(-d "$projectroot/$input") ||
749 !check_export_ok("$projectroot/$input") ||
750 ($strict_export && !project_in_list($input))) {
751 return undef;
752 } else {
753 return $input;
757 sub validate_pathname {
758 my $input = shift || return undef;
760 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
761 # at the beginning, at the end, and between slashes.
762 # also this catches doubled slashes
763 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
764 return undef;
766 # no null characters
767 if ($input =~ m!\0!) {
768 return undef;
770 return $input;
773 sub validate_refname {
774 my $input = shift || return undef;
776 # textual hashes are O.K.
777 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
778 return $input;
780 # it must be correct pathname
781 $input = validate_pathname($input)
782 or return undef;
783 # restrictions on ref name according to git-check-ref-format
784 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
785 return undef;
787 return $input;
790 # decode sequences of octets in utf8 into Perl's internal form,
791 # which is utf-8 with utf8 flag set if needed. gitweb writes out
792 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
793 sub to_utf8 {
794 my $str = shift;
795 if (utf8::valid($str)) {
796 utf8::decode($str);
797 return $str;
798 } else {
799 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
803 # quote unsafe chars, but keep the slash, even when it's not
804 # correct, but quoted slashes look too horrible in bookmarks
805 sub esc_param {
806 my $str = shift;
807 $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
808 $str =~ s/\+/%2B/g;
809 $str =~ s/ /\+/g;
810 return $str;
813 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
814 sub esc_url {
815 my $str = shift;
816 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
817 $str =~ s/\+/%2B/g;
818 $str =~ s/ /\+/g;
819 return $str;
822 # replace invalid utf8 character with SUBSTITUTION sequence
823 sub esc_html {
824 my $str = shift;
825 my %opts = @_;
827 $str = to_utf8($str);
828 $str = $cgi->escapeHTML($str);
829 if ($opts{'-nbsp'}) {
830 $str =~ s/ /&nbsp;/g;
832 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
833 return $str;
836 # quote control characters and escape filename to HTML
837 sub esc_path {
838 my $str = shift;
839 my %opts = @_;
841 $str = to_utf8($str);
842 $str = $cgi->escapeHTML($str);
843 if ($opts{'-nbsp'}) {
844 $str =~ s/ /&nbsp;/g;
846 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
847 return $str;
850 # Make control characters "printable", using character escape codes (CEC)
851 sub quot_cec {
852 my $cntrl = shift;
853 my %opts = @_;
854 my %es = ( # character escape codes, aka escape sequences
855 "\t" => '\t', # tab (HT)
856 "\n" => '\n', # line feed (LF)
857 "\r" => '\r', # carrige return (CR)
858 "\f" => '\f', # form feed (FF)
859 "\b" => '\b', # backspace (BS)
860 "\a" => '\a', # alarm (bell) (BEL)
861 "\e" => '\e', # escape (ESC)
862 "\013" => '\v', # vertical tab (VT)
863 "\000" => '\0', # nul character (NUL)
865 my $chr = ( (exists $es{$cntrl})
866 ? $es{$cntrl}
867 : sprintf('\%2x', ord($cntrl)) );
868 if ($opts{-nohtml}) {
869 return $chr;
870 } else {
871 return "<span class=\"cntrl\">$chr</span>";
875 # Alternatively use unicode control pictures codepoints,
876 # Unicode "printable representation" (PR)
877 sub quot_upr {
878 my $cntrl = shift;
879 my %opts = @_;
881 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
882 if ($opts{-nohtml}) {
883 return $chr;
884 } else {
885 return "<span class=\"cntrl\">$chr</span>";
889 # git may return quoted and escaped filenames
890 sub unquote {
891 my $str = shift;
893 sub unq {
894 my $seq = shift;
895 my %es = ( # character escape codes, aka escape sequences
896 't' => "\t", # tab (HT, TAB)
897 'n' => "\n", # newline (NL)
898 'r' => "\r", # return (CR)
899 'f' => "\f", # form feed (FF)
900 'b' => "\b", # backspace (BS)
901 'a' => "\a", # alarm (bell) (BEL)
902 'e' => "\e", # escape (ESC)
903 'v' => "\013", # vertical tab (VT)
906 if ($seq =~ m/^[0-7]{1,3}$/) {
907 # octal char sequence
908 return chr(oct($seq));
909 } elsif (exists $es{$seq}) {
910 # C escape sequence, aka character escape code
911 return $es{$seq};
913 # quoted ordinary character
914 return $seq;
917 if ($str =~ m/^"(.*)"$/) {
918 # needs unquoting
919 $str = $1;
920 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
922 return $str;
925 # escape tabs (convert tabs to spaces)
926 sub untabify {
927 my $line = shift;
929 while ((my $pos = index($line, "\t")) != -1) {
930 if (my $count = (8 - ($pos % 8))) {
931 my $spaces = ' ' x $count;
932 $line =~ s/\t/$spaces/;
936 return $line;
939 sub project_in_list {
940 my $project = shift;
941 my @list = git_get_projects_list();
942 return @list && scalar(grep { $_->{'path'} eq $project } @list);
945 ## ----------------------------------------------------------------------
946 ## HTML aware string manipulation
948 # Try to chop given string on a word boundary between position
949 # $len and $len+$add_len. If there is no word boundary there,
950 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
951 # (marking chopped part) would be longer than given string.
952 sub chop_str {
953 my $str = shift;
954 my $len = shift;
955 my $add_len = shift || 10;
956 my $where = shift || 'right'; # 'left' | 'center' | 'right'
958 # Make sure perl knows it is utf8 encoded so we don't
959 # cut in the middle of a utf8 multibyte char.
960 $str = to_utf8($str);
962 # allow only $len chars, but don't cut a word if it would fit in $add_len
963 # if it doesn't fit, cut it if it's still longer than the dots we would add
964 # remove chopped character entities entirely
966 # when chopping in the middle, distribute $len into left and right part
967 # return early if chopping wouldn't make string shorter
968 if ($where eq 'center') {
969 return $str if ($len + 5 >= length($str)); # filler is length 5
970 $len = int($len/2);
971 } else {
972 return $str if ($len + 4 >= length($str)); # filler is length 4
975 # regexps: ending and beginning with word part up to $add_len
976 my $endre = qr/.{$len}\w{0,$add_len}/;
977 my $begre = qr/\w{0,$add_len}.{$len}/;
979 if ($where eq 'left') {
980 $str =~ m/^(.*?)($begre)$/;
981 my ($lead, $body) = ($1, $2);
982 if (length($lead) > 4) {
983 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
984 $lead = " ...";
986 return "$lead$body";
988 } elsif ($where eq 'center') {
989 $str =~ m/^($endre)(.*)$/;
990 my ($left, $str) = ($1, $2);
991 $str =~ m/^(.*?)($begre)$/;
992 my ($mid, $right) = ($1, $2);
993 if (length($mid) > 5) {
994 $left =~ s/&[^;]*$//;
995 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
996 $mid = " ... ";
998 return "$left$mid$right";
1000 } else {
1001 $str =~ m/^($endre)(.*)$/;
1002 my $body = $1;
1003 my $tail = $2;
1004 if (length($tail) > 4) {
1005 $body =~ s/&[^;]*$//;
1006 $tail = "... ";
1008 return "$body$tail";
1012 # takes the same arguments as chop_str, but also wraps a <span> around the
1013 # result with a title attribute if it does get chopped. Additionally, the
1014 # string is HTML-escaped.
1015 sub chop_and_escape_str {
1016 my ($str) = @_;
1018 my $chopped = chop_str(@_);
1019 if ($chopped eq $str) {
1020 return esc_html($chopped);
1021 } else {
1022 $str =~ s/[[:cntrl:]]/?/g;
1023 return $cgi->span({-title=>$str}, esc_html($chopped));
1027 ## ----------------------------------------------------------------------
1028 ## functions returning short strings
1030 # CSS class for given age value (in seconds)
1031 sub age_class {
1032 my $age = shift;
1034 if (!defined $age) {
1035 return "noage";
1036 } elsif ($age < 60*60*2) {
1037 return "age0";
1038 } elsif ($age < 60*60*24*2) {
1039 return "age1";
1040 } else {
1041 return "age2";
1045 # convert age in seconds to "nn units ago" string
1046 sub age_string {
1047 my $age = shift;
1048 my $age_str;
1050 if ($age > 60*60*24*365*2) {
1051 $age_str = (int $age/60/60/24/365);
1052 $age_str .= " years ago";
1053 } elsif ($age > 60*60*24*(365/12)*2) {
1054 $age_str = int $age/60/60/24/(365/12);
1055 $age_str .= " months ago";
1056 } elsif ($age > 60*60*24*7*2) {
1057 $age_str = int $age/60/60/24/7;
1058 $age_str .= " weeks ago";
1059 } elsif ($age > 60*60*24*2) {
1060 $age_str = int $age/60/60/24;
1061 $age_str .= " days ago";
1062 } elsif ($age > 60*60*2) {
1063 $age_str = int $age/60/60;
1064 $age_str .= " hours ago";
1065 } elsif ($age > 60*2) {
1066 $age_str = int $age/60;
1067 $age_str .= " min ago";
1068 } elsif ($age > 2) {
1069 $age_str = int $age;
1070 $age_str .= " sec ago";
1071 } else {
1072 $age_str .= " right now";
1074 return $age_str;
1077 use constant {
1078 S_IFINVALID => 0030000,
1079 S_IFGITLINK => 0160000,
1082 # submodule/subproject, a commit object reference
1083 sub S_ISGITLINK {
1084 my $mode = shift;
1086 return (($mode & S_IFMT) == S_IFGITLINK)
1089 # convert file mode in octal to symbolic file mode string
1090 sub mode_str {
1091 my $mode = oct shift;
1093 if (S_ISGITLINK($mode)) {
1094 return 'm---------';
1095 } elsif (S_ISDIR($mode & S_IFMT)) {
1096 return 'drwxr-xr-x';
1097 } elsif (S_ISLNK($mode)) {
1098 return 'lrwxrwxrwx';
1099 } elsif (S_ISREG($mode)) {
1100 # git cares only about the executable bit
1101 if ($mode & S_IXUSR) {
1102 return '-rwxr-xr-x';
1103 } else {
1104 return '-rw-r--r--';
1106 } else {
1107 return '----------';
1111 # convert file mode in octal to file type string
1112 sub file_type {
1113 my $mode = shift;
1115 if ($mode !~ m/^[0-7]+$/) {
1116 return $mode;
1117 } else {
1118 $mode = oct $mode;
1121 if (S_ISGITLINK($mode)) {
1122 return "submodule";
1123 } elsif (S_ISDIR($mode & S_IFMT)) {
1124 return "directory";
1125 } elsif (S_ISLNK($mode)) {
1126 return "symlink";
1127 } elsif (S_ISREG($mode)) {
1128 return "file";
1129 } else {
1130 return "unknown";
1134 # convert file mode in octal to file type description string
1135 sub file_type_long {
1136 my $mode = shift;
1138 if ($mode !~ m/^[0-7]+$/) {
1139 return $mode;
1140 } else {
1141 $mode = oct $mode;
1144 if (S_ISGITLINK($mode)) {
1145 return "submodule";
1146 } elsif (S_ISDIR($mode & S_IFMT)) {
1147 return "directory";
1148 } elsif (S_ISLNK($mode)) {
1149 return "symlink";
1150 } elsif (S_ISREG($mode)) {
1151 if ($mode & S_IXUSR) {
1152 return "executable";
1153 } else {
1154 return "file";
1156 } else {
1157 return "unknown";
1162 ## ----------------------------------------------------------------------
1163 ## functions returning short HTML fragments, or transforming HTML fragments
1164 ## which don't belong to other sections
1166 # format line of commit message.
1167 sub format_log_line_html {
1168 my $line = shift;
1170 $line = esc_html($line, -nbsp=>1);
1171 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1172 $cgi->a({-href => href(action=>"object", hash=>$1),
1173 -class => "text"}, $1);
1174 }eg;
1176 return $line;
1179 # format marker of refs pointing to given object
1181 # the destination action is chosen based on object type and current context:
1182 # - for annotated tags, we choose the tag view unless it's the current view
1183 # already, in which case we go to shortlog view
1184 # - for other refs, we keep the current view if we're in history, shortlog or
1185 # log view, and select shortlog otherwise
1186 sub format_ref_marker {
1187 my ($refs, $id) = @_;
1188 my $markers = '';
1190 if (defined $refs->{$id}) {
1191 foreach my $ref (@{$refs->{$id}}) {
1192 # this code exploits the fact that non-lightweight tags are the
1193 # only indirect objects, and that they are the only objects for which
1194 # we want to use tag instead of shortlog as action
1195 my ($type, $name) = qw();
1196 my $indirect = ($ref =~ s/\^\{\}$//);
1197 # e.g. tags/v2.6.11 or heads/next
1198 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1199 $type = $1;
1200 $name = $2;
1201 } else {
1202 $type = "ref";
1203 $name = $ref;
1206 my $class = $type;
1207 $class .= " indirect" if $indirect;
1209 my $dest_action = "shortlog";
1211 if ($indirect) {
1212 $dest_action = "tag" unless $action eq "tag";
1213 } elsif ($action =~ /^(history|(short)?log)$/) {
1214 $dest_action = $action;
1217 my $dest = "";
1218 $dest .= "refs/" unless $ref =~ m!^refs/!;
1219 $dest .= $ref;
1221 my $link = $cgi->a({
1222 -href => href(
1223 action=>$dest_action,
1224 hash=>$dest
1225 )}, $name);
1227 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1228 $link . "</span>";
1232 if ($markers) {
1233 return ' <span class="refs">'. $markers . '</span>';
1234 } else {
1235 return "";
1239 # format, perhaps shortened and with markers, title line
1240 sub format_subject_html {
1241 my ($long, $short, $href, $extra) = @_;
1242 $extra = '' unless defined($extra);
1244 if (length($short) < length($long)) {
1245 $long =~ s/[[:cntrl:]]/?/g;
1246 return $cgi->a({-href => $href, -class => "list subject",
1247 -title => to_utf8($long)},
1248 esc_html($short)) . $extra;
1249 } else {
1250 return $cgi->a({-href => $href, -class => "list subject"},
1251 esc_html($long)) . $extra;
1255 # Rather than recomputing the url for an email multiple times, we cache it
1256 # after the first hit. This gives a visible benefit in views where the avatar
1257 # for the same email is used repeatedly (e.g. shortlog).
1258 # The cache is shared by all avatar engines (currently gravatar only), which
1259 # are free to use it as preferred. Since only one avatar engine is used for any
1260 # given page, there's no risk for cache conflicts.
1261 our %avatar_cache = ();
1263 # Compute the picon url for a given email, by using the picon search service over at
1264 # http://www.cs.indiana.edu/picons/search.html
1265 sub picon_url {
1266 my $email = lc shift;
1267 if (!$avatar_cache{$email}) {
1268 my ($user, $domain) = split('@', $email);
1269 $avatar_cache{$email} =
1270 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1271 "$domain/$user/" .
1272 "users+domains+unknown/up/single";
1274 return $avatar_cache{$email};
1277 # Compute the gravatar url for a given email, if it's not in the cache already.
1278 # Gravatar stores only the part of the URL before the size, since that's the
1279 # one computationally more expensive. This also allows reuse of the cache for
1280 # different sizes (for this particular engine).
1281 sub gravatar_url {
1282 my $email = lc shift;
1283 my $size = shift;
1284 $avatar_cache{$email} ||=
1285 "http://www.gravatar.com/avatar/" .
1286 Digest::MD5::md5_hex($email) . "?s=";
1287 return $avatar_cache{$email} . $size;
1290 # Insert an avatar for the given $email at the given $size if the feature
1291 # is enabled.
1292 sub git_get_avatar {
1293 my ($email, %opts) = @_;
1294 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1295 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1296 $opts{-size} ||= 'default';
1297 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1298 my $url = "";
1299 if ($git_avatar eq 'gravatar') {
1300 $url = gravatar_url($email, $size);
1301 } elsif ($git_avatar eq 'picon') {
1302 $url = picon_url($email);
1304 # Other providers can be added by extending the if chain, defining $url
1305 # as needed. If no variant puts something in $url, we assume avatars
1306 # are completely disabled/unavailable.
1307 if ($url) {
1308 return $pre_white .
1309 "<img width=\"$size\" " .
1310 "class=\"avatar\" " .
1311 "src=\"$url\" " .
1312 "alt=\"\" " .
1313 "/>" . $post_white;
1314 } else {
1315 return "";
1319 # format the author name of the given commit with the given tag
1320 # the author name is chopped and escaped according to the other
1321 # optional parameters (see chop_str).
1322 sub format_author_html {
1323 my $tag = shift;
1324 my $co = shift;
1325 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1326 return "<$tag class=\"author\">" .
1327 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1328 $author . "</$tag>";
1331 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1332 sub format_git_diff_header_line {
1333 my $line = shift;
1334 my $diffinfo = shift;
1335 my ($from, $to) = @_;
1337 if ($diffinfo->{'nparents'}) {
1338 # combined diff
1339 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1340 if ($to->{'href'}) {
1341 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1342 esc_path($to->{'file'}));
1343 } else { # file was deleted (no href)
1344 $line .= esc_path($to->{'file'});
1346 } else {
1347 # "ordinary" diff
1348 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1349 if ($from->{'href'}) {
1350 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1351 'a/' . esc_path($from->{'file'}));
1352 } else { # file was added (no href)
1353 $line .= 'a/' . esc_path($from->{'file'});
1355 $line .= ' ';
1356 if ($to->{'href'}) {
1357 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1358 'b/' . esc_path($to->{'file'}));
1359 } else { # file was deleted
1360 $line .= 'b/' . esc_path($to->{'file'});
1364 return "<div class=\"diff header\">$line</div>\n";
1367 # format extended diff header line, before patch itself
1368 sub format_extended_diff_header_line {
1369 my $line = shift;
1370 my $diffinfo = shift;
1371 my ($from, $to) = @_;
1373 # match <path>
1374 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1375 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1376 esc_path($from->{'file'}));
1378 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1379 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1380 esc_path($to->{'file'}));
1382 # match single <mode>
1383 if ($line =~ m/\s(\d{6})$/) {
1384 $line .= '<span class="info"> (' .
1385 file_type_long($1) .
1386 ')</span>';
1388 # match <hash>
1389 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1390 # can match only for combined diff
1391 $line = 'index ';
1392 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1393 if ($from->{'href'}[$i]) {
1394 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1395 -class=>"hash"},
1396 substr($diffinfo->{'from_id'}[$i],0,7));
1397 } else {
1398 $line .= '0' x 7;
1400 # separator
1401 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1403 $line .= '..';
1404 if ($to->{'href'}) {
1405 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1406 substr($diffinfo->{'to_id'},0,7));
1407 } else {
1408 $line .= '0' x 7;
1411 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1412 # can match only for ordinary diff
1413 my ($from_link, $to_link);
1414 if ($from->{'href'}) {
1415 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1416 substr($diffinfo->{'from_id'},0,7));
1417 } else {
1418 $from_link = '0' x 7;
1420 if ($to->{'href'}) {
1421 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1422 substr($diffinfo->{'to_id'},0,7));
1423 } else {
1424 $to_link = '0' x 7;
1426 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1427 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1430 return $line . "<br/>\n";
1433 # format from-file/to-file diff header
1434 sub format_diff_from_to_header {
1435 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1436 my $line;
1437 my $result = '';
1439 $line = $from_line;
1440 #assert($line =~ m/^---/) if DEBUG;
1441 # no extra formatting for "^--- /dev/null"
1442 if (! $diffinfo->{'nparents'}) {
1443 # ordinary (single parent) diff
1444 if ($line =~ m!^--- "?a/!) {
1445 if ($from->{'href'}) {
1446 $line = '--- a/' .
1447 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1448 esc_path($from->{'file'}));
1449 } else {
1450 $line = '--- a/' .
1451 esc_path($from->{'file'});
1454 $result .= qq!<div class="diff from_file">$line</div>\n!;
1456 } else {
1457 # combined diff (merge commit)
1458 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1459 if ($from->{'href'}[$i]) {
1460 $line = '--- ' .
1461 $cgi->a({-href=>href(action=>"blobdiff",
1462 hash_parent=>$diffinfo->{'from_id'}[$i],
1463 hash_parent_base=>$parents[$i],
1464 file_parent=>$from->{'file'}[$i],
1465 hash=>$diffinfo->{'to_id'},
1466 hash_base=>$hash,
1467 file_name=>$to->{'file'}),
1468 -class=>"path",
1469 -title=>"diff" . ($i+1)},
1470 $i+1) .
1471 '/' .
1472 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1473 esc_path($from->{'file'}[$i]));
1474 } else {
1475 $line = '--- /dev/null';
1477 $result .= qq!<div class="diff from_file">$line</div>\n!;
1481 $line = $to_line;
1482 #assert($line =~ m/^\+\+\+/) if DEBUG;
1483 # no extra formatting for "^+++ /dev/null"
1484 if ($line =~ m!^\+\+\+ "?b/!) {
1485 if ($to->{'href'}) {
1486 $line = '+++ b/' .
1487 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1488 esc_path($to->{'file'}));
1489 } else {
1490 $line = '+++ b/' .
1491 esc_path($to->{'file'});
1494 $result .= qq!<div class="diff to_file">$line</div>\n!;
1496 return $result;
1499 # create note for patch simplified by combined diff
1500 sub format_diff_cc_simplified {
1501 my ($diffinfo, @parents) = @_;
1502 my $result = '';
1504 $result .= "<div class=\"diff header\">" .
1505 "diff --cc ";
1506 if (!is_deleted($diffinfo)) {
1507 $result .= $cgi->a({-href => href(action=>"blob",
1508 hash_base=>$hash,
1509 hash=>$diffinfo->{'to_id'},
1510 file_name=>$diffinfo->{'to_file'}),
1511 -class => "path"},
1512 esc_path($diffinfo->{'to_file'}));
1513 } else {
1514 $result .= esc_path($diffinfo->{'to_file'});
1516 $result .= "</div>\n" . # class="diff header"
1517 "<div class=\"diff nodifferences\">" .
1518 "Simple merge" .
1519 "</div>\n"; # class="diff nodifferences"
1521 return $result;
1524 # format patch (diff) line (not to be used for diff headers)
1525 sub format_diff_line {
1526 my $line = shift;
1527 my ($from, $to) = @_;
1528 my $diff_class = "";
1530 chomp $line;
1532 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1533 # combined diff
1534 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1535 if ($line =~ m/^\@{3}/) {
1536 $diff_class = " chunk_header";
1537 } elsif ($line =~ m/^\\/) {
1538 $diff_class = " incomplete";
1539 } elsif ($prefix =~ tr/+/+/) {
1540 $diff_class = " add";
1541 } elsif ($prefix =~ tr/-/-/) {
1542 $diff_class = " rem";
1544 } else {
1545 # assume ordinary diff
1546 my $char = substr($line, 0, 1);
1547 if ($char eq '+') {
1548 $diff_class = " add";
1549 } elsif ($char eq '-') {
1550 $diff_class = " rem";
1551 } elsif ($char eq '@') {
1552 $diff_class = " chunk_header";
1553 } elsif ($char eq "\\") {
1554 $diff_class = " incomplete";
1557 $line = untabify($line);
1558 if ($from && $to && $line =~ m/^\@{2} /) {
1559 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1560 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1562 $from_lines = 0 unless defined $from_lines;
1563 $to_lines = 0 unless defined $to_lines;
1565 if ($from->{'href'}) {
1566 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1567 -class=>"list"}, $from_text);
1569 if ($to->{'href'}) {
1570 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1571 -class=>"list"}, $to_text);
1573 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1574 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1575 return "<div class=\"diff$diff_class\">$line</div>\n";
1576 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1577 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1578 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1580 @from_text = split(' ', $ranges);
1581 for (my $i = 0; $i < @from_text; ++$i) {
1582 ($from_start[$i], $from_nlines[$i]) =
1583 (split(',', substr($from_text[$i], 1)), 0);
1586 $to_text = pop @from_text;
1587 $to_start = pop @from_start;
1588 $to_nlines = pop @from_nlines;
1590 $line = "<span class=\"chunk_info\">$prefix ";
1591 for (my $i = 0; $i < @from_text; ++$i) {
1592 if ($from->{'href'}[$i]) {
1593 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1594 -class=>"list"}, $from_text[$i]);
1595 } else {
1596 $line .= $from_text[$i];
1598 $line .= " ";
1600 if ($to->{'href'}) {
1601 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1602 -class=>"list"}, $to_text);
1603 } else {
1604 $line .= $to_text;
1606 $line .= " $prefix</span>" .
1607 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1608 return "<div class=\"diff$diff_class\">$line</div>\n";
1610 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1613 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1614 # linked. Pass the hash of the tree/commit to snapshot.
1615 sub format_snapshot_links {
1616 my ($hash) = @_;
1617 my $num_fmts = @snapshot_fmts;
1618 if ($num_fmts > 1) {
1619 # A parenthesized list of links bearing format names.
1620 # e.g. "snapshot (_tar.gz_ _zip_)"
1621 return "snapshot (" . join(' ', map
1622 $cgi->a({
1623 -href => href(
1624 action=>"snapshot",
1625 hash=>$hash,
1626 snapshot_format=>$_
1628 }, $known_snapshot_formats{$_}{'display'})
1629 , @snapshot_fmts) . ")";
1630 } elsif ($num_fmts == 1) {
1631 # A single "snapshot" link whose tooltip bears the format name.
1632 # i.e. "_snapshot_"
1633 my ($fmt) = @snapshot_fmts;
1634 return
1635 $cgi->a({
1636 -href => href(
1637 action=>"snapshot",
1638 hash=>$hash,
1639 snapshot_format=>$fmt
1641 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1642 }, "snapshot");
1643 } else { # $num_fmts == 0
1644 return undef;
1648 ## ......................................................................
1649 ## functions returning values to be passed, perhaps after some
1650 ## transformation, to other functions; e.g. returning arguments to href()
1652 # returns hash to be passed to href to generate gitweb URL
1653 # in -title key it returns description of link
1654 sub get_feed_info {
1655 my $format = shift || 'Atom';
1656 my %res = (action => lc($format));
1658 # feed links are possible only for project views
1659 return unless (defined $project);
1660 # some views should link to OPML, or to generic project feed,
1661 # or don't have specific feed yet (so they should use generic)
1662 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1664 my $branch;
1665 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1666 # from tag links; this also makes possible to detect branch links
1667 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1668 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1669 $branch = $1;
1671 # find log type for feed description (title)
1672 my $type = 'log';
1673 if (defined $file_name) {
1674 $type = "history of $file_name";
1675 $type .= "/" if ($action eq 'tree');
1676 $type .= " on '$branch'" if (defined $branch);
1677 } else {
1678 $type = "log of $branch" if (defined $branch);
1681 $res{-title} = $type;
1682 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1683 $res{'file_name'} = $file_name;
1685 return %res;
1688 ## ----------------------------------------------------------------------
1689 ## git utility subroutines, invoking git commands
1691 # returns path to the core git executable and the --git-dir parameter as list
1692 sub git_cmd {
1693 return $GIT, '--git-dir='.$git_dir;
1696 # quote the given arguments for passing them to the shell
1697 # quote_command("command", "arg 1", "arg with ' and ! characters")
1698 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1699 # Try to avoid using this function wherever possible.
1700 sub quote_command {
1701 return join(' ',
1702 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
1705 # get HEAD ref of given project as hash
1706 sub git_get_head_hash {
1707 my $project = shift;
1708 my $o_git_dir = $git_dir;
1709 my $retval = undef;
1710 $git_dir = "$projectroot/$project";
1711 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1712 my $head = <$fd>;
1713 close $fd;
1714 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1715 $retval = $1;
1718 if (defined $o_git_dir) {
1719 $git_dir = $o_git_dir;
1721 return $retval;
1724 # get type of given object
1725 sub git_get_type {
1726 my $hash = shift;
1728 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1729 my $type = <$fd>;
1730 close $fd or return;
1731 chomp $type;
1732 return $type;
1735 # repository configuration
1736 our $config_file = '';
1737 our %config;
1739 # store multiple values for single key as anonymous array reference
1740 # single values stored directly in the hash, not as [ <value> ]
1741 sub hash_set_multi {
1742 my ($hash, $key, $value) = @_;
1744 if (!exists $hash->{$key}) {
1745 $hash->{$key} = $value;
1746 } elsif (!ref $hash->{$key}) {
1747 $hash->{$key} = [ $hash->{$key}, $value ];
1748 } else {
1749 push @{$hash->{$key}}, $value;
1753 # return hash of git project configuration
1754 # optionally limited to some section, e.g. 'gitweb'
1755 sub git_parse_project_config {
1756 my $section_regexp = shift;
1757 my %config;
1759 local $/ = "\0";
1761 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
1762 or return;
1764 while (my $keyval = <$fh>) {
1765 chomp $keyval;
1766 my ($key, $value) = split(/\n/, $keyval, 2);
1768 hash_set_multi(\%config, $key, $value)
1769 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
1771 close $fh;
1773 return %config;
1776 # convert config value to boolean: 'true' or 'false'
1777 # no value, number > 0, 'true' and 'yes' values are true
1778 # rest of values are treated as false (never as error)
1779 sub config_to_bool {
1780 my $val = shift;
1782 return 1 if !defined $val; # section.key
1784 # strip leading and trailing whitespace
1785 $val =~ s/^\s+//;
1786 $val =~ s/\s+$//;
1788 return (($val =~ /^\d+$/ && $val) || # section.key = 1
1789 ($val =~ /^(?:true|yes)$/i)); # section.key = true
1792 # convert config value to simple decimal number
1793 # an optional value suffix of 'k', 'm', or 'g' will cause the value
1794 # to be multiplied by 1024, 1048576, or 1073741824
1795 sub config_to_int {
1796 my $val = shift;
1798 # strip leading and trailing whitespace
1799 $val =~ s/^\s+//;
1800 $val =~ s/\s+$//;
1802 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
1803 $unit = lc($unit);
1804 # unknown unit is treated as 1
1805 return $num * ($unit eq 'g' ? 1073741824 :
1806 $unit eq 'm' ? 1048576 :
1807 $unit eq 'k' ? 1024 : 1);
1809 return $val;
1812 # convert config value to array reference, if needed
1813 sub config_to_multi {
1814 my $val = shift;
1816 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
1819 sub git_get_project_config {
1820 my ($key, $type) = @_;
1822 # key sanity check
1823 return unless ($key);
1824 $key =~ s/^gitweb\.//;
1825 return if ($key =~ m/\W/);
1827 # type sanity check
1828 if (defined $type) {
1829 $type =~ s/^--//;
1830 $type = undef
1831 unless ($type eq 'bool' || $type eq 'int');
1834 # get config
1835 if (!defined $config_file ||
1836 $config_file ne "$git_dir/config") {
1837 %config = git_parse_project_config('gitweb');
1838 $config_file = "$git_dir/config";
1841 # check if config variable (key) exists
1842 return unless exists $config{"gitweb.$key"};
1844 # ensure given type
1845 if (!defined $type) {
1846 return $config{"gitweb.$key"};
1847 } elsif ($type eq 'bool') {
1848 # backward compatibility: 'git config --bool' returns true/false
1849 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
1850 } elsif ($type eq 'int') {
1851 return config_to_int($config{"gitweb.$key"});
1853 return $config{"gitweb.$key"};
1856 # get hash of given path at given ref
1857 sub git_get_hash_by_path {
1858 my $base = shift;
1859 my $path = shift || return undef;
1860 my $type = shift;
1862 $path =~ s,/+$,,;
1864 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1865 or die_error(500, "Open git-ls-tree failed");
1866 my $line = <$fd>;
1867 close $fd or return undef;
1869 if (!defined $line) {
1870 # there is no tree or hash given by $path at $base
1871 return undef;
1874 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
1875 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1876 if (defined $type && $type ne $2) {
1877 # type doesn't match
1878 return undef;
1880 return $3;
1883 # get path of entry with given hash at given tree-ish (ref)
1884 # used to get 'from' filename for combined diff (merge commit) for renames
1885 sub git_get_path_by_hash {
1886 my $base = shift || return;
1887 my $hash = shift || return;
1889 local $/ = "\0";
1891 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1892 or return undef;
1893 while (my $line = <$fd>) {
1894 chomp $line;
1896 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
1897 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
1898 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1899 close $fd;
1900 return $1;
1903 close $fd;
1904 return undef;
1907 ## ......................................................................
1908 ## git utility functions, directly accessing git repository
1910 sub git_get_project_description {
1911 my $path = shift;
1913 $git_dir = "$projectroot/$path";
1914 open my $fd, '<', "$git_dir/description"
1915 or return git_get_project_config('description');
1916 my $descr = <$fd>;
1917 close $fd;
1918 if (defined $descr) {
1919 chomp $descr;
1921 return $descr;
1924 sub git_get_project_ctags {
1925 my $path = shift;
1926 my $ctags = {};
1928 $git_dir = "$projectroot/$path";
1929 opendir my $dh, "$git_dir/ctags"
1930 or return $ctags;
1931 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
1932 open my $ct, '<', $_ or next;
1933 my $val = <$ct>;
1934 chomp $val;
1935 close $ct;
1936 my $ctag = $_; $ctag =~ s#.*/##;
1937 $ctags->{$ctag} = $val;
1939 closedir $dh;
1940 $ctags;
1943 sub git_populate_project_tagcloud {
1944 my $ctags = shift;
1946 # First, merge different-cased tags; tags vote on casing
1947 my %ctags_lc;
1948 foreach (keys %$ctags) {
1949 $ctags_lc{lc $_}->{count} += $ctags->{$_};
1950 if (not $ctags_lc{lc $_}->{topcount}
1951 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
1952 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
1953 $ctags_lc{lc $_}->{topname} = $_;
1957 my $cloud;
1958 if (eval { require HTML::TagCloud; 1; }) {
1959 $cloud = HTML::TagCloud->new;
1960 foreach (sort keys %ctags_lc) {
1961 # Pad the title with spaces so that the cloud looks
1962 # less crammed.
1963 my $title = $ctags_lc{$_}->{topname};
1964 $title =~ s/ /&nbsp;/g;
1965 $title =~ s/^/&nbsp;/g;
1966 $title =~ s/$/&nbsp;/g;
1967 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
1969 } else {
1970 $cloud = \%ctags_lc;
1972 $cloud;
1975 sub git_show_project_tagcloud {
1976 my ($cloud, $count) = @_;
1977 print STDERR ref($cloud)."..\n";
1978 if (ref $cloud eq 'HTML::TagCloud') {
1979 return $cloud->html_and_css($count);
1980 } else {
1981 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
1982 return '<p align="center">' . join (', ', map {
1983 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
1984 } splice(@tags, 0, $count)) . '</p>';
1988 sub git_get_project_url_list {
1989 my $path = shift;
1991 $git_dir = "$projectroot/$path";
1992 open my $fd, '<', "$git_dir/cloneurl"
1993 or return wantarray ?
1994 @{ config_to_multi(git_get_project_config('url')) } :
1995 config_to_multi(git_get_project_config('url'));
1996 my @git_project_url_list = map { chomp; $_ } <$fd>;
1997 close $fd;
1999 return wantarray ? @git_project_url_list : \@git_project_url_list;
2002 sub git_get_projects_list {
2003 my ($filter) = @_;
2004 my @list;
2006 $filter ||= '';
2007 $filter =~ s/\.git$//;
2009 my $check_forks = gitweb_check_feature('forks');
2011 if (-d $projects_list) {
2012 # search in directory
2013 my $dir = $projects_list . ($filter ? "/$filter" : '');
2014 # remove the trailing "/"
2015 $dir =~ s!/+$!!;
2016 my $pfxlen = length("$dir");
2017 my $pfxdepth = ($dir =~ tr!/!!);
2019 File::Find::find({
2020 follow_fast => 1, # follow symbolic links
2021 follow_skip => 2, # ignore duplicates
2022 dangling_symlinks => 0, # ignore dangling symlinks, silently
2023 wanted => sub {
2024 # skip project-list toplevel, if we get it.
2025 return if (m!^[/.]$!);
2026 # only directories can be git repositories
2027 return unless (-d $_);
2028 # don't traverse too deep (Find is super slow on os x)
2029 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2030 $File::Find::prune = 1;
2031 return;
2034 my $subdir = substr($File::Find::name, $pfxlen + 1);
2035 # we check related file in $projectroot
2036 my $path = ($filter ? "$filter/" : '') . $subdir;
2037 if (check_export_ok("$projectroot/$path")) {
2038 push @list, { path => $path };
2039 $File::Find::prune = 1;
2042 }, "$dir");
2044 } elsif (-f $projects_list) {
2045 # read from file(url-encoded):
2046 # 'git%2Fgit.git Linus+Torvalds'
2047 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2048 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2049 my %paths;
2050 open my $fd, '<', $projects_list or return;
2051 PROJECT:
2052 while (my $line = <$fd>) {
2053 chomp $line;
2054 my ($path, $owner) = split ' ', $line;
2055 $path = unescape($path);
2056 $owner = unescape($owner);
2057 if (!defined $path) {
2058 next;
2060 if ($filter ne '') {
2061 # looking for forks;
2062 my $pfx = substr($path, 0, length($filter));
2063 if ($pfx ne $filter) {
2064 next PROJECT;
2066 my $sfx = substr($path, length($filter));
2067 if ($sfx !~ /^\/.*\.git$/) {
2068 next PROJECT;
2070 } elsif ($check_forks) {
2071 PATH:
2072 foreach my $filter (keys %paths) {
2073 # looking for forks;
2074 my $pfx = substr($path, 0, length($filter));
2075 if ($pfx ne $filter) {
2076 next PATH;
2078 my $sfx = substr($path, length($filter));
2079 if ($sfx !~ /^\/.*\.git$/) {
2080 next PATH;
2082 # is a fork, don't include it in
2083 # the list
2084 next PROJECT;
2087 if (check_export_ok("$projectroot/$path")) {
2088 my $pr = {
2089 path => $path,
2090 owner => to_utf8($owner),
2092 push @list, $pr;
2093 (my $forks_path = $path) =~ s/\.git$//;
2094 $paths{$forks_path}++;
2097 close $fd;
2099 return @list;
2102 our $gitweb_project_owner = undef;
2103 sub git_get_project_list_from_file {
2105 return if (defined $gitweb_project_owner);
2107 $gitweb_project_owner = {};
2108 # read from file (url-encoded):
2109 # 'git%2Fgit.git Linus+Torvalds'
2110 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2111 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2112 if (-f $projects_list) {
2113 open(my $fd, '<', $projects_list);
2114 while (my $line = <$fd>) {
2115 chomp $line;
2116 my ($pr, $ow) = split ' ', $line;
2117 $pr = unescape($pr);
2118 $ow = unescape($ow);
2119 $gitweb_project_owner->{$pr} = to_utf8($ow);
2121 close $fd;
2125 sub git_get_project_owner {
2126 my $project = shift;
2127 my $owner;
2129 return undef unless $project;
2130 $git_dir = "$projectroot/$project";
2132 if (!defined $gitweb_project_owner) {
2133 git_get_project_list_from_file();
2136 if (exists $gitweb_project_owner->{$project}) {
2137 $owner = $gitweb_project_owner->{$project};
2139 if (!defined $owner){
2140 $owner = git_get_project_config('owner');
2142 if (!defined $owner) {
2143 $owner = get_file_owner("$git_dir");
2146 return $owner;
2149 sub git_get_last_activity {
2150 my ($path) = @_;
2151 my $fd;
2153 $git_dir = "$projectroot/$path";
2154 open($fd, "-|", git_cmd(), 'for-each-ref',
2155 '--format=%(committer)',
2156 '--sort=-committerdate',
2157 '--count=1',
2158 'refs/heads') or return;
2159 my $most_recent = <$fd>;
2160 close $fd or return;
2161 if (defined $most_recent &&
2162 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2163 my $timestamp = $1;
2164 my $age = time - $timestamp;
2165 return ($age, age_string($age));
2167 return (undef, undef);
2170 sub git_get_references {
2171 my $type = shift || "";
2172 my %refs;
2173 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2174 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2175 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2176 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2177 or return;
2179 while (my $line = <$fd>) {
2180 chomp $line;
2181 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2182 if (defined $refs{$1}) {
2183 push @{$refs{$1}}, $2;
2184 } else {
2185 $refs{$1} = [ $2 ];
2189 close $fd or return;
2190 return \%refs;
2193 sub git_get_rev_name_tags {
2194 my $hash = shift || return undef;
2196 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2197 or return;
2198 my $name_rev = <$fd>;
2199 close $fd;
2201 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2202 return $1;
2203 } else {
2204 # catches also '$hash undefined' output
2205 return undef;
2209 ## ----------------------------------------------------------------------
2210 ## parse to hash functions
2212 sub parse_date {
2213 my $epoch = shift;
2214 my $tz = shift || "-0000";
2216 my %date;
2217 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2218 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2219 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2220 $date{'hour'} = $hour;
2221 $date{'minute'} = $min;
2222 $date{'mday'} = $mday;
2223 $date{'day'} = $days[$wday];
2224 $date{'month'} = $months[$mon];
2225 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2226 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2227 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2228 $mday, $months[$mon], $hour ,$min;
2229 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2230 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2232 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2233 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2234 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2235 $date{'hour_local'} = $hour;
2236 $date{'minute_local'} = $min;
2237 $date{'tz_local'} = $tz;
2238 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2239 1900+$year, $mon+1, $mday,
2240 $hour, $min, $sec, $tz);
2241 return %date;
2244 sub parse_tag {
2245 my $tag_id = shift;
2246 my %tag;
2247 my @comment;
2249 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2250 $tag{'id'} = $tag_id;
2251 while (my $line = <$fd>) {
2252 chomp $line;
2253 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2254 $tag{'object'} = $1;
2255 } elsif ($line =~ m/^type (.+)$/) {
2256 $tag{'type'} = $1;
2257 } elsif ($line =~ m/^tag (.+)$/) {
2258 $tag{'name'} = $1;
2259 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2260 $tag{'author'} = $1;
2261 $tag{'author_epoch'} = $2;
2262 $tag{'author_tz'} = $3;
2263 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2264 $tag{'author_name'} = $1;
2265 $tag{'author_email'} = $2;
2266 } else {
2267 $tag{'author_name'} = $tag{'author'};
2269 } elsif ($line =~ m/--BEGIN/) {
2270 push @comment, $line;
2271 last;
2272 } elsif ($line eq "") {
2273 last;
2276 push @comment, <$fd>;
2277 $tag{'comment'} = \@comment;
2278 close $fd or return;
2279 if (!defined $tag{'name'}) {
2280 return
2282 return %tag
2285 sub parse_commit_text {
2286 my ($commit_text, $withparents) = @_;
2287 my @commit_lines = split '\n', $commit_text;
2288 my %co;
2290 pop @commit_lines; # Remove '\0'
2292 if (! @commit_lines) {
2293 return;
2296 my $header = shift @commit_lines;
2297 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2298 return;
2300 ($co{'id'}, my @parents) = split ' ', $header;
2301 while (my $line = shift @commit_lines) {
2302 last if $line eq "\n";
2303 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2304 $co{'tree'} = $1;
2305 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2306 push @parents, $1;
2307 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2308 $co{'author'} = to_utf8($1);
2309 $co{'author_epoch'} = $2;
2310 $co{'author_tz'} = $3;
2311 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2312 $co{'author_name'} = $1;
2313 $co{'author_email'} = $2;
2314 } else {
2315 $co{'author_name'} = $co{'author'};
2317 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2318 $co{'committer'} = to_utf8($1);
2319 $co{'committer_epoch'} = $2;
2320 $co{'committer_tz'} = $3;
2321 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2322 $co{'committer_name'} = $1;
2323 $co{'committer_email'} = $2;
2324 } else {
2325 $co{'committer_name'} = $co{'committer'};
2329 if (!defined $co{'tree'}) {
2330 return;
2332 $co{'parents'} = \@parents;
2333 $co{'parent'} = $parents[0];
2335 foreach my $title (@commit_lines) {
2336 $title =~ s/^ //;
2337 if ($title ne "") {
2338 $co{'title'} = chop_str($title, 80, 5);
2339 # remove leading stuff of merges to make the interesting part visible
2340 if (length($title) > 50) {
2341 $title =~ s/^Automatic //;
2342 $title =~ s/^merge (of|with) /Merge ... /i;
2343 if (length($title) > 50) {
2344 $title =~ s/(http|rsync):\/\///;
2346 if (length($title) > 50) {
2347 $title =~ s/(master|www|rsync)\.//;
2349 if (length($title) > 50) {
2350 $title =~ s/kernel.org:?//;
2352 if (length($title) > 50) {
2353 $title =~ s/\/pub\/scm//;
2356 $co{'title_short'} = chop_str($title, 50, 5);
2357 last;
2360 if (! defined $co{'title'} || $co{'title'} eq "") {
2361 $co{'title'} = $co{'title_short'} = '(no commit message)';
2363 # remove added spaces
2364 foreach my $line (@commit_lines) {
2365 $line =~ s/^ //;
2367 $co{'comment'} = \@commit_lines;
2369 my $age = time - $co{'committer_epoch'};
2370 $co{'age'} = $age;
2371 $co{'age_string'} = age_string($age);
2372 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2373 if ($age > 60*60*24*7*2) {
2374 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2375 $co{'age_string_age'} = $co{'age_string'};
2376 } else {
2377 $co{'age_string_date'} = $co{'age_string'};
2378 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2380 return %co;
2383 sub parse_commit {
2384 my ($commit_id) = @_;
2385 my %co;
2387 local $/ = "\0";
2389 open my $fd, "-|", git_cmd(), "rev-list",
2390 "--parents",
2391 "--header",
2392 "--max-count=1",
2393 $commit_id,
2394 "--",
2395 or die_error(500, "Open git-rev-list failed");
2396 %co = parse_commit_text(<$fd>, 1);
2397 close $fd;
2399 return %co;
2402 sub parse_commits {
2403 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2404 my @cos;
2406 $maxcount ||= 1;
2407 $skip ||= 0;
2409 local $/ = "\0";
2411 open my $fd, "-|", git_cmd(), "rev-list",
2412 "--header",
2413 @args,
2414 ("--max-count=" . $maxcount),
2415 ("--skip=" . $skip),
2416 @extra_options,
2417 $commit_id,
2418 "--",
2419 ($filename ? ($filename) : ())
2420 or die_error(500, "Open git-rev-list failed");
2421 while (my $line = <$fd>) {
2422 my %co = parse_commit_text($line);
2423 push @cos, \%co;
2425 close $fd;
2427 return wantarray ? @cos : \@cos;
2430 # parse line of git-diff-tree "raw" output
2431 sub parse_difftree_raw_line {
2432 my $line = shift;
2433 my %res;
2435 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2436 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2437 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2438 $res{'from_mode'} = $1;
2439 $res{'to_mode'} = $2;
2440 $res{'from_id'} = $3;
2441 $res{'to_id'} = $4;
2442 $res{'status'} = $5;
2443 $res{'similarity'} = $6;
2444 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2445 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2446 } else {
2447 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2450 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2451 # combined diff (for merge commit)
2452 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2453 $res{'nparents'} = length($1);
2454 $res{'from_mode'} = [ split(' ', $2) ];
2455 $res{'to_mode'} = pop @{$res{'from_mode'}};
2456 $res{'from_id'} = [ split(' ', $3) ];
2457 $res{'to_id'} = pop @{$res{'from_id'}};
2458 $res{'status'} = [ split('', $4) ];
2459 $res{'to_file'} = unquote($5);
2461 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2462 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2463 $res{'commit'} = $1;
2466 return wantarray ? %res : \%res;
2469 # wrapper: return parsed line of git-diff-tree "raw" output
2470 # (the argument might be raw line, or parsed info)
2471 sub parsed_difftree_line {
2472 my $line_or_ref = shift;
2474 if (ref($line_or_ref) eq "HASH") {
2475 # pre-parsed (or generated by hand)
2476 return $line_or_ref;
2477 } else {
2478 return parse_difftree_raw_line($line_or_ref);
2482 # parse line of git-ls-tree output
2483 sub parse_ls_tree_line {
2484 my $line = shift;
2485 my %opts = @_;
2486 my %res;
2488 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2489 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2491 $res{'mode'} = $1;
2492 $res{'type'} = $2;
2493 $res{'hash'} = $3;
2494 if ($opts{'-z'}) {
2495 $res{'name'} = $4;
2496 } else {
2497 $res{'name'} = unquote($4);
2500 return wantarray ? %res : \%res;
2503 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2504 sub parse_from_to_diffinfo {
2505 my ($diffinfo, $from, $to, @parents) = @_;
2507 if ($diffinfo->{'nparents'}) {
2508 # combined diff
2509 $from->{'file'} = [];
2510 $from->{'href'} = [];
2511 fill_from_file_info($diffinfo, @parents)
2512 unless exists $diffinfo->{'from_file'};
2513 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2514 $from->{'file'}[$i] =
2515 defined $diffinfo->{'from_file'}[$i] ?
2516 $diffinfo->{'from_file'}[$i] :
2517 $diffinfo->{'to_file'};
2518 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2519 $from->{'href'}[$i] = href(action=>"blob",
2520 hash_base=>$parents[$i],
2521 hash=>$diffinfo->{'from_id'}[$i],
2522 file_name=>$from->{'file'}[$i]);
2523 } else {
2524 $from->{'href'}[$i] = undef;
2527 } else {
2528 # ordinary (not combined) diff
2529 $from->{'file'} = $diffinfo->{'from_file'};
2530 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2531 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2532 hash=>$diffinfo->{'from_id'},
2533 file_name=>$from->{'file'});
2534 } else {
2535 delete $from->{'href'};
2539 $to->{'file'} = $diffinfo->{'to_file'};
2540 if (!is_deleted($diffinfo)) { # file exists in result
2541 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2542 hash=>$diffinfo->{'to_id'},
2543 file_name=>$to->{'file'});
2544 } else {
2545 delete $to->{'href'};
2549 ## ......................................................................
2550 ## parse to array of hashes functions
2552 sub git_get_heads_list {
2553 my $limit = shift;
2554 my @headslist;
2556 open my $fd, '-|', git_cmd(), 'for-each-ref',
2557 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2558 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2559 'refs/heads'
2560 or return;
2561 while (my $line = <$fd>) {
2562 my %ref_item;
2564 chomp $line;
2565 my ($refinfo, $committerinfo) = split(/\0/, $line);
2566 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2567 my ($committer, $epoch, $tz) =
2568 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2569 $ref_item{'fullname'} = $name;
2570 $name =~ s!^refs/heads/!!;
2572 $ref_item{'name'} = $name;
2573 $ref_item{'id'} = $hash;
2574 $ref_item{'title'} = $title || '(no commit message)';
2575 $ref_item{'epoch'} = $epoch;
2576 if ($epoch) {
2577 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2578 } else {
2579 $ref_item{'age'} = "unknown";
2582 push @headslist, \%ref_item;
2584 close $fd;
2586 return wantarray ? @headslist : \@headslist;
2589 sub git_get_tags_list {
2590 my $limit = shift;
2591 my @tagslist;
2593 open my $fd, '-|', git_cmd(), 'for-each-ref',
2594 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2595 '--format=%(objectname) %(objecttype) %(refname) '.
2596 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2597 'refs/tags'
2598 or return;
2599 while (my $line = <$fd>) {
2600 my %ref_item;
2602 chomp $line;
2603 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2604 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2605 my ($creator, $epoch, $tz) =
2606 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2607 $ref_item{'fullname'} = $name;
2608 $name =~ s!^refs/tags/!!;
2610 $ref_item{'type'} = $type;
2611 $ref_item{'id'} = $id;
2612 $ref_item{'name'} = $name;
2613 if ($type eq "tag") {
2614 $ref_item{'subject'} = $title;
2615 $ref_item{'reftype'} = $reftype;
2616 $ref_item{'refid'} = $refid;
2617 } else {
2618 $ref_item{'reftype'} = $type;
2619 $ref_item{'refid'} = $id;
2622 if ($type eq "tag" || $type eq "commit") {
2623 $ref_item{'epoch'} = $epoch;
2624 if ($epoch) {
2625 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2626 } else {
2627 $ref_item{'age'} = "unknown";
2631 push @tagslist, \%ref_item;
2633 close $fd;
2635 return wantarray ? @tagslist : \@tagslist;
2638 ## ----------------------------------------------------------------------
2639 ## filesystem-related functions
2641 sub get_file_owner {
2642 my $path = shift;
2644 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2645 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2646 if (!defined $gcos) {
2647 return undef;
2649 my $owner = $gcos;
2650 $owner =~ s/[,;].*$//;
2651 return to_utf8($owner);
2654 # assume that file exists
2655 sub insert_file {
2656 my $filename = shift;
2658 my $output = "";
2660 open my $fd, '<', $filename;
2661 my @toutf8 = map { to_utf8($_) } <$fd>;
2662 foreach( @toutf8 ){
2663 $output .= $_;
2665 close $fd;
2667 return $output;
2670 ## ......................................................................
2671 ## mimetype related functions
2673 sub mimetype_guess_file {
2674 my $filename = shift;
2675 my $mimemap = shift;
2676 -r $mimemap or return undef;
2678 my %mimemap;
2679 open(my $mh, '<', $mimemap) or return undef;
2680 while (<$mh>) {
2681 next if m/^#/; # skip comments
2682 my ($mimetype, $exts) = split(/\t+/);
2683 if (defined $exts) {
2684 my @exts = split(/\s+/, $exts);
2685 foreach my $ext (@exts) {
2686 $mimemap{$ext} = $mimetype;
2690 close($mh);
2692 $filename =~ /\.([^.]*)$/;
2693 return $mimemap{$1};
2696 sub mimetype_guess {
2697 my $filename = shift;
2698 my $mime;
2699 $filename =~ /\./ or return undef;
2701 if ($mimetypes_file) {
2702 my $file = $mimetypes_file;
2703 if ($file !~ m!^/!) { # if it is relative path
2704 # it is relative to project
2705 $file = "$projectroot/$project/$file";
2707 $mime = mimetype_guess_file($filename, $file);
2709 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2710 return $mime;
2713 sub blob_mimetype {
2714 my $fd = shift;
2715 my $filename = shift;
2717 if ($filename) {
2718 my $mime = mimetype_guess($filename);
2719 $mime and return $mime;
2722 # just in case
2723 return $default_blob_plain_mimetype unless $fd;
2725 if (-T $fd) {
2726 return 'text/plain';
2727 } elsif (! $filename) {
2728 return 'application/octet-stream';
2729 } elsif ($filename =~ m/\.png$/i) {
2730 return 'image/png';
2731 } elsif ($filename =~ m/\.gif$/i) {
2732 return 'image/gif';
2733 } elsif ($filename =~ m/\.jpe?g$/i) {
2734 return 'image/jpeg';
2735 } else {
2736 return 'application/octet-stream';
2740 sub blob_contenttype {
2741 my ($fd, $file_name, $type) = @_;
2743 $type ||= blob_mimetype($fd, $file_name);
2744 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
2745 $type .= "; charset=$default_text_plain_charset";
2748 return $type;
2751 ## ======================================================================
2752 ## functions printing HTML: header, footer, error page
2754 sub git_header_html {
2755 my $status = shift || "200 OK";
2756 my $expires = shift;
2758 my $output = "";
2760 my $title = "$site_name";
2761 if (defined $project) {
2762 $title .= " - " . to_utf8($project);
2763 if (defined $action) {
2764 $title .= "/$action";
2765 if (defined $file_name) {
2766 $title .= " - " . esc_path($file_name);
2767 if ($action eq "tree" && $file_name !~ m|/$|) {
2768 $title .= "/";
2773 my $content_type;
2774 # require explicit support from the UA if we are to send the page as
2775 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2776 # we have to do this because MSIE sometimes globs '*/*', pretending to
2777 # support xhtml+xml but choking when it gets what it asked for.
2778 #if (defined $::cgi->http('HTTP_ACCEPT') &&
2779 # $::cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2780 # $::cgi->Accept('application/xhtml+xml') != 0) {
2781 # $content_type = 'application/xhtml+xml';
2782 #} else {
2783 $content_type = 'text/html';
2785 $output .= $cgi->header(-type=>$content_type, -charset => 'utf-8',
2786 -status=> $status, -expires => $expires);
2787 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2788 $output .= <<EOF;
2789 <?xml version="1.0" encoding="utf-8"?>
2790 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2791 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2792 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2793 <!-- git core binaries version $git_version -->
2794 <head>
2795 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2796 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2797 <meta name="robots" content="index, nofollow"/>
2798 <title>$title</title>
2800 if($headerRefresh){
2801 $output .= "<meta http-equiv=\"refresh\" content=\"1\"/>\n";
2804 # the stylesheet, favicon etc urls won't work correctly with path_info
2805 # unless we set the appropriate base URL
2806 if ($ENV{'PATH_INFO'}) {
2807 $output .= "<base href=\"".esc_url($base_url)."\" />\n";
2809 # print out each stylesheet that exist, providing backwards capability
2810 # for those people who defined $stylesheet in a config file
2811 if (defined $stylesheet) {
2812 $output .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2813 } else {
2814 foreach my $stylesheet (@stylesheets) {
2815 next unless $stylesheet;
2816 $output .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2819 if (defined $project) {
2820 my %href_params = get_feed_info();
2821 if (!exists $href_params{'-title'}) {
2822 $href_params{'-title'} = 'log';
2825 foreach my $format qw(RSS Atom) {
2826 my $type = lc($format);
2827 my %link_attr = (
2828 '-rel' => 'alternate',
2829 '-title' => "$project - $href_params{'-title'} - $format feed",
2830 '-type' => "application/$type+xml"
2833 $href_params{'action'} = $type;
2834 $link_attr{'-href'} = href(%href_params);
2835 $output .= "<link ".
2836 "rel=\"$link_attr{'-rel'}\" ".
2837 "title=\"$link_attr{'-title'}\" ".
2838 "href=\"$link_attr{'-href'}\" ".
2839 "type=\"$link_attr{'-type'}\" ".
2840 "/>\n";
2842 $href_params{'extra_options'} = '--no-merges';
2843 $link_attr{'-href'} = href(%href_params);
2844 $link_attr{'-title'} .= ' (no merges)';
2845 $output .= "<link ".
2846 "rel=\"$link_attr{'-rel'}\" ".
2847 "title=\"$link_attr{'-title'}\" ".
2848 "href=\"$link_attr{'-href'}\" ".
2849 "type=\"$link_attr{'-type'}\" ".
2850 "/>\n";
2853 } else {
2854 $output .= sprintf('<link rel="alternate" title="%s projects list" '.
2855 'href="%s" type="text/plain; charset=utf-8" />'."\n",
2856 $site_name, href(project=>undef, action=>"project_index"));
2857 $output .= sprintf('<link rel="alternate" title="%s projects feeds" '.
2858 'href="%s" type="text/x-opml" />'."\n",
2859 $site_name, href(project=>undef, action=>"opml"));
2861 if (defined $favicon) {
2862 $output .= qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
2865 $output .= "</head>\n" .
2866 "<body>\n";
2868 if ($site_header && -f $site_header) {
2869 $output .= insert_file($site_header);
2872 $output .= "<div class=\"page_header\">\n" .
2873 $cgi->a({-href => esc_url($logo_url),
2874 -title => $logo_label},
2875 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2876 $output .= $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2877 if (defined $project) {
2878 $output .= $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2879 if (defined $action) {
2880 $output .= " / $action";
2882 $output .= "\n";
2884 $output .= "</div>\n";
2886 my $have_search = gitweb_check_feature('search');
2887 if (defined $project && $have_search) {
2888 if (!defined $searchtext) {
2889 $searchtext = "";
2891 my $search_hash;
2892 if (defined $hash_base) {
2893 $search_hash = $hash_base;
2894 } elsif (defined $hash) {
2895 $search_hash = $hash;
2896 } else {
2897 $search_hash = "HEAD";
2899 my $action = $my_uri;
2900 my $use_pathinfo = gitweb_check_feature('pathinfo');
2901 if ($use_pathinfo) {
2902 $action .= "/".esc_url($project);
2904 $output .= $cgi->startform(-method => "get", -action => $action) .
2905 "<div class=\"search\">\n" .
2906 (!$use_pathinfo &&
2907 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
2908 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
2909 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
2910 $cgi->popup_menu(-name => 'st', -default => 'commit',
2911 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2912 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2913 " search:\n".
2914 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2915 "<span title=\"Extended regular expression\">" .
2916 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
2917 -checked => $search_use_regexp) .
2918 "</span>" .
2919 "</div>" .
2920 $cgi->end_form() . "\n";
2922 $output .= "</div>\n";
2924 return $output;
2927 sub git_footer_html {
2928 my $output;
2930 my $feed_class = 'rss_logo';
2931 $output .= "<div class=\"page_footer\">\n";
2932 $output .= "<div class=\"cachetime\">Cache Last Updated: ". gmtime( time ) ." GMT</div>\n";
2933 if (defined $project) {
2934 my $descr = git_get_project_description($project);
2935 if (defined $descr) {
2936 $output .= "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2939 my %href_params = get_feed_info();
2940 if (!%href_params) {
2941 $feed_class .= ' generic';
2943 $href_params{'-title'} ||= 'log';
2945 foreach my $format qw(RSS Atom) {
2946 $href_params{'action'} = lc($format);
2947 $output .= $cgi->a({-href => href(%href_params),
2948 -title => "$href_params{'-title'} $format feed",
2949 -class => $feed_class}, $format)."\n";
2952 } else {
2953 $output .= $cgi->a({-href => href(project=>undef, action=>"opml"),
2954 -class => $feed_class}, "OPML") . " ";
2955 $output .= $cgi->a({-href => href(project=>undef, action=>"project_index"),
2956 -class => $feed_class}, "TXT") . "\n";
2958 $output .= "</div>\n"; # class="page_footer"
2960 if (-f $site_footer) {
2961 $output .= insert_file($site_footer);
2964 $output .= "</body>\n" .
2965 "</html>";
2968 # die_error(<http_status_code>, <error_message>)
2969 # Example: die_error(404, 'Hash not found')
2970 # By convention, use the following status codes (as defined in RFC 2616):
2971 # 400: Invalid or missing CGI parameters, or
2972 # requested object exists but has wrong type.
2973 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
2974 # this server or project.
2975 # 404: Requested object/revision/project doesn't exist.
2976 # 500: The server isn't configured properly, or
2977 # an internal error occurred (e.g. failed assertions caused by bugs), or
2978 # an unknown error occurred (e.g. the git binary died unexpectedly).
2979 sub die_error {
2980 my $status = shift || 500;
2981 my $error = shift || "Internal server error";
2983 my %http_responses = (400 => '400 Bad Request',
2984 403 => '403 Forbidden',
2985 404 => '404 Not Found',
2986 500 => '500 Internal Server Error');
2987 git_header_html($http_responses{$status});
2988 print <<EOF;
2989 <div class="page_body">
2990 <br /><br />
2991 $status - $error
2992 <br />
2993 </div>
2995 git_footer_html();
2996 exit;
2999 ## ----------------------------------------------------------------------
3000 ## functions printing or outputting HTML: navigation
3002 sub git_print_page_nav {
3003 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3004 my $output = "";
3005 $extra = '' if !defined $extra; # pager or formats
3007 my @navs = qw(summary shortlog log commit commitdiff tree);
3008 if ($suppress) {
3009 @navs = grep { $_ ne $suppress } @navs;
3012 my %arg = map { $_ => {action=>$_} } @navs;
3013 if (defined $head) {
3014 for (qw(commit commitdiff)) {
3015 $arg{$_}{'hash'} = $head;
3017 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3018 for (qw(shortlog log)) {
3019 $arg{$_}{'hash'} = $head;
3024 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3025 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3027 my @actions = gitweb_get_feature('actions');
3028 my %repl = (
3029 '%' => '%',
3030 'n' => $project, # project name
3031 'f' => $git_dir, # project path within filesystem
3032 'h' => $treehead || '', # current hash ('h' parameter)
3033 'b' => $treebase || '', # hash base ('hb' parameter)
3035 while (@actions) {
3036 my ($label, $link, $pos) = splice(@actions,0,3);
3037 # insert
3038 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3039 # munch munch
3040 $link =~ s/%([%nfhb])/$repl{$1}/g;
3041 $arg{$label}{'_href'} = $link;
3044 $output .= "<div class=\"page_nav\">\n" .
3045 (join " | ",
3046 map { $_ eq $current ?
3047 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3048 } @navs);
3049 $output .= "<br/>\n$extra<br/>\n" .
3050 "</div>\n";
3053 sub format_paging_nav {
3054 my ($action, $hash, $head, $page, $has_next_link) = @_;
3055 my $paging_nav;
3058 if ($hash ne $head || $page) {
3059 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3060 } else {
3061 $paging_nav .= "HEAD";
3064 if ($page > 0) {
3065 $paging_nav .= " &sdot; " .
3066 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3067 -accesskey => "p", -title => "Alt-p"}, "prev");
3068 } else {
3069 $paging_nav .= " &sdot; prev";
3072 if ($has_next_link) {
3073 $paging_nav .= " &sdot; " .
3074 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3075 -accesskey => "n", -title => "Alt-n"}, "next");
3076 } else {
3077 $paging_nav .= " &sdot; next";
3080 return $paging_nav;
3083 ## ......................................................................
3084 ## functions printing or outputting HTML: div
3086 sub git_print_header_div {
3087 my ($action, $title, $hash, $hash_base) = @_;
3088 my %args = ();
3089 my $output = "";
3091 $args{'action'} = $action;
3092 $args{'hash'} = $hash if $hash;
3093 $args{'hash_base'} = $hash_base if $hash_base;
3095 $output .= "<div class=\"header\">\n" .
3096 $cgi->a({-href => href(%args), -class => "title"},
3097 $title ? $title : $action) .
3098 "\n</div>\n";
3099 return $output;
3102 sub print_local_time {
3103 print get_local_time(@_);
3106 sub get_local_time {
3107 my $localtime = "";
3108 my %date = @_;
3109 if ($date{'hour_local'} < 6) {
3110 $localtime .= sprintf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3111 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3112 } else {
3113 $localtime .= sprintf(" (%02d:%02d %s)",
3114 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3117 return $localtime
3120 # Outputs the author name and date in long form
3121 sub git_print_authorship {
3122 my $co = shift;
3123 my $output = "";
3125 my %opts = @_;
3126 my $tag = $opts{-tag} || 'div';
3128 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3129 $output .= "<$tag class=\"author_date\">" .
3130 esc_html($co->{'author_name'}) .
3131 " [$ad{'rfc2822'}";
3132 $output .= get_local_time(%ad) if ($opts{-localtime});
3133 $output .= "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3134 . "</$tag>\n";
3136 return $output;
3139 # Outputs table rows containing the full author or committer information,
3140 # in the format expected for 'commit' view (& similia).
3141 # Parameters are a commit hash reference, followed by the list of people
3142 # to output information for. If the list is empty it defalts to both
3143 # author and committer.
3144 sub git_print_authorship_rows {
3145 my $output = "";
3147 my $co = shift;
3148 # too bad we can't use @people = @_ || ('author', 'committer')
3149 my @people = @_;
3150 @people = ('author', 'committer') unless @people;
3151 foreach my $who (@people) {
3152 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3153 $output .= "<tr><td>$who</td><td>" . esc_html($co->{$who}) . "</td>" .
3154 "<td rowspan=\"2\">" .
3155 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3156 "</td></tr>\n" .
3157 "<tr>" .
3158 "<td></td><td> $wd{'rfc2822'}";
3159 $output .= get_local_time(%wd);
3160 $output .= "</td>" .
3161 "</tr>\n";
3164 return $output;
3167 sub git_print_page_path {
3168 my $name = shift;
3169 my $type = shift;
3170 my $hb = shift;
3172 my $output = "";
3174 $output .= "<div class=\"page_path\">";
3175 $output .= $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3176 -title => 'tree root'}, to_utf8("[$project]"));
3177 $output .= " / ";
3178 if (defined $name) {
3179 my @dirname = split '/', $name;
3180 my $basename = pop @dirname;
3181 my $fullname = '';
3183 foreach my $dir (@dirname) {
3184 $fullname .= ($fullname ? '/' : '') . $dir;
3185 $output .= $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3186 hash_base=>$hb),
3187 -title => $fullname}, esc_path($dir));
3188 $output .= " / ";
3190 if (defined $type && $type eq 'blob') {
3191 $output .= $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3192 hash_base=>$hb),
3193 -title => $name}, esc_path($basename));
3194 } elsif (defined $type && $type eq 'tree') {
3195 $output .= $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3196 hash_base=>$hb),
3197 -title => $name}, esc_path($basename));
3198 $output .= " / ";
3199 } else {
3200 $output .= esc_path($basename);
3203 $output .= "<br/></div>\n";
3205 return $output;
3208 sub git_print_log {
3209 my $log = shift;
3210 my %opts = @_;
3212 my $output = "";
3214 if ($opts{'-remove_title'}) {
3215 # remove title, i.e. first line of log
3216 shift @$log;
3218 # remove leading empty lines
3219 while (defined $log->[0] && $log->[0] eq "") {
3220 shift @$log;
3223 # print log
3224 my $signoff = 0;
3225 my $empty = 0;
3226 foreach my $line (@$log) {
3227 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3228 $signoff = 1;
3229 $empty = 0;
3230 if (! $opts{'-remove_signoff'}) {
3231 $output .= "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3232 next;
3233 } else {
3234 # remove signoff lines
3235 next;
3237 } else {
3238 $signoff = 0;
3241 # print only one empty line
3242 # do not print empty line after signoff
3243 if ($line eq "") {
3244 next if ($empty || $signoff);
3245 $empty = 1;
3246 } else {
3247 $empty = 0;
3250 $output .= format_log_line_html($line) . "<br/>\n";
3253 if ($opts{'-final_empty_line'}) {
3254 # end with single empty line
3255 $output .= "<br/>\n" unless $empty;
3258 return $output;
3261 # return link target (what link points to)
3262 sub git_get_link_target {
3263 my $hash = shift;
3264 my $link_target;
3266 # read link
3267 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3268 or return;
3270 local $/ = undef;
3271 $link_target = <$fd>;
3273 close $fd
3274 or return;
3276 return $link_target;
3279 # given link target, and the directory (basedir) the link is in,
3280 # return target of link relative to top directory (top tree);
3281 # return undef if it is not possible (including absolute links).
3282 sub normalize_link_target {
3283 my ($link_target, $basedir) = @_;
3285 # absolute symlinks (beginning with '/') cannot be normalized
3286 return if (substr($link_target, 0, 1) eq '/');
3288 # normalize link target to path from top (root) tree (dir)
3289 my $path;
3290 if ($basedir) {
3291 $path = $basedir . '/' . $link_target;
3292 } else {
3293 # we are in top (root) tree (dir)
3294 $path = $link_target;
3297 # remove //, /./, and /../
3298 my @path_parts;
3299 foreach my $part (split('/', $path)) {
3300 # discard '.' and ''
3301 next if (!$part || $part eq '.');
3302 # handle '..'
3303 if ($part eq '..') {
3304 if (@path_parts) {
3305 pop @path_parts;
3306 } else {
3307 # link leads outside repository (outside top dir)
3308 return;
3310 } else {
3311 push @path_parts, $part;
3314 $path = join('/', @path_parts);
3316 return $path;
3319 # print tree entry (row of git_tree), but without encompassing <tr> element
3320 sub git_print_tree_entry {
3321 my ($t, $basedir, $hash_base, $have_blame) = @_;
3323 my $output = "";
3325 my %base_key = ();
3326 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3328 # The format of a table row is: mode list link. Where mode is
3329 # the mode of the entry, list is the name of the entry, an href,
3330 # and link is the action links of the entry.
3332 $output .= "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3333 if ($t->{'type'} eq "blob") {
3334 $output .= "<td class=\"list\">" .
3335 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3336 file_name=>"$basedir$t->{'name'}", %base_key),
3337 -class => "list"}, esc_path($t->{'name'}));
3338 if (S_ISLNK(oct $t->{'mode'})) {
3339 my $link_target = git_get_link_target($t->{'hash'});
3340 if ($link_target) {
3341 my $norm_target = normalize_link_target($link_target, $basedir);
3342 if (defined $norm_target) {
3343 $output .= " -> " .
3344 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3345 file_name=>$norm_target),
3346 -title => $norm_target}, esc_path($link_target));
3347 } else {
3348 $output .= " -> " . esc_path($link_target);
3352 $output .= "</td>\n";
3353 $output .= "<td class=\"link\">";
3354 $output .= $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3355 file_name=>"$basedir$t->{'name'}", %base_key)},
3356 "blob");
3357 if ($have_blame) {
3358 $output .= " | " .
3359 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3360 file_name=>"$basedir$t->{'name'}", %base_key)},
3361 "blame");
3363 if (defined $hash_base) {
3364 $output .= " | " .
3365 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3366 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3367 "history");
3369 $output .= " | " .
3370 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3371 file_name=>"$basedir$t->{'name'}")},
3372 "raw");
3373 $output .= "</td>\n";
3375 } elsif ($t->{'type'} eq "tree") {
3376 $output .= "<td class=\"list\">";
3377 $output .= $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3378 file_name=>"$basedir$t->{'name'}", %base_key)},
3379 esc_path($t->{'name'}));
3380 $output .= "</td>\n";
3381 $output .= "<td class=\"link\">";
3382 $output .= $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3383 file_name=>"$basedir$t->{'name'}", %base_key)},
3384 "tree");
3385 if (defined $hash_base) {
3386 $output .= " | " .
3387 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3388 file_name=>"$basedir$t->{'name'}")},
3389 "history");
3391 $output .= "</td>\n";
3392 } else {
3393 # unknown object: we can only present history for it
3394 # (this includes 'commit' object, i.e. submodule support)
3395 $output .= "<td class=\"list\">" .
3396 esc_path($t->{'name'}) .
3397 "</td>\n";
3398 $output .= "<td class=\"link\">";
3399 if (defined $hash_base) {
3400 $output .= $cgi->a({-href => href(action=>"history",
3401 hash_base=>$hash_base,
3402 file_name=>"$basedir$t->{'name'}")},
3403 "history");
3405 $output .= "</td>\n";
3408 return $output;
3411 ## ......................................................................
3412 ## functions printing large fragments of HTML
3414 # get pre-image filenames for merge (combined) diff
3415 sub fill_from_file_info {
3416 my ($diff, @parents) = @_;
3418 $diff->{'from_file'} = [ ];
3419 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3420 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3421 if ($diff->{'status'}[$i] eq 'R' ||
3422 $diff->{'status'}[$i] eq 'C') {
3423 $diff->{'from_file'}[$i] =
3424 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3428 return $diff;
3431 # is current raw difftree line of file deletion
3432 sub is_deleted {
3433 my $diffinfo = shift;
3435 return $diffinfo->{'to_id'} eq ('0' x 40);
3438 # does patch correspond to [previous] difftree raw line
3439 # $diffinfo - hashref of parsed raw diff format
3440 # $patchinfo - hashref of parsed patch diff format
3441 # (the same keys as in $diffinfo)
3442 sub is_patch_split {
3443 my ($diffinfo, $patchinfo) = @_;
3445 return defined $diffinfo && defined $patchinfo
3446 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3450 sub git_difftree_body {
3451 my $output = "";
3453 my ($difftree, $hash, @parents) = @_;
3454 my ($parent) = $parents[0];
3455 my $have_blame = gitweb_check_feature('blame');
3456 $output .= "<div class=\"list_head\">\n";
3457 if ($#{$difftree} > 10) {
3458 $output .= (($#{$difftree} + 1) . " files changed:\n");
3460 $output .= "</div>\n";
3462 $output .= "<table class=\"" .
3463 (@parents > 1 ? "combined " : "") .
3464 "diff_tree\">\n";
3466 # header only for combined diff in 'commitdiff' view
3467 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3468 if ($has_header) {
3469 # table header
3470 $output .= "<thead><tr>\n" .
3471 "<th></th><th></th>\n"; # filename, patchN link
3472 for (my $i = 0; $i < @parents; $i++) {
3473 my $par = $parents[$i];
3474 $output .= "<th>" .
3475 $cgi->a({-href => href(action=>"commitdiff",
3476 hash=>$hash, hash_parent=>$par),
3477 -title => 'commitdiff to parent number ' .
3478 ($i+1) . ': ' . substr($par,0,7)},
3479 $i+1) .
3480 "&nbsp;</th>\n";
3482 $output .= "</tr></thead>\n<tbody>\n";
3485 my $alternate = 1;
3486 my $patchno = 0;
3487 foreach my $line (@{$difftree}) {
3488 my $diff = parsed_difftree_line($line);
3490 if ($alternate) {
3491 $output .= "<tr class=\"dark\">\n";
3492 } else {
3493 $output .= "<tr class=\"light\">\n";
3495 $alternate ^= 1;
3497 if (exists $diff->{'nparents'}) { # combined diff
3499 fill_from_file_info($diff, @parents)
3500 unless exists $diff->{'from_file'};
3502 if (!is_deleted($diff)) {
3503 # file exists in the result (child) commit
3504 $output .= "<td>" .
3505 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3506 file_name=>$diff->{'to_file'},
3507 hash_base=>$hash),
3508 -class => "list"}, esc_path($diff->{'to_file'})) .
3509 "</td>\n";
3510 } else {
3511 $output .= "<td>" .
3512 esc_path($diff->{'to_file'}) .
3513 "</td>\n";
3516 if ($action eq 'commitdiff') {
3517 # link to patch
3518 $patchno++;
3519 $output .= "<td class=\"link\">" .
3520 $cgi->a({-href => "#patch$patchno"}, "patch") .
3521 " | " .
3522 "</td>\n";
3525 my $has_history = 0;
3526 my $not_deleted = 0;
3527 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3528 my $hash_parent = $parents[$i];
3529 my $from_hash = $diff->{'from_id'}[$i];
3530 my $from_path = $diff->{'from_file'}[$i];
3531 my $status = $diff->{'status'}[$i];
3533 $has_history ||= ($status ne 'A');
3534 $not_deleted ||= ($status ne 'D');
3536 if ($status eq 'A') {
3537 $output .= "<td class=\"link\" align=\"right\"> | </td>\n";
3538 } elsif ($status eq 'D') {
3539 $output .= "<td class=\"link\">" .
3540 $cgi->a({-href => href(action=>"blob",
3541 hash_base=>$hash,
3542 hash=>$from_hash,
3543 file_name=>$from_path)},
3544 "blob" . ($i+1)) .
3545 " | </td>\n";
3546 } else {
3547 if ($diff->{'to_id'} eq $from_hash) {
3548 $output .= "<td class=\"link nochange\">";
3549 } else {
3550 $output .= "<td class=\"link\">";
3552 $output .= $cgi->a({-href => href(action=>"blobdiff",
3553 hash=>$diff->{'to_id'},
3554 hash_parent=>$from_hash,
3555 hash_base=>$hash,
3556 hash_parent_base=>$hash_parent,
3557 file_name=>$diff->{'to_file'},
3558 file_parent=>$from_path)},
3559 "diff" . ($i+1)) .
3560 " | </td>\n";
3564 $output .= "<td class=\"link\">";
3565 if ($not_deleted) {
3566 $output .= $cgi->a({-href => href(action=>"blob",
3567 hash=>$diff->{'to_id'},
3568 file_name=>$diff->{'to_file'},
3569 hash_base=>$hash)},
3570 "blob");
3571 $output .= " | " if ($has_history);
3573 if ($has_history) {
3574 $output .= $cgi->a({-href => href(action=>"history",
3575 file_name=>$diff->{'to_file'},
3576 hash_base=>$hash)},
3577 "history");
3579 $output .= "</td>\n";
3581 $output .= "</tr>\n";
3582 next; # instead of 'else' clause, to avoid extra indent
3584 # else ordinary diff
3586 my ($to_mode_oct, $to_mode_str, $to_file_type);
3587 my ($from_mode_oct, $from_mode_str, $from_file_type);
3588 if ($diff->{'to_mode'} ne ('0' x 6)) {
3589 $to_mode_oct = oct $diff->{'to_mode'};
3590 if (S_ISREG($to_mode_oct)) { # only for regular file
3591 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3593 $to_file_type = file_type($diff->{'to_mode'});
3595 if ($diff->{'from_mode'} ne ('0' x 6)) {
3596 $from_mode_oct = oct $diff->{'from_mode'};
3597 if (S_ISREG($to_mode_oct)) { # only for regular file
3598 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3600 $from_file_type = file_type($diff->{'from_mode'});
3603 if ($diff->{'status'} eq "A") { # created
3604 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3605 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3606 $mode_chng .= "]</span>";
3607 $output .= "<td>";
3608 $output .= $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3609 hash_base=>$hash, file_name=>$diff->{'file'}),
3610 -class => "list"}, esc_path($diff->{'file'}));
3611 $output .= "</td>\n";
3612 $output .= "<td>$mode_chng</td>\n";
3613 $output .= "<td class=\"link\">";
3614 if ($action eq 'commitdiff') {
3615 # link to patch
3616 $patchno++;
3617 $output .= $cgi->a({-href => "#patch$patchno"}, "patch");
3618 $output .= " | ";
3620 $output .= $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3621 hash_base=>$hash, file_name=>$diff->{'file'})},
3622 "blob");
3623 $output .= "</td>\n";
3625 } elsif ($diff->{'status'} eq "D") { # deleted
3626 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3627 $output .= "<td>";
3628 $output .= $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3629 hash_base=>$parent, file_name=>$diff->{'file'}),
3630 -class => "list"}, esc_path($diff->{'file'}));
3631 $output .= "</td>\n";
3632 $output .= "<td>$mode_chng</td>\n";
3633 $output .= "<td class=\"link\">";
3634 if ($action eq 'commitdiff') {
3635 # link to patch
3636 $patchno++;
3637 $output .= $cgi->a({-href => "#patch$patchno"}, "patch");
3638 $output .= " | ";
3640 $output .= $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3641 hash_base=>$parent, file_name=>$diff->{'file'})},
3642 "blob") . " | ";
3643 if ($have_blame) {
3644 $output .= $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3645 file_name=>$diff->{'file'})},
3646 "blame") . " | ";
3648 $output .= $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3649 file_name=>$diff->{'file'})},
3650 "history");
3651 $output .= "</td>\n";
3653 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3654 my $mode_chnge = "";
3655 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3656 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3657 if ($from_file_type ne $to_file_type) {
3658 $mode_chnge .= " from $from_file_type to $to_file_type";
3660 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3661 if ($from_mode_str && $to_mode_str) {
3662 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3663 } elsif ($to_mode_str) {
3664 $mode_chnge .= " mode: $to_mode_str";
3667 $mode_chnge .= "]</span>\n";
3669 $output .= "<td>";
3670 $output .= $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3671 hash_base=>$hash, file_name=>$diff->{'file'}),
3672 -class => "list"}, esc_path($diff->{'file'}));
3673 $output .= "</td>\n";
3674 $output .= "<td>$mode_chnge</td>\n";
3675 $output .= "<td class=\"link\">";
3676 if ($action eq 'commitdiff') {
3677 # link to patch
3678 $patchno++;
3679 $output .= $cgi->a({-href => "#patch$patchno"}, "patch") .
3680 " | ";
3681 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3682 # "commit" view and modified file (not onlu mode changed)
3683 $output .= $cgi->a({-href => href(action=>"blobdiff",
3684 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3685 hash_base=>$hash, hash_parent_base=>$parent,
3686 file_name=>$diff->{'file'})},
3687 "diff") .
3688 " | ";
3690 $output .= $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3691 hash_base=>$hash, file_name=>$diff->{'file'})},
3692 "blob") . " | ";
3693 if ($have_blame) {
3694 $output .= $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3695 file_name=>$diff->{'file'})},
3696 "blame") . " | ";
3698 $output .= $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3699 file_name=>$diff->{'file'})},
3700 "history");
3701 $output .= "</td>\n";
3703 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3704 my %status_name = ('R' => 'moved', 'C' => 'copied');
3705 my $nstatus = $status_name{$diff->{'status'}};
3706 my $mode_chng = "";
3707 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3708 # mode also for directories, so we cannot use $to_mode_str
3709 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3711 $output .= "<td>" .
3712 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3713 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3714 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3715 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3716 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3717 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3718 -class => "list"}, esc_path($diff->{'from_file'})) .
3719 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3720 "<td class=\"link\">";
3721 if ($action eq 'commitdiff') {
3722 # link to patch
3723 $patchno++;
3724 $output .= $cgi->a({-href => "#patch$patchno"}, "patch") .
3725 " | ";
3726 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3727 # "commit" view and modified file (not only pure rename or copy)
3728 $output .= $cgi->a({-href => href(action=>"blobdiff",
3729 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3730 hash_base=>$hash, hash_parent_base=>$parent,
3731 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3732 "diff") .
3733 " | ";
3735 $output .= $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3736 hash_base=>$parent, file_name=>$diff->{'to_file'})},
3737 "blob") . " | ";
3738 if ($have_blame) {
3739 $output .= $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3740 file_name=>$diff->{'to_file'})},
3741 "blame") . " | ";
3743 $output .= $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3744 file_name=>$diff->{'to_file'})},
3745 "history");
3746 $output .= "</td>\n";
3748 } # we should not encounter Unmerged (U) or Unknown (X) status
3749 $output .= "</tr>\n";
3751 $output .= "</tbody>" if $has_header;
3752 $output .= "</table>\n";
3754 return $output;
3757 sub git_patchset_body {
3758 my ($fd, $difftree, $hash, @hash_parents) = @_;
3759 my ($hash_parent) = $hash_parents[0];
3761 my $is_combined = (@hash_parents > 1);
3762 my $patch_idx = 0;
3763 my $patch_number = 0;
3764 my $patch_line;
3765 my $diffinfo;
3766 my $to_name;
3767 my (%from, %to);
3769 my $output = "";
3771 $output .= "<div class=\"patchset\">\n";
3773 # skip to first patch
3774 while ($patch_line = <$fd>) {
3775 chomp $patch_line;
3777 last if ($patch_line =~ m/^diff /);
3780 PATCH:
3781 while ($patch_line) {
3783 # parse "git diff" header line
3784 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
3785 # $1 is from_name, which we do not use
3786 $to_name = unquote($2);
3787 $to_name =~ s!^b/!!;
3788 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
3789 # $1 is 'cc' or 'combined', which we do not use
3790 $to_name = unquote($2);
3791 } else {
3792 $to_name = undef;
3795 # check if current patch belong to current raw line
3796 # and parse raw git-diff line if needed
3797 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
3798 # this is continuation of a split patch
3799 $output .= "<div class=\"patch cont\">\n";
3800 } else {
3801 # advance raw git-diff output if needed
3802 $patch_idx++ if defined $diffinfo;
3804 # read and prepare patch information
3805 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3807 # compact combined diff output can have some patches skipped
3808 # find which patch (using pathname of result) we are at now;
3809 if ($is_combined) {
3810 while ($to_name ne $diffinfo->{'to_file'}) {
3811 $output .= "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3812 format_diff_cc_simplified($diffinfo, @hash_parents) .
3813 "</div>\n"; # class="patch"
3815 $patch_idx++;
3816 $patch_number++;
3818 last if $patch_idx > $#$difftree;
3819 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3823 # modifies %from, %to hashes
3824 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3826 # this is first patch for raw difftree line with $patch_idx index
3827 # we index @$difftree array from 0, but number patches from 1
3828 $output .= "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3831 # git diff header
3832 #assert($patch_line =~ m/^diff /) if DEBUG;
3833 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3834 $patch_number++;
3835 # print "git diff" header
3836 $output .= format_git_diff_header_line($patch_line, $diffinfo,
3837 \%from, \%to);
3839 # print extended diff header
3840 $output .= "<div class=\"diff extended_header\">\n";
3841 EXTENDED_HEADER:
3842 while ($patch_line = <$fd>) {
3843 chomp $patch_line;
3845 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3847 $output .= format_extended_diff_header_line($patch_line, $diffinfo,
3848 \%from, \%to);
3850 $output .= "</div>\n"; # class="diff extended_header"
3852 # from-file/to-file diff header
3853 if (! $patch_line) {
3854 $output .= "</div>\n"; # class="patch"
3855 last PATCH;
3857 next PATCH if ($patch_line =~ m/^diff /);
3858 #assert($patch_line =~ m/^---/) if DEBUG;
3860 my $last_patch_line = $patch_line;
3861 $patch_line = <$fd>;
3862 chomp $patch_line;
3863 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3865 $output .= format_diff_from_to_header($last_patch_line, $patch_line,
3866 $diffinfo, \%from, \%to,
3867 @hash_parents);
3869 # the patch itself
3870 LINE:
3871 while ($patch_line = <$fd>) {
3872 chomp $patch_line;
3874 next PATCH if ($patch_line =~ m/^diff /);
3876 $output .= format_diff_line($patch_line, \%from, \%to);
3879 } continue {
3880 $output .= "</div>\n"; # class="patch"
3883 # for compact combined (--cc) format, with chunk and patch simpliciaction
3884 # patchset might be empty, but there might be unprocessed raw lines
3885 for (++$patch_idx if $patch_number > 0;
3886 $patch_idx < @$difftree;
3887 ++$patch_idx) {
3888 # read and prepare patch information
3889 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3891 # generate anchor for "patch" links in difftree / whatchanged part
3892 $output .= "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3893 format_diff_cc_simplified($diffinfo, @hash_parents) .
3894 "</div>\n"; # class="patch"
3896 $patch_number++;
3899 if ($patch_number == 0) {
3900 if (@hash_parents > 1) {
3901 $output .= "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3902 } else {
3903 $output .= "<div class=\"diff nodifferences\">No differences found</div>\n";
3907 $output .= "</div>\n"; # class="patchset"
3910 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3912 # fills project list info (age, description, owner, forks) for each
3913 # project in the list, removing invalid projects from returned list
3914 # NOTE: modifies $projlist, but does not remove entries from it
3915 sub fill_project_list_info {
3916 my ($projlist, $check_forks) = @_;
3917 my @projects;
3919 my $output = "";
3921 my $show_ctags = gitweb_check_feature('ctags');
3922 PROJECT:
3923 foreach my $pr (@$projlist) {
3924 my (@activity) = git_get_last_activity($pr->{'path'});
3925 unless (@activity) {
3926 next PROJECT;
3928 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
3929 if (!defined $pr->{'descr'}) {
3930 my $descr = git_get_project_description($pr->{'path'}) || "";
3931 $descr = to_utf8($descr);
3932 $pr->{'descr_long'} = $descr;
3933 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3935 if (!defined $pr->{'owner'}) {
3936 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3938 if ($check_forks) {
3939 my $pname = $pr->{'path'};
3940 if (($pname =~ s/\.git$//) &&
3941 ($pname !~ /\/$/) &&
3942 (-d "$projectroot/$pname")) {
3943 $pr->{'forks'} = "-d $projectroot/$pname";
3944 } else {
3945 $pr->{'forks'} = 0;
3948 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
3949 push @projects, $pr;
3952 return @projects;
3955 # print 'sort by' <th> element, generating 'sort by $name' replay link
3956 # if that order is not selected
3957 sub print_sort_th {
3958 print get_sort_th(@_);
3961 sub get_sort_th {
3962 my ($name, $order, $header) = @_;
3963 my $sortth = "";
3964 $header ||= ucfirst($name);
3966 if ($order eq $name) {
3967 $sortth .= "<th>$header</th>\n";
3968 } else {
3969 $sortth .= "<th>" .
3970 $cgi->a({-href => href(-replay=>1, order=>$name),
3971 -class => "header"}, $header) .
3972 "</th>\n";
3975 return $sortth;
3978 sub git_project_list_body {
3979 # actually uses global variable $project
3980 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3982 my $output = "";
3984 my $check_forks = gitweb_check_feature('forks');
3985 my @projects = fill_project_list_info($projlist, $check_forks);
3987 $order ||= $default_projects_order;
3988 $from = 0 unless defined $from;
3989 $to = $#projects if (!defined $to || $#projects < $to);
3991 my %order_info = (
3992 project => { key => 'path', type => 'str' },
3993 descr => { key => 'descr_long', type => 'str' },
3994 owner => { key => 'owner', type => 'str' },
3995 age => { key => 'age', type => 'num' }
3997 my $oi = $order_info{$order};
3998 if ($oi->{'type'} eq 'str') {
3999 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4000 } else {
4001 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4004 my $show_ctags = gitweb_check_feature('ctags');
4005 if ($show_ctags) {
4006 my %ctags;
4007 foreach my $p (@projects) {
4008 foreach my $ct (keys %{$p->{'ctags'}}) {
4009 $ctags{$ct} += $p->{'ctags'}->{$ct};
4012 my $cloud = git_populate_project_tagcloud(\%ctags);
4013 $output .= git_show_project_tagcloud($cloud, 64);
4016 $output .= "<table class=\"project_list\">\n";
4017 unless ($no_header) {
4018 $output .= "<tr>\n";
4019 if ($check_forks) {
4020 $output .= "<th></th>\n";
4022 $output .= get_sort_th('project', $order, 'Project');
4023 $output .= get_sort_th('descr', $order, 'Description');
4024 $output .= get_sort_th('owner', $order, 'Owner');
4025 $output .= get_sort_th('age', $order, 'Last Change');
4026 $output .= "<th></th>\n" . # for links
4027 "</tr>\n";
4029 my $alternate = 1;
4030 my $tagfilter = $cgi->param('by_tag');
4031 for (my $i = $from; $i <= $to; $i++) {
4032 my $pr = $projects[$i];
4034 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4035 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4036 and not $pr->{'descr_long'} =~ /$searchtext/;
4037 # Weed out forks or non-matching entries of search
4038 if ($check_forks) {
4039 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4040 $forkbase="^$forkbase" if $forkbase;
4041 next if not $searchtext and not $tagfilter and $show_ctags
4042 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4045 if ($alternate) {
4046 $output .= "<tr class=\"dark\">\n";
4047 } else {
4048 $output .= "<tr class=\"light\">\n";
4050 #$alternate ^= 1;
4051 if ($check_forks) {
4052 $output .= "<td>";
4053 if ($pr->{'forks'}) {
4054 $output .= "<!-- $pr->{'forks'} -->\n";
4055 $output .= $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4057 $output .= "</td>\n";
4059 $output .= "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4060 -class => "list"}, esc_html($pr->{'path'})) ."</td>\n".
4061 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4062 -class => "list", -title => $pr->{'descr_long'}},
4063 esc_html($pr->{'descr'})) . "</td>\n" .
4064 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4065 $output .= "<td class=\"". age_class($pr->{'age'}) . "\">" .
4066 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4067 "<td class=\"link\">" .
4068 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4069 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4070 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4071 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4072 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '');
4073 if( $gitlinkurl ne '' ){
4074 $output .= " | ". $cgi->a({-href => "git://$gitlinkurl/".esc_html($pr->{'path'})}, "git");
4076 $output .= "".
4077 "</td>\n" .
4078 "</tr>\n";
4079 $alternate ^= 1;
4081 if (defined $extra) {
4082 $output .= "<tr>\n";
4083 if ($check_forks) {
4084 $output .= "<td></td>\n";
4086 $output .= "<td colspan=\"5\">$extra</td>\n" .
4087 "</tr>\n";
4089 $output .= "</table>\n";
4091 return $output;
4094 sub git_shortlog_body {
4095 # uses global variable $project
4096 my ($commitlist, $from, $to, $refs, $extra) = @_;
4098 $from = 0 unless defined $from;
4099 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4101 my $output = "";
4103 $output .= "<table class=\"shortlog\">\n";
4104 my $alternate = 1;
4105 for (my $i = $from; $i <= $to; $i++) {
4106 my %co = %{$commitlist->[$i]};
4107 my $commit = $co{'id'};
4108 my $ref = format_ref_marker($refs, $commit);
4109 if ($alternate) {
4110 $output .= "<tr class=\"dark\">\n";
4111 } else {
4112 $output .= "<tr class=\"light\">\n";
4114 $alternate ^= 1;
4115 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4116 $output .= "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4117 format_author_html('td', \%co, 10) . "<td>";
4118 $output .= format_subject_html($co{'title'}, $co{'title_short'},
4119 href(action=>"commit", hash=>$commit), $ref);
4120 $output .= "</td>\n" .
4121 "<td class=\"link\">" .
4122 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4123 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4124 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4125 my $snapshot_links = format_snapshot_links($commit);
4126 if (defined $snapshot_links) {
4127 $output .= " | " . $snapshot_links;
4129 $output .= "</td>\n" .
4130 "</tr>\n";
4132 if (defined $extra) {
4133 $output .= "<tr>\n" .
4134 "<td colspan=\"4\">$extra</td>\n" .
4135 "</tr>\n";
4137 $output .= "</table>\n";
4139 return $output;
4142 sub git_history_body {
4143 # Warning: assumes constant type (blob or tree) during history
4144 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4146 my $output = "";
4148 $from = 0 unless defined $from;
4149 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4151 $output .= "<table class=\"history\">\n";
4152 my $alternate = 1;
4153 for (my $i = $from; $i <= $to; $i++) {
4154 my %co = %{$commitlist->[$i]};
4155 if (!%co) {
4156 next;
4158 my $commit = $co{'id'};
4160 my $ref = format_ref_marker($refs, $commit);
4162 if ($alternate) {
4163 $output .= "<tr class=\"dark\">\n";
4164 } else {
4165 $output .= "<tr class=\"light\">\n";
4167 $alternate ^= 1;
4168 $output .= "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4169 # shortlog: format_author_html('td', \%co, 10)
4170 format_author_html('td', \%co, 15, 3) . "<td>";
4171 # originally git_history used chop_str($co{'title'}, 50)
4172 $output .= format_subject_html($co{'title'}, $co{'title_short'},
4173 href(action=>"commit", hash=>$commit), $ref);
4174 $output .= "</td>\n" .
4175 "<td class=\"link\">" .
4176 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4177 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4179 if ($ftype eq 'blob') {
4180 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4181 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4182 if (defined $blob_current && defined $blob_parent &&
4183 $blob_current ne $blob_parent) {
4184 $output .= " | " .
4185 $cgi->a({-href => href(action=>"blobdiff",
4186 hash=>$blob_current, hash_parent=>$blob_parent,
4187 hash_base=>$hash_base, hash_parent_base=>$commit,
4188 file_name=>$file_name)},
4189 "diff to current");
4192 $output .= "</td>\n" .
4193 "</tr>\n";
4195 if (defined $extra) {
4196 $output .= "<tr>\n" .
4197 "<td colspan=\"4\">$extra</td>\n" .
4198 "</tr>\n";
4200 $output .= "</table>\n";
4202 return $output;
4205 sub git_tags_body {
4206 # uses global variable $project
4207 my ($taglist, $from, $to, $extra) = @_;
4208 $from = 0 unless defined $from;
4209 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4211 my $output = "";
4213 $output .= "<table class=\"tags\">\n";
4214 my $alternate = 1;
4215 for (my $i = $from; $i <= $to; $i++) {
4216 my $entry = $taglist->[$i];
4217 my %tag = %$entry;
4218 my $comment = $tag{'subject'};
4219 my $comment_short;
4220 if (defined $comment) {
4221 $comment_short = chop_str($comment, 30, 5);
4223 if ($alternate) {
4224 $output .= "<tr class=\"dark\">\n";
4225 } else {
4226 $output .= "<tr class=\"light\">\n";
4228 $alternate ^= 1;
4229 if (defined $tag{'age'}) {
4230 $output .= "<td><i>$tag{'age'}</i></td>\n";
4231 } else {
4232 $output .= "<td></td>\n";
4234 $output .= "<td>" .
4235 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4236 -class => "list name"}, esc_html($tag{'name'})) .
4237 "</td>\n" .
4238 "<td>";
4239 if (defined $comment) {
4240 $output .= format_subject_html($comment, $comment_short,
4241 href(action=>"tag", hash=>$tag{'id'}));
4243 $output .= "</td>\n" .
4244 "<td class=\"selflink\">";
4245 if ($tag{'type'} eq "tag") {
4246 $output .= $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4247 } else {
4248 $output .= "&nbsp;";
4250 $output .= "</td>\n" .
4251 "<td class=\"link\">" . " | " .
4252 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4253 if ($tag{'reftype'} eq "commit") {
4254 $output .= " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4255 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4256 } elsif ($tag{'reftype'} eq "blob") {
4257 $output .= " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4259 $output .= "</td>\n" .
4260 "</tr>";
4262 if (defined $extra) {
4263 $output .= "<tr>\n" .
4264 "<td colspan=\"5\">$extra</td>\n" .
4265 "</tr>\n";
4267 $output .= "</table>\n";
4269 return $output;
4272 sub git_heads_body {
4273 # uses global variable $project
4274 my ($headlist, $head, $from, $to, $extra) = @_;
4275 $from = 0 unless defined $from;
4276 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4278 my $output = "";
4280 $output .= "<table class=\"heads\">\n";
4281 my $alternate = 1;
4282 for (my $i = $from; $i <= $to; $i++) {
4283 my $entry = $headlist->[$i];
4284 my %ref = %$entry;
4285 my $curr = $ref{'id'} eq $head;
4286 if ($alternate) {
4287 $output .= "<tr class=\"dark\">\n";
4288 } else {
4289 $output .= "<tr class=\"light\">\n";
4291 $alternate ^= 1;
4292 $output .= "<td><i>$ref{'age'}</i></td>\n" .
4293 ($curr ? "<td class=\"current_head\">" : "<td>") .
4294 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4295 -class => "list name"},esc_html($ref{'name'})) .
4296 "</td>\n" .
4297 "<td class=\"link\">" .
4298 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4299 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4300 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4301 "</td>\n" .
4302 "</tr>";
4304 if (defined $extra) {
4305 $output .= "<tr>\n" .
4306 "<td colspan=\"3\">$extra</td>\n" .
4307 "</tr>\n";
4309 $output .= "</table>\n";
4311 return $output;
4314 sub git_search_grep_body {
4315 my ($commitlist, $from, $to, $extra) = @_;
4316 $from = 0 unless defined $from;
4317 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4319 my $output = "";
4321 $output .= "<table class=\"commit_search\">\n";
4322 my $alternate = 1;
4323 for (my $i = $from; $i <= $to; $i++) {
4324 my %co = %{$commitlist->[$i]};
4325 if (!%co) {
4326 next;
4328 my $commit = $co{'id'};
4329 if ($alternate) {
4330 $output .= "<tr class=\"dark\">\n";
4331 } else {
4332 $output .= "<tr class=\"light\">\n";
4334 $alternate ^= 1;
4335 $output .= "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4336 format_author_html('td', \%co, 15, 5) .
4337 "<td>" .
4338 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4339 -class => "list subject"},
4340 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4341 my $comment = $co{'comment'};
4342 foreach my $line (@$comment) {
4343 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4344 my ($lead, $match, $trail) = ($1, $2, $3);
4345 $match = chop_str($match, 70, 5, 'center');
4346 my $contextlen = int((80 - length($match))/2);
4347 $contextlen = 30 if ($contextlen > 30);
4348 $lead = chop_str($lead, $contextlen, 10, 'left');
4349 $trail = chop_str($trail, $contextlen, 10, 'right');
4351 $lead = esc_html($lead);
4352 $match = esc_html($match);
4353 $trail = esc_html($trail);
4355 $output .= "$lead<span class=\"match\">$match</span>$trail<br />";
4358 $output .= "</td>\n" .
4359 "<td class=\"link\">" .
4360 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4361 " | " .
4362 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4363 " | " .
4364 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4365 $output .= "</td>\n" .
4366 "</tr>\n";
4368 if (defined $extra) {
4369 $output .= "<tr>\n" .
4370 "<td colspan=\"3\">$extra</td>\n" .
4371 "</tr>\n";
4373 $output .= "</table>\n";
4375 return $output;
4378 ## ======================================================================
4379 ## ======================================================================
4380 ## actions
4382 sub git_project_list {
4383 my $output = "";
4385 my $order = $input_params{'order'};
4386 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4387 die_error(400, "Unknown order parameter");
4390 my @list = git_get_projects_list();
4391 if (!@list) {
4392 die_error(404, "No projects found");
4395 $output .= git_header_html();
4396 if (-f $home_text) {
4397 $output .= "<div class=\"index_include\">\n";
4398 $output .= insert_file($home_text);
4399 $output .= "</div>\n";
4401 $output .= $cgi->startform(-method => "get") .
4402 "<p class=\"projsearch\">Search:\n" .
4403 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4404 "</p>" .
4405 $cgi->end_form() . "\n";
4406 $output .= git_project_list_body(\@list, $order);
4407 $output .= git_footer_html();
4409 return $output;
4412 sub git_forks {
4413 my $output = "";
4415 my $order = $input_params{'order'};
4416 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4417 die_error(400, "Unknown order parameter");
4420 my @list = git_get_projects_list($project);
4421 if (!@list) {
4422 die_error(404, "No forks found");
4425 $output .= git_header_html();
4426 $output .= git_print_page_nav('','');
4427 $output .= git_print_header_div('summary', "$project forks");
4428 $output .= git_project_list_body(\@list, $order);
4429 $output .= git_footer_html();
4431 return $output;
4434 sub git_project_index {
4435 my @projects = git_get_projects_list($project);
4437 my $output = "";
4439 $output .= $cgi->header(
4440 -type => 'text/plain',
4441 -charset => 'utf-8',
4442 -content_disposition => 'inline; filename="index.aux"');
4444 foreach my $pr (@projects) {
4445 if (!exists $pr->{'owner'}) {
4446 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4449 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4450 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4451 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4452 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4453 $path =~ s/ /\+/g;
4454 $owner =~ s/ /\+/g;
4456 $output .= "$path $owner\n";
4459 return $output;
4462 sub git_summary {
4463 my $descr = git_get_project_description($project) || "none";
4464 my %co = parse_commit("HEAD");
4465 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4466 my $head = $co{'id'};
4468 my $owner = git_get_project_owner($project);
4470 my $refs = git_get_references();
4471 # These get_*_list functions return one more to allow us to see if
4472 # there are more ...
4473 my @taglist = git_get_tags_list(16);
4474 my @headlist = git_get_heads_list(16);
4475 my @forklist;
4476 my $check_forks = gitweb_check_feature('forks');
4478 my $output = "";
4480 if ($check_forks) {
4481 @forklist = git_get_projects_list($project);
4484 $output .= git_header_html();
4485 $output .= git_print_page_nav('summary','', $head);
4487 $output .= "<div class=\"title\">&nbsp;</div>\n";
4488 $output .= "<table class=\"projects_list\">\n" .
4489 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4490 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4491 if (defined $cd{'rfc2822'}) {
4492 $output .= "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4495 # use per project git URL list in $projectroot/$project/cloneurl
4496 # or make project git URL from git base URL and project name
4497 my $url_tag = "URL";
4498 my @url_list = git_get_project_url_list($project);
4499 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4500 foreach my $git_url (@url_list) {
4501 next unless $git_url;
4502 $output .= "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4503 $url_tag = "";
4506 # Tag cloud
4507 my $show_ctags = gitweb_check_feature('ctags');
4508 if ($show_ctags) {
4509 my $ctags = git_get_project_ctags($project);
4510 my $cloud = git_populate_project_tagcloud($ctags);
4511 $output .= "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4512 $output .= "</td>\n<td>" unless %$ctags;
4513 $output .= "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4514 $output .= "</td>\n<td>" if %$ctags;
4515 $output .= git_show_project_tagcloud($cloud, 48);
4516 $output .= "</td></tr>";
4519 $output .= "</table>\n";
4521 # If XSS prevention is on, we don't include README.html.
4522 # TODO: Allow a readme in some safe format.
4523 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4524 $output .= "<div class=\"title\">readme</div>\n" .
4525 "<div class=\"readme\">\n";
4526 $output .= insert_file("$projectroot/$project/README.html");
4527 $output .= "\n</div>\n"; # class="readme"
4530 # we need to request one more than 16 (0..15) to check if
4531 # those 16 are all
4532 my @commitlist = $head ? parse_commits($head, 17) : ();
4533 if (@commitlist) {
4534 $output .= git_print_header_div('shortlog');
4535 $output .= git_shortlog_body(\@commitlist, 0, 15, $refs,
4536 $#commitlist <= 15 ? undef :
4537 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4540 if (@taglist) {
4541 $output .= git_print_header_div('tags');
4542 $output .= git_tags_body(\@taglist, 0, 15,
4543 $#taglist <= 15 ? undef :
4544 $cgi->a({-href => href(action=>"tags")}, "..."));
4547 if (@headlist) {
4548 $output .= git_print_header_div('heads');
4549 $output .= git_heads_body(\@headlist, $head, 0, 15,
4550 $#headlist <= 15 ? undef :
4551 $cgi->a({-href => href(action=>"heads")}, "..."));
4554 if (@forklist) {
4555 $output .= git_print_header_div('forks');
4556 $output .= git_project_list_body(\@forklist, 'age', 0, 15,
4557 $#forklist <= 15 ? undef :
4558 $cgi->a({-href => href(action=>"forks")}, "..."),
4559 'no_header');
4562 $output .= git_footer_html();
4564 return $output;
4567 sub git_tag {
4568 my $output = "";
4570 my $head = git_get_head_hash($project);
4571 $output .= git_header_html();
4572 $output .= git_print_page_nav('','', $head,undef,$head);
4573 my %tag = parse_tag($hash);
4575 if (! %tag) {
4576 die_error(404, "Unknown tag object");
4579 $output .= git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4580 $output .= "<div class=\"title_text\">\n" .
4581 "<table class=\"object_header\">\n" .
4582 "<tr>\n" .
4583 "<td>object</td>\n" .
4584 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4585 $tag{'object'}) . "</td>\n" .
4586 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4587 $tag{'type'}) . "</td>\n" .
4588 "</tr>\n";
4589 if (defined($tag{'author'})) {
4590 $output .= git_print_authorship_rows(\%tag, 'author');
4592 $output .= "</table>\n\n" .
4593 "</div>\n";
4594 $output .= "<div class=\"page_body\">";
4595 my $comment = $tag{'comment'};
4596 foreach my $line (@$comment) {
4597 chomp $line;
4598 $output .= esc_html($line, -nbsp=>1) . "<br/>\n";
4600 $output .= "</div>\n";
4601 $output .= git_footer_html();
4603 return $output;
4606 sub git_blame {
4607 my $output = "";
4609 # permissions
4610 gitweb_check_feature('blame')
4611 or die_error(403, "Blame view not allowed");
4613 # error checking
4614 die_error(400, "No file name given") unless $file_name;
4615 $hash_base ||= git_get_head_hash($project);
4616 die_error(404, "Couldn't find base commit") unless $hash_base;
4617 my %co = parse_commit($hash_base)
4618 or die_error(404, "Commit not found");
4619 my $ftype = "blob";
4620 if (!defined $hash) {
4621 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4622 or die_error(404, "Error looking up file");
4623 } else {
4624 $ftype = git_get_type($hash);
4625 if ($ftype !~ "blob") {
4626 die_error(400, "Object is not a blob");
4630 # run git-blame --porcelain
4631 open my $fd, "-|", git_cmd(), "blame", '-p',
4632 $hash_base, '--', $file_name
4633 or die_error(500, "Open git-blame failed");
4635 # page header
4636 $output .= git_header_html();
4637 my $formats_nav =
4638 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4639 "blob") .
4640 " | " .
4641 $cgi->a({-href => href(action=>"history", -replay=>1)},
4642 "history") .
4643 " | " .
4644 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4645 "HEAD");
4646 $output .= git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4647 $output .= git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4648 $output .= git_print_page_path($file_name, $ftype, $hash_base);
4650 # page body
4651 my @rev_color = qw(light dark);
4652 my $num_colors = scalar(@rev_color);
4653 my $current_color = 0;
4654 my %metainfo = ();
4656 $output .= <<HTML;
4657 <div class="page_body">
4658 <table class="blame">
4659 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4660 HTML
4661 LINE:
4662 while (my $line = <$fd>) {
4663 chomp $line;
4664 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4665 # no <lines in group> for subsequent lines in group of lines
4666 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4667 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
4668 if (!exists $metainfo{$full_rev}) {
4669 $metainfo{$full_rev} = { 'nprevious' => 0 };
4671 my $meta = $metainfo{$full_rev};
4672 my $data;
4673 while ($data = <$fd>) {
4674 chomp $data;
4675 last if ($data =~ s/^\t//); # contents of line
4676 if ($data =~ /^(\S+)(?: (.*))?$/) {
4677 $meta->{$1} = $2 unless exists $meta->{$1};
4679 if ($data =~ /^previous /) {
4680 $meta->{'nprevious'}++;
4683 my $short_rev = substr($full_rev, 0, 8);
4684 my $author = $meta->{'author'};
4685 my %date =
4686 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
4687 my $date = $date{'iso-tz'};
4688 if ($group_size) {
4689 $current_color = ($current_color + 1) % $num_colors;
4691 my $tr_class = $rev_color[$current_color];
4692 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
4693 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
4694 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
4695 $output .= "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
4696 if ($group_size) {
4697 $output .= "<td class=\"sha1\"";
4698 $output .= " title=\"". esc_html($author) . ", $date\"";
4699 $output .= " rowspan=\"$group_size\"" if ($group_size > 1);
4700 $output .= ">";
4701 $output .= $cgi->a({-href => href(action=>"commit",
4702 hash=>$full_rev,
4703 file_name=>$file_name)},
4704 esc_html($short_rev));
4705 if ($group_size >= 2) {
4706 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
4707 if (@author_initials) {
4708 $output .= "<br />" .
4709 esc_html(join('', @author_initials));
4710 # or join('.', ...)
4713 $output .= "</td>\n";
4715 # 'previous' <sha1 of parent commit> <filename at commit>
4716 if (exists $meta->{'previous'} &&
4717 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
4718 $meta->{'parent'} = $1;
4719 $meta->{'file_parent'} = unquote($2);
4721 my $linenr_commit =
4722 exists($meta->{'parent'}) ?
4723 $meta->{'parent'} : $full_rev;
4724 my $linenr_filename =
4725 exists($meta->{'file_parent'}) ?
4726 $meta->{'file_parent'} : unquote($meta->{'filename'});
4727 my $blamed = href(action => 'blame',
4728 file_name => $linenr_filename,
4729 hash_base => $linenr_commit);
4730 $output .= "<td class=\"linenr\">";
4731 $output .= $cgi->a({ -href => "$blamed#l$orig_lineno",
4732 -class => "linenr" },
4733 esc_html($lineno));
4734 $output .= "</td>";
4735 $output .= "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4736 $output .= "</tr>\n";
4738 $output .= "</table>\n";
4739 $output .= "</div>";
4740 close $fd
4741 or $output .= "Reading blob failed\n";
4743 # page footer
4744 $output .= git_footer_html();
4746 return $output;
4749 sub git_tags {
4751 my $output = "";
4753 my $head = git_get_head_hash($project);
4754 $output .= git_header_html();
4755 $output .= git_print_page_nav('','', $head,undef,$head);
4756 $output .= git_print_header_div('summary', $project);
4758 my @tagslist = git_get_tags_list();
4759 if (@tagslist) {
4760 $output .= git_tags_body(\@tagslist);
4762 $output .= git_footer_html();
4764 return $output;
4767 sub git_heads {
4769 my $output = "";
4771 my $head = git_get_head_hash($project);
4772 $output .= git_header_html();
4773 $output .= git_print_page_nav('','', $head,undef,$head);
4774 $output .= git_print_header_div('summary', $project);
4776 my @headslist = git_get_heads_list();
4777 if (@headslist) {
4778 $output .= git_heads_body(\@headslist, $head);
4780 $output .= git_footer_html();
4782 return $output;
4785 sub git_blob_plain {
4786 my $type = shift;
4787 my $expires;
4789 my $output = "";
4791 if (!defined $hash) {
4792 if (defined $file_name) {
4793 my $base = $hash_base || git_get_head_hash($project);
4794 $hash = git_get_hash_by_path($base, $file_name, "blob")
4795 or die_error(404, "Cannot find file");
4796 } else {
4797 die_error(400, "No file name defined");
4799 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4800 # blobs defined by non-textual hash id's can be cached
4801 $expires = "+1d";
4804 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4805 or die_error(500, "Open git-cat-file blob '$hash' failed");
4807 # content-type (can include charset)
4808 $type = blob_contenttype($fd, $file_name, $type);
4810 # "save as" filename, even when no $file_name is given
4811 my $save_as = "$hash";
4812 if (defined $file_name) {
4813 $save_as = $file_name;
4814 } elsif ($type =~ m/^text\//) {
4815 $save_as .= '.txt';
4818 # With XSS prevention on, blobs of all types except a few known safe
4819 # ones are served with "Content-Disposition: attachment" to make sure
4820 # they don't run in our security domain. For certain image types,
4821 # blob view writes an <img> tag referring to blob_plain view, and we
4822 # want to be sure not to break that by serving the image as an
4823 # attachment (though Firefox 3 doesn't seem to care).
4824 my $sandbox = $prevent_xss &&
4825 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
4827 $output .= $cgi->header(
4828 -type => $type,
4829 -expires => $expires,
4830 -content_disposition =>
4831 ($sandbox ? 'attachment' : 'inline')
4832 . '; filename="' . $save_as . '"');
4833 local $/ = undef;
4834 open BINOUT, '>', $fullhashbinpath or die_error(500, "Could not open bin dump file");
4835 binmode BINOUT, ':raw';
4836 print BINOUT <$fd>;
4837 binmode BINOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4838 close BINOUT;
4839 close $fd;
4841 return $output;
4844 sub git_blob {
4845 my $expires;
4847 my $output = "";
4849 if (!defined $hash) {
4850 if (defined $file_name) {
4851 my $base = $hash_base || git_get_head_hash($project);
4852 $hash = git_get_hash_by_path($base, $file_name, "blob")
4853 or die_error(404, "Cannot find file");
4854 } else {
4855 die_error(400, "No file name defined");
4857 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4858 # blobs defined by non-textual hash id's can be cached
4859 $expires = "+1d";
4862 my $have_blame = gitweb_check_feature('blame');
4863 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4864 or die_error(500, "Couldn't cat $file_name, $hash");
4865 my $mimetype = blob_mimetype($fd, $file_name);
4866 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
4867 close $fd;
4868 return git_blob_plain($mimetype);
4870 # we can have blame only for text/* mimetype
4871 $have_blame &&= ($mimetype =~ m!^text/!);
4873 $output .= git_header_html(undef, $expires);
4874 my $formats_nav = '';
4875 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4876 if (defined $file_name) {
4877 if ($have_blame) {
4878 $formats_nav .=
4879 $cgi->a({-href => href(action=>"blame", -replay=>1)},
4880 "blame") .
4881 " | ";
4883 $formats_nav .=
4884 $cgi->a({-href => href(action=>"history", -replay=>1)},
4885 "history") .
4886 " | " .
4887 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4888 "raw") .
4889 " | " .
4890 $cgi->a({-href => href(action=>"blob",
4891 hash_base=>"HEAD", file_name=>$file_name)},
4892 "HEAD");
4893 } else {
4894 $formats_nav .=
4895 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4896 "raw");
4898 $output .= git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4899 $output .= git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4900 } else {
4901 $output .= "<div class=\"page_nav\">\n" .
4902 "<br/><br/></div>\n" .
4903 "<div class=\"title\">$hash</div>\n";
4905 $output .= git_print_page_path($file_name, "blob", $hash_base);
4906 $output .= "<div class=\"page_body\">\n";
4907 if ($mimetype =~ m!^image/!) {
4908 $output .= qq!<img type="$mimetype"!;
4909 if ($file_name) {
4910 $output .= qq! alt="$file_name" title="$file_name"!;
4912 $output .= qq! src="! .
4913 href(action=>"blob_plain", hash=>$hash,
4914 hash_base=>$hash_base, file_name=>$file_name) .
4915 qq!" />\n!;
4916 } else {
4917 my $nr;
4918 while (my $line = <$fd>) {
4919 chomp $line;
4920 $nr++;
4921 $line = untabify($line);
4922 $output .= sprintf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4923 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4926 close $fd
4927 or $output .= "Reading blob failed.\n";
4928 $output .= "</div>";
4929 $output .= git_footer_html();
4931 return $output;
4934 sub git_tree {
4935 my $output = "";
4937 if (!defined $hash_base) {
4938 $hash_base = "HEAD";
4940 if (!defined $hash) {
4941 if (defined $file_name) {
4942 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4943 } else {
4944 $hash = $hash_base;
4947 die_error(404, "No such tree") unless defined($hash);
4949 my @entries = ();
4951 local $/ = "\0";
4952 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4953 or die_error(500, "Open git-ls-tree failed");
4954 @entries = map { chomp; $_ } <$fd>;
4955 close $fd
4956 or die_error(404, "Reading tree failed");
4959 my $refs = git_get_references();
4960 my $ref = format_ref_marker($refs, $hash_base);
4961 $output .= git_header_html();
4962 my $basedir = '';
4963 my $have_blame = gitweb_check_feature('blame');
4964 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4965 my @views_nav = ();
4966 if (defined $file_name) {
4967 push @views_nav,
4968 $output .= $cgi->a({-href => href(action=>"history", -replay=>1)},
4969 "history"),
4970 $output .= $cgi->a({-href => href(action=>"tree",
4971 hash_base=>"HEAD", file_name=>$file_name)},
4972 "HEAD"),
4974 my $snapshot_links = format_snapshot_links($hash);
4975 if (defined $snapshot_links) {
4976 # FIXME: Should be available when we have no hash base as well.
4977 push @views_nav, $snapshot_links;
4979 $output .= git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4980 $output .= git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4981 } else {
4982 undef $hash_base;
4983 $output .= "<div class=\"page_nav\">\n";
4984 $output .= "<br/><br/></div>\n";
4985 $output .= "<div class=\"title\">$hash</div>\n";
4987 if (defined $file_name) {
4988 $basedir = $file_name;
4989 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4990 $basedir .= '/';
4992 $output .= git_print_page_path($file_name, 'tree', $hash_base);
4994 $output .= "<div class=\"page_body\">\n";
4995 $output .= "<table class=\"tree\">\n";
4996 my $alternate = 1;
4997 # '..' (top directory) link if possible
4998 if (defined $hash_base &&
4999 defined $file_name && $file_name =~ m![^/]+$!) {
5000 if ($alternate) {
5001 $output .= "<tr class=\"dark\">\n";
5002 } else {
5003 $output .= "<tr class=\"light\">\n";
5005 $alternate ^= 1;
5007 my $up = $file_name;
5008 $up =~ s!/?[^/]+$!!;
5009 undef $up unless $up;
5010 # based on git_print_tree_entry
5011 $output .= '<td class="mode">' . mode_str('040000') . "</td>\n";
5012 $output .= '<td class="list">';
5013 $output .= $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
5014 file_name=>$up)},
5015 "..");
5016 $output .= "</td>\n";
5017 $output .= "<td class=\"link\"></td>\n";
5019 $output .= "</tr>\n";
5021 foreach my $line (@entries) {
5022 my %t = parse_ls_tree_line($line, -z => 1);
5024 if ($alternate) {
5025 $output .= "<tr class=\"dark\">\n";
5026 } else {
5027 $output .= "<tr class=\"light\">\n";
5029 $alternate ^= 1;
5031 $output .= git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5033 $output .= "</tr>\n";
5035 $output .= "</table>\n" .
5036 "</div>";
5037 $output .= git_footer_html();
5039 return $output;
5042 sub git_snapshot {
5043 my $output = "";
5045 my $format = $input_params{'snapshot_format'};
5046 if (!@snapshot_fmts) {
5047 die_error(403, "Snapshots not allowed");
5049 # default to first supported snapshot format
5050 $format ||= $snapshot_fmts[0];
5051 if ($format !~ m/^[a-z0-9]+$/) {
5052 die_error(400, "Invalid snapshot format parameter");
5053 } elsif (!exists($known_snapshot_formats{$format})) {
5054 die_error(400, "Unknown snapshot format");
5055 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5056 die_error(403, "Snapshot format not allowed");
5057 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5058 die_error(403, "Unsupported snapshot format");
5061 if (!defined $hash) {
5062 $hash = git_get_head_hash($project);
5065 my $name = $project;
5066 $name =~ s,([^/])/*\.git$,$1,;
5067 $name = basename($name);
5068 my $filename = to_utf8($name);
5069 $name =~ s/\047/\047\\\047\047/g;
5070 my $cmd;
5071 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5072 $cmd = quote_command(
5073 git_cmd(), 'archive',
5074 "--format=$known_snapshot_formats{$format}{'format'}",
5075 "--prefix=$name/", $hash);
5076 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5077 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5080 $output .= $cgi->header(
5081 -type => $known_snapshot_formats{$format}{'type'},
5082 -content_disposition => 'inline; filename="' . "$filename" . '"',
5083 -status => '200 OK');
5085 open my $fd, "-|", $cmd
5086 or die_error(500, "Execute git-archive failed");
5087 open BINOUT, '>', $fullhashbinpath or die_error(500, "Could not open snap dump");
5088 binmode BINOUT, ':raw';
5089 print BINOUT <$fd>;
5090 binmode BINOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5091 close BINOUT;
5092 close $fd;
5094 return $output;
5097 sub git_log {
5098 my $head = git_get_head_hash($project);
5100 my $output = "";
5102 if (!defined $hash) {
5103 $hash = $head;
5105 if (!defined $page) {
5106 $page = 0;
5108 my $refs = git_get_references();
5110 my @commitlist = parse_commits($hash, 101, (100 * $page));
5112 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5114 my ($patch_max) = gitweb_get_feature('patches');
5115 if ($patch_max) {
5116 if ($patch_max < 0 || @commitlist <= $patch_max) {
5117 $paging_nav .= " &sdot; " .
5118 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5119 "patches");
5123 $output .= git_header_html();
5124 $output .= git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5126 if (!@commitlist) {
5127 my %co = parse_commit($hash);
5129 $output .= git_print_header_div('summary', $project);
5130 $output .= "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5132 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5133 for (my $i = 0; $i <= $to; $i++) {
5134 my %co = %{$commitlist[$i]};
5135 next if !%co;
5136 my $commit = $co{'id'};
5137 my $ref = format_ref_marker($refs, $commit);
5138 my %ad = parse_date($co{'author_epoch'});
5139 $output .= git_print_header_div('commit',
5140 "<span class=\"age\">$co{'age_string'}</span>" .
5141 esc_html($co{'title'}) . $ref,
5142 $commit);
5143 $output .= "<div class=\"title_text\">\n" .
5144 "<div class=\"log_link\">\n" .
5145 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5146 " | " .
5147 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5148 " | " .
5149 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5150 "<br/>\n" .
5151 "</div>\n";
5152 $output .= git_print_authorship(\%co, -tag => 'span');
5153 $output .= "<br/>\n</div>\n";
5155 $output .= "<div class=\"log_body\">\n";
5156 $output .= git_print_log($co{'comment'}, -final_empty_line=> 1);
5157 $output .= "</div>\n";
5159 if ($#commitlist >= 100) {
5160 $output .= "<div class=\"page_nav\">\n";
5161 $output .= $cgi->a({-href => href(-replay=>1, page=>$page+1),
5162 -accesskey => "n", -title => "Alt-n"}, "next");
5163 $output .= "</div>\n";
5166 $output .= git_footer_html();
5168 return $output;
5171 sub git_commit {
5172 $hash ||= $hash_base || "HEAD";
5174 my $output = "";
5176 my %co = parse_commit($hash)
5177 or die_error(404, "Unknown commit object");
5179 my $parent = $co{'parent'};
5180 my $parents = $co{'parents'}; # listref
5182 # we need to prepare $formats_nav before any parameter munging
5183 my $formats_nav;
5184 if (!defined $parent) {
5185 # --root commitdiff
5186 $formats_nav .= '(initial)';
5187 } elsif (@$parents == 1) {
5188 # single parent commit
5189 $formats_nav .=
5190 '(parent: ' .
5191 $cgi->a({-href => href(action=>"commit",
5192 hash=>$parent)},
5193 esc_html(substr($parent, 0, 7))) .
5194 ')';
5195 } else {
5196 # merge commit
5197 $formats_nav .=
5198 '(merge: ' .
5199 join(' ', map {
5200 $cgi->a({-href => href(action=>"commit",
5201 hash=>$_)},
5202 esc_html(substr($_, 0, 7)));
5203 } @$parents ) .
5204 ')';
5206 if (gitweb_check_feature('patches')) {
5207 $formats_nav .= " | " .
5208 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5209 "patch");
5212 if (!defined $parent) {
5213 $parent = "--root";
5215 my @difftree;
5216 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5217 @diff_opts,
5218 (@$parents <= 1 ? $parent : '-c'),
5219 $hash, "--"
5220 or die_error(500, "Open git-diff-tree failed");
5221 @difftree = map { chomp; $_ } <$fd>;
5222 close $fd or die_error(404, "Reading git-diff-tree failed");
5224 # non-textual hash id's can be cached
5225 my $expires;
5226 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5227 $expires = "+1d";
5229 my $refs = git_get_references();
5230 my $ref = format_ref_marker($refs, $co{'id'});
5232 $output .= git_header_html(undef, $expires);
5233 $output .= git_print_page_nav('commit', '',
5234 $hash, $co{'tree'}, $hash,
5235 $formats_nav);
5237 if (defined $co{'parent'}) {
5238 $output .= git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5239 } else {
5240 $output .= git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5242 $output .= "<div class=\"title_text\">\n" .
5243 "<table class=\"object_header\">\n";
5244 $output .= git_print_authorship_rows(\%co);
5245 $output .= "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5246 $output .= "<tr>" .
5247 "<td>tree</td>" .
5248 "<td class=\"sha1\">" .
5249 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5250 class => "list"}, $co{'tree'}) .
5251 "</td>" .
5252 "<td class=\"link\">" .
5253 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5254 "tree");
5255 my $snapshot_links = format_snapshot_links($hash);
5256 if (defined $snapshot_links) {
5257 $output .= " | " . $snapshot_links;
5259 $output .= "</td>" .
5260 "</tr>\n";
5262 foreach my $par (@$parents) {
5263 $output .= "<tr>" .
5264 "<td>parent</td>" .
5265 "<td class=\"sha1\">" .
5266 $cgi->a({-href => href(action=>"commit", hash=>$par),
5267 class => "list"}, $par) .
5268 "</td>" .
5269 "<td class=\"link\">" .
5270 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5271 " | " .
5272 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5273 "</td>" .
5274 "</tr>\n";
5276 $output .= "</table>".
5277 "</div>\n";
5279 $output .= "<div class=\"page_body\">\n";
5280 $output .= git_print_log($co{'comment'});
5281 $output .= "</div>\n";
5283 $output .= git_difftree_body(\@difftree, $hash, @$parents);
5285 $output .= git_footer_html();
5287 return $output;
5290 sub git_object {
5291 # object is defined by:
5292 # - hash or hash_base alone
5293 # - hash_base and file_name
5294 my $type;
5296 # - hash or hash_base alone
5297 if ($hash || ($hash_base && !defined $file_name)) {
5298 my $object_id = $hash || $hash_base;
5300 open my $fd, "-|", quote_command(
5301 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5302 or die_error(404, "Object does not exist");
5303 $type = <$fd>;
5304 chomp $type;
5305 close $fd
5306 or die_error(404, "Object does not exist");
5308 # - hash_base and file_name
5309 } elsif ($hash_base && defined $file_name) {
5310 $file_name =~ s,/+$,,;
5312 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5313 or die_error(404, "Base object does not exist");
5315 # here errors should not hapen
5316 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5317 or die_error(500, "Open git-ls-tree failed");
5318 my $line = <$fd>;
5319 close $fd;
5321 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5322 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5323 die_error(404, "File or directory for given base does not exist");
5325 $type = $2;
5326 $hash = $3;
5327 } else {
5328 die_error(400, "Not enough information to find object");
5331 return $cgi->redirect(-uri => href(action=>$type, -full=>1,
5332 hash=>$hash, hash_base=>$hash_base,
5333 file_name=>$file_name),
5334 -status => '302 Found');
5337 sub git_blobdiff {
5338 my $format = shift || 'html';
5340 my $fd;
5341 my @difftree;
5342 my %diffinfo;
5343 my $expires;
5345 my $output = "";
5347 # preparing $fd and %diffinfo for git_patchset_body
5348 # new style URI
5349 if (defined $hash_base && defined $hash_parent_base) {
5350 if (defined $file_name) {
5351 # read raw output
5352 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5353 $hash_parent_base, $hash_base,
5354 "--", (defined $file_parent ? $file_parent : ()), $file_name
5355 or die_error(500, "Open git-diff-tree failed");
5356 @difftree = map { chomp; $_ } <$fd>;
5357 close $fd
5358 or die_error(404, "Reading git-diff-tree failed");
5359 @difftree
5360 or die_error(404, "Blob diff not found");
5362 } elsif (defined $hash &&
5363 $hash =~ /[0-9a-fA-F]{40}/) {
5364 # try to find filename from $hash
5366 # read filtered raw output
5367 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5368 $hash_parent_base, $hash_base, "--"
5369 or die_error(500, "Open git-diff-tree failed");
5370 @difftree =
5371 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5372 # $hash == to_id
5373 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5374 map { chomp; $_ } <$fd>;
5375 close $fd
5376 or die_error(404, "Reading git-diff-tree failed");
5377 @difftree
5378 or die_error(404, "Blob diff not found");
5380 } else {
5381 die_error(400, "Missing one of the blob diff parameters");
5384 if (@difftree > 1) {
5385 die_error(400, "Ambiguous blob diff specification");
5388 %diffinfo = parse_difftree_raw_line($difftree[0]);
5389 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5390 $file_name ||= $diffinfo{'to_file'};
5392 $hash_parent ||= $diffinfo{'from_id'};
5393 $hash ||= $diffinfo{'to_id'};
5395 # non-textual hash id's can be cached
5396 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5397 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5398 $expires = '+1d';
5401 # open patch output
5402 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5403 '-p', ($format eq 'html' ? "--full-index" : ()),
5404 $hash_parent_base, $hash_base,
5405 "--", (defined $file_parent ? $file_parent : ()), $file_name
5406 or die_error(500, "Open git-diff-tree failed");
5409 # old/legacy style URI -- not generated anymore since 1.4.3.
5410 if (!%diffinfo) {
5411 die_error('404 Not Found', "Missing one of the blob diff parameters")
5414 # header
5415 if ($format eq 'html') {
5416 my $formats_nav =
5417 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5418 "raw");
5419 $output .= git_header_html(undef, $expires);
5420 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5421 $output .= git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5422 $output .= git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5423 } else {
5424 $output .= "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5425 $output .= "<div class=\"title\">$hash vs $hash_parent</div>\n";
5427 if (defined $file_name) {
5428 $output .= git_print_page_path($file_name, "blob", $hash_base);
5429 } else {
5430 $output .= "<div class=\"page_path\"></div>\n";
5433 } elsif ($format eq 'plain') {
5434 $output .= $cgi->header(
5435 -type => 'text/plain',
5436 -charset => 'utf-8',
5437 -expires => $expires,
5438 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5440 $output .= "X-Git-Url: " . $cgi->self_url() . "\n\n";
5442 } else {
5443 die_error(400, "Unknown blobdiff format");
5446 # patch
5447 if ($format eq 'html') {
5448 $output .= "<div class=\"page_body\">\n";
5450 $output .= git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5451 close $fd;
5453 $output .= "</div>\n"; # class="page_body"
5454 $output .= git_footer_html();
5456 } else {
5457 while (my $line = <$fd>) {
5458 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5459 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5461 $output .= $line;
5463 last if $line =~ m!^\+\+\+!;
5465 local $/ = undef;
5466 $output .= <$fd>;
5467 close $fd;
5471 sub git_blobdiff_plain {
5472 git_blobdiff('plain');
5475 sub git_commitdiff {
5476 my %params = @_;
5477 my $format = $params{-format} || 'html';
5479 my $output = "";
5481 my ($patch_max) = gitweb_get_feature('patches');
5482 if ($format eq 'patch') {
5483 die_error(403, "Patch view not allowed") unless $patch_max;
5486 $hash ||= $hash_base || "HEAD";
5487 my %co = parse_commit($hash)
5488 or die_error(404, "Unknown commit object");
5490 # choose format for commitdiff for merge
5491 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5492 $hash_parent = '--cc';
5494 # we need to prepare $formats_nav before almost any parameter munging
5495 my $formats_nav;
5496 if ($format eq 'html') {
5497 $formats_nav =
5498 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5499 "raw");
5500 if ($patch_max) {
5501 $formats_nav .= " | " .
5502 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5503 "patch");
5506 if (defined $hash_parent &&
5507 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5508 # commitdiff with two commits given
5509 my $hash_parent_short = $hash_parent;
5510 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5511 $hash_parent_short = substr($hash_parent, 0, 7);
5513 $formats_nav .=
5514 ' (from';
5515 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5516 if ($co{'parents'}[$i] eq $hash_parent) {
5517 $formats_nav .= ' parent ' . ($i+1);
5518 last;
5521 $formats_nav .= ': ' .
5522 $cgi->a({-href => href(action=>"commitdiff",
5523 hash=>$hash_parent)},
5524 esc_html($hash_parent_short)) .
5525 ')';
5526 } elsif (!$co{'parent'}) {
5527 # --root commitdiff
5528 $formats_nav .= ' (initial)';
5529 } elsif (scalar @{$co{'parents'}} == 1) {
5530 # single parent commit
5531 $formats_nav .=
5532 ' (parent: ' .
5533 $cgi->a({-href => href(action=>"commitdiff",
5534 hash=>$co{'parent'})},
5535 esc_html(substr($co{'parent'}, 0, 7))) .
5536 ')';
5537 } else {
5538 # merge commit
5539 if ($hash_parent eq '--cc') {
5540 $formats_nav .= ' | ' .
5541 $cgi->a({-href => href(action=>"commitdiff",
5542 hash=>$hash, hash_parent=>'-c')},
5543 'combined');
5544 } else { # $hash_parent eq '-c'
5545 $formats_nav .= ' | ' .
5546 $cgi->a({-href => href(action=>"commitdiff",
5547 hash=>$hash, hash_parent=>'--cc')},
5548 'compact');
5550 $formats_nav .=
5551 ' (merge: ' .
5552 join(' ', map {
5553 $cgi->a({-href => href(action=>"commitdiff",
5554 hash=>$_)},
5555 esc_html(substr($_, 0, 7)));
5556 } @{$co{'parents'}} ) .
5557 ')';
5561 my $hash_parent_param = $hash_parent;
5562 if (!defined $hash_parent_param) {
5563 # --cc for multiple parents, --root for parentless
5564 $hash_parent_param =
5565 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5568 # read commitdiff
5569 my $fd;
5570 my @difftree;
5571 if ($format eq 'html') {
5572 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5573 "--no-commit-id", "--patch-with-raw", "--full-index",
5574 $hash_parent_param, $hash, "--"
5575 or die_error(500, "Open git-diff-tree failed");
5577 while (my $line = <$fd>) {
5578 chomp $line;
5579 # empty line ends raw part of diff-tree output
5580 last unless $line;
5581 push @difftree, scalar parse_difftree_raw_line($line);
5584 } elsif ($format eq 'plain') {
5585 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5586 '-p', $hash_parent_param, $hash, "--"
5587 or die_error(500, "Open git-diff-tree failed");
5588 } elsif ($format eq 'patch') {
5589 # For commit ranges, we limit the output to the number of
5590 # patches specified in the 'patches' feature.
5591 # For single commits, we limit the output to a single patch,
5592 # diverging from the git-format-patch default.
5593 my @commit_spec = ();
5594 if ($hash_parent) {
5595 if ($patch_max > 0) {
5596 push @commit_spec, "-$patch_max";
5598 push @commit_spec, '-n', "$hash_parent..$hash";
5599 } else {
5600 if ($params{-single}) {
5601 push @commit_spec, '-1';
5602 } else {
5603 if ($patch_max > 0) {
5604 push @commit_spec, "-$patch_max";
5606 push @commit_spec, "-n";
5608 push @commit_spec, '--root', $hash;
5610 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5611 '--stdout', @commit_spec
5612 or die_error(500, "Open git-format-patch failed");
5613 } else {
5614 die_error(400, "Unknown commitdiff format");
5617 # non-textual hash id's can be cached
5618 my $expires;
5619 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5620 $expires = "+1d";
5623 # write commit message
5624 if ($format eq 'html') {
5625 my $refs = git_get_references();
5626 my $ref = format_ref_marker($refs, $co{'id'});
5628 $output .= git_header_html(undef, $expires);
5629 $output .= git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5630 $output .= git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5631 $output .= "<div class=\"title_text\">\n" .
5632 "<table class=\"object_header\">\n";
5633 $output .= git_print_authorship_rows(\%co);
5634 $output .= "</table>".
5635 "</div>\n";
5636 $output .= "<div class=\"page_body\">\n";
5637 if (@{$co{'comment'}} > 1) {
5638 $output .= "<div class=\"log\">\n";
5639 $output .= git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5640 $output .= "</div>\n"; # class="log"
5643 } elsif ($format eq 'plain') {
5644 my $refs = git_get_references("tags");
5645 my $tagname = git_get_rev_name_tags($hash);
5646 my $filename = basename($project) . "-$hash.patch";
5648 $output .= $cgi->header(
5649 -type => 'text/plain',
5650 -charset => 'utf-8',
5651 -expires => $expires,
5652 -content_disposition => 'inline; filename="' . "$filename" . '"');
5653 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5654 $output .= "From: " . to_utf8($co{'author'}) . "\n";
5655 $output .= "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5656 $output .= "Subject: " . to_utf8($co{'title'}) . "\n";
5658 $output .= "X-Git-Tag: $tagname\n" if $tagname;
5659 $output .= "X-Git-Url: " . $cgi->self_url() . "\n\n";
5661 foreach my $line (@{$co{'comment'}}) {
5662 $output .= to_utf8($line) . "\n";
5664 $output .= "---\n\n";
5665 } elsif ($format eq 'patch') {
5666 my $filename = basename($project) . "-$hash.patch";
5668 $output .= $cgi->header(
5669 -type => 'text/plain',
5670 -charset => 'utf-8',
5671 -expires => $expires,
5672 -content_disposition => 'inline; filename="' . "$filename" . '"');
5675 # write patch
5676 if ($format eq 'html') {
5677 my $use_parents = !defined $hash_parent ||
5678 $hash_parent eq '-c' || $hash_parent eq '--cc';
5679 $output .= git_difftree_body(\@difftree, $hash,
5680 $use_parents ? @{$co{'parents'}} : $hash_parent);
5681 $output .= "<br/>\n";
5683 $output .= git_patchset_body($fd, \@difftree, $hash,
5684 $use_parents ? @{$co{'parents'}} : $hash_parent);
5685 close $fd;
5686 $output .= "</div>\n"; # class="page_body"
5687 $output .= git_footer_html();
5689 } elsif ($format eq 'plain') {
5690 local $/ = undef;
5691 $output .= <$fd>;
5692 close $fd
5693 or $output .= "Reading git-diff-tree failed\n";
5694 } elsif ($format eq 'patch') {
5695 local $/ = undef;
5696 $output .= <$fd>;
5697 close $fd
5698 or $output .= "Reading git-format-patch failed\n";
5701 return $output;
5704 sub git_commitdiff_plain {
5705 return git_commitdiff(-format => 'plain');
5708 # format-patch-style patches
5709 sub git_patch {
5710 return git_commitdiff(-format => 'patch', -single=> 1);
5713 sub git_patches {
5714 return git_commitdiff(-format => 'patch');
5717 sub git_history {
5718 my $output = "";
5720 if (!defined $hash_base) {
5721 $hash_base = git_get_head_hash($project);
5723 if (!defined $page) {
5724 $page = 0;
5726 my $ftype;
5727 my %co = parse_commit($hash_base)
5728 or die_error(404, "Unknown commit object");
5730 my $refs = git_get_references();
5731 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5733 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5734 $file_name, "--full-history")
5735 or die_error(404, "No such file or directory on given branch");
5737 if (!defined $hash && defined $file_name) {
5738 # some commits could have deleted file in question,
5739 # and not have it in tree, but one of them has to have it
5740 for (my $i = 0; $i <= @commitlist; $i++) {
5741 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5742 last if defined $hash;
5745 if (defined $hash) {
5746 $ftype = git_get_type($hash);
5748 if (!defined $ftype) {
5749 die_error(500, "Unknown type of object");
5752 my $paging_nav = '';
5753 if ($page > 0) {
5754 $paging_nav .=
5755 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5756 file_name=>$file_name)},
5757 "first");
5758 $paging_nav .= " &sdot; " .
5759 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5760 -accesskey => "p", -title => "Alt-p"}, "prev");
5761 } else {
5762 $paging_nav .= "first";
5763 $paging_nav .= " &sdot; prev";
5765 my $next_link = '';
5766 if ($#commitlist >= 100) {
5767 $next_link =
5768 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5769 -accesskey => "n", -title => "Alt-n"}, "next");
5770 $paging_nav .= " &sdot; $next_link";
5771 } else {
5772 $paging_nav .= " &sdot; next";
5775 $output .= git_header_html();
5776 $output .= git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5777 $output .= git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5778 $output .= git_print_page_path($file_name, $ftype, $hash_base);
5780 $output .= git_history_body(\@commitlist, 0, 99,
5781 $refs, $hash_base, $ftype, $next_link);
5783 $output .= git_footer_html();
5785 return $output;
5788 sub git_search {
5789 my $output = "";
5791 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5792 if (!defined $searchtext) {
5793 die_error(400, "Text field is empty");
5795 if (!defined $hash) {
5796 $hash = git_get_head_hash($project);
5798 my %co = parse_commit($hash);
5799 if (!%co) {
5800 die_error(404, "Unknown commit object");
5802 if (!defined $page) {
5803 $page = 0;
5806 $searchtype ||= 'commit';
5807 if ($searchtype eq 'pickaxe') {
5808 # pickaxe may take all resources of your box and run for several minutes
5809 # with every query - so decide by yourself how public you make this feature
5810 gitweb_check_feature('pickaxe')
5811 or die_error(403, "Pickaxe is disabled");
5813 if ($searchtype eq 'grep') {
5814 gitweb_check_feature('grep')
5815 or die_error(403, "Grep is disabled");
5818 $output .= git_header_html();
5820 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5821 my $greptype;
5822 if ($searchtype eq 'commit') {
5823 $greptype = "--grep=";
5824 } elsif ($searchtype eq 'author') {
5825 $greptype = "--author=";
5826 } elsif ($searchtype eq 'committer') {
5827 $greptype = "--committer=";
5829 $greptype .= $searchtext;
5830 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5831 $greptype, '--regexp-ignore-case',
5832 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5834 my $paging_nav = '';
5835 if ($page > 0) {
5836 $paging_nav .=
5837 $cgi->a({-href => href(action=>"search", hash=>$hash,
5838 searchtext=>$searchtext,
5839 searchtype=>$searchtype)},
5840 "first");
5841 $paging_nav .= " &sdot; " .
5842 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5843 -accesskey => "p", -title => "Alt-p"}, "prev");
5844 } else {
5845 $paging_nav .= "first";
5846 $paging_nav .= " &sdot; prev";
5848 my $next_link = '';
5849 if ($#commitlist >= 100) {
5850 $next_link =
5851 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5852 -accesskey => "n", -title => "Alt-n"}, "next");
5853 $paging_nav .= " &sdot; $next_link";
5854 } else {
5855 $paging_nav .= " &sdot; next";
5858 if ($#commitlist >= 100) {
5861 $output .= git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5862 $output .= git_print_header_div('commit', esc_html($co{'title'}), $hash);
5863 $output .= git_search_grep_body(\@commitlist, 0, 99, $next_link);
5866 if ($searchtype eq 'pickaxe') {
5867 $output .= git_print_page_nav('','', $hash,$co{'tree'},$hash);
5868 $output .= git_print_header_div('commit', esc_html($co{'title'}), $hash);
5870 $output .= "<table class=\"pickaxe search\">\n";
5871 my $alternate = 1;
5872 local $/ = "\n";
5873 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5874 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5875 ($search_use_regexp ? '--pickaxe-regex' : ());
5876 undef %co;
5877 my @files;
5878 while (my $line = <$fd>) {
5879 chomp $line;
5880 next unless $line;
5882 my %set = parse_difftree_raw_line($line);
5883 if (defined $set{'commit'}) {
5884 # finish previous commit
5885 if (%co) {
5886 $output .= "</td>\n" .
5887 "<td class=\"link\">" .
5888 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5889 " | " .
5890 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5891 $output .= "</td>\n" .
5892 "</tr>\n";
5895 if ($alternate) {
5896 $output .= "<tr class=\"dark\">\n";
5897 } else {
5898 $output .= "<tr class=\"light\">\n";
5900 $alternate ^= 1;
5901 %co = parse_commit($set{'commit'});
5902 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5903 $output .= "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5904 "<td><i>$author</i></td>\n" .
5905 "<td>" .
5906 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5907 -class => "list subject"},
5908 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5909 } elsif (defined $set{'to_id'}) {
5910 next if ($set{'to_id'} =~ m/^0{40}$/);
5912 $output .= $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5913 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5914 -class => "list"},
5915 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5916 "<br/>\n";
5919 close $fd;
5921 # finish last commit (warning: repetition!)
5922 if (%co) {
5923 $output .= "</td>\n" .
5924 "<td class=\"link\">" .
5925 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5926 " | " .
5927 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5928 $output .= "</td>\n" .
5929 "</tr>\n";
5932 $output .= "</table>\n";
5935 if ($searchtype eq 'grep') {
5936 $output .= git_print_page_nav('','', $hash,$co{'tree'},$hash);
5937 $output .= git_print_header_div('commit', esc_html($co{'title'}), $hash);
5939 $output .= "<table class=\"grep_search\">\n";
5940 my $alternate = 1;
5941 my $matches = 0;
5942 local $/ = "\n";
5943 open my $fd, "-|", git_cmd(), 'grep', '-n',
5944 $search_use_regexp ? ('-E', '-i') : '-F',
5945 $searchtext, $co{'tree'};
5946 my $lastfile = '';
5947 while (my $line = <$fd>) {
5948 chomp $line;
5949 my ($file, $lno, $ltext, $binary);
5950 last if ($matches++ > 1000);
5951 if ($line =~ /^Binary file (.+) matches$/) {
5952 $file = $1;
5953 $binary = 1;
5954 } else {
5955 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5957 if ($file ne $lastfile) {
5958 $lastfile and $output .= "</td></tr>\n";
5959 if ($alternate++) {
5960 $output .= "<tr class=\"dark\">\n";
5961 } else {
5962 $output .= "<tr class=\"light\">\n";
5964 $output .= "<td class=\"list\">".
5965 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5966 file_name=>"$file"),
5967 -class => "list"}, esc_path($file));
5968 $output .= "</td><td>\n";
5969 $lastfile = $file;
5971 if ($binary) {
5972 $output .= "<div class=\"binary\">Binary file</div>\n";
5973 } else {
5974 $ltext = untabify($ltext);
5975 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5976 $ltext = esc_html($1, -nbsp=>1);
5977 $ltext .= '<span class="match">';
5978 $ltext .= esc_html($2, -nbsp=>1);
5979 $ltext .= '</span>';
5980 $ltext .= esc_html($3, -nbsp=>1);
5981 } else {
5982 $ltext = esc_html($ltext, -nbsp=>1);
5984 $output .= "<div class=\"pre\">" .
5985 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5986 file_name=>"$file").'#l'.$lno,
5987 -class => "linenr"}, sprintf('%4i', $lno))
5988 . ' ' . $ltext . "</div>\n";
5991 if ($lastfile) {
5992 $output .= "</td></tr>\n";
5993 if ($matches > 1000) {
5994 $output .= "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5996 } else {
5997 $output .= "<div class=\"diff nodifferences\">No matches found</div>\n";
5999 close $fd;
6001 $output .= "</table>\n";
6003 $output .= git_footer_html();
6005 return $output;
6008 sub git_search_help {
6009 my $output = "";
6011 $output .= git_header_html();
6012 $output .= git_print_page_nav('','', $hash,$hash,$hash);
6013 $output .= <<EOT;
6014 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6015 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6016 the pattern entered is recognized as the POSIX extended
6017 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6018 insensitive).</p>
6019 <dl>
6020 <dt><b>commit</b></dt>
6021 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6023 my $have_grep = gitweb_check_feature('grep');
6024 if ($have_grep) {
6025 $output .= <<EOT;
6026 <dt><b>grep</b></dt>
6027 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6028 a different one) are searched for the given pattern. On large trees, this search can take
6029 a while and put some strain on the server, so please use it with some consideration. Note that
6030 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6031 case-sensitive.</dd>
6034 $output .= <<EOT;
6035 <dt><b>author</b></dt>
6036 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6037 <dt><b>committer</b></dt>
6038 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6040 my $have_pickaxe = gitweb_check_feature('pickaxe');
6041 if ($have_pickaxe) {
6042 $output .= <<EOT;
6043 <dt><b>pickaxe</b></dt>
6044 <dd>All commits that caused the string to appear or disappear from any file (changes that
6045 added, removed or "modified" the string) will be listed. This search can take a while and
6046 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6047 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6050 $output .= "</dl>\n";
6051 $output .= git_footer_html();
6053 return $output;
6056 sub git_shortlog {
6057 my $head = git_get_head_hash($project);
6058 my $output = "";
6060 if (!defined $hash) {
6061 $hash = $head;
6063 if (!defined $page) {
6064 $page = 0;
6066 my $refs = git_get_references();
6068 my $commit_hash = $hash;
6069 if (defined $hash_parent) {
6070 $commit_hash = "$hash_parent..$hash";
6072 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6074 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6075 my $next_link = '';
6076 if ($#commitlist >= 100) {
6077 $next_link =
6078 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6079 -accesskey => "n", -title => "Alt-n"}, "next");
6081 my $patch_max = gitweb_check_feature('patches');
6082 if ($patch_max) {
6083 if ($patch_max < 0 || @commitlist <= $patch_max) {
6084 $paging_nav .= " &sdot; " .
6085 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6086 "patches");
6090 $output .= git_header_html();
6091 $output .= git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6092 $output .= git_print_header_div('summary', $project);
6094 $output .= git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6096 $output .= git_footer_html();
6098 return $output;
6101 ## ......................................................................
6102 ## feeds (RSS, Atom; OPML)
6104 sub git_feed {
6105 my $format = shift || 'atom';
6106 my $have_blame = gitweb_check_feature('blame');
6108 my $output = "";
6110 # Atom: http://www.atomenabled.org/developers/syndication/
6111 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6112 if ($format ne 'rss' && $format ne 'atom') {
6113 die_error(400, "Unknown web feed format");
6116 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6117 my $head = $hash || 'HEAD';
6118 my @commitlist = parse_commits($head, 150, 0, $file_name);
6120 my %latest_commit;
6121 my %latest_date;
6122 my $content_type = "application/$format+xml";
6123 if (defined $cgi->http('HTTP_ACCEPT') &&
6124 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6125 # browser (feed reader) prefers text/xml
6126 $content_type = 'text/xml';
6128 if (defined($commitlist[0])) {
6129 %latest_commit = %{$commitlist[0]};
6130 my $latest_epoch = $latest_commit{'committer_epoch'};
6131 %latest_date = parse_date($latest_epoch);
6132 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6133 if (defined $if_modified) {
6134 my $since;
6135 if (eval { require HTTP::Date; 1; }) {
6136 $since = HTTP::Date::str2time($if_modified);
6137 } elsif (eval { require Time::ParseDate; 1; }) {
6138 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6140 if (defined $since && $latest_epoch <= $since) {
6141 $output .= $cgi->header(
6142 -type => $content_type,
6143 -charset => 'utf-8',
6144 -last_modified => $latest_date{'rfc2822'},
6145 -status => '304 Not Modified');
6146 return $output;
6149 $output .= $cgi->header(
6150 -type => $content_type,
6151 -charset => 'utf-8',
6152 -last_modified => $latest_date{'rfc2822'});
6153 } else {
6154 $output .= $cgi->header(
6155 -type => $content_type,
6156 -charset => 'utf-8');
6159 # Optimization: skip generating the body if client asks only
6160 # for Last-Modified date.
6161 return if ($cgi->request_method() eq 'HEAD');
6163 # header variables
6164 my $title = "$site_name - $project/$action";
6165 my $feed_type = 'log';
6166 if (defined $hash) {
6167 $title .= " - '$hash'";
6168 $feed_type = 'branch log';
6169 if (defined $file_name) {
6170 $title .= " :: $file_name";
6171 $feed_type = 'history';
6173 } elsif (defined $file_name) {
6174 $title .= " - $file_name";
6175 $feed_type = 'history';
6177 $title .= " $feed_type";
6178 my $descr = git_get_project_description($project);
6179 if (defined $descr) {
6180 $descr = esc_html($descr);
6181 } else {
6182 $descr = "$project " .
6183 ($format eq 'rss' ? 'RSS' : 'Atom') .
6184 " feed";
6186 my $owner = git_get_project_owner($project);
6187 $owner = esc_html($owner);
6189 #header
6190 my $alt_url;
6191 if (defined $file_name) {
6192 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6193 } elsif (defined $hash) {
6194 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6195 } else {
6196 $alt_url = href(-full=>1, action=>"summary");
6198 $output .= qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6199 if ($format eq 'rss') {
6200 $output .= <<XML;
6201 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6202 <channel>
6204 $output .= "<title>$title</title>\n" .
6205 "<link>$alt_url</link>\n" .
6206 "<description>$descr</description>\n" .
6207 "<language>en</language>\n" .
6208 # project owner is responsible for 'editorial' content
6209 "<managingEditor>$owner</managingEditor>\n";
6210 if (defined $logo || defined $favicon) {
6211 # prefer the logo to the favicon, since RSS
6212 # doesn't allow both
6213 my $img = esc_url($logo || $favicon);
6214 $output .= "<image>\n" .
6215 "<url>$img</url>\n" .
6216 "<title>$title</title>\n" .
6217 "<link>$alt_url</link>\n" .
6218 "</image>\n";
6220 if (%latest_date) {
6221 $output .= "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6222 $output .= "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6224 $output .= "<generator>gitweb v.$version/$git_version</generator>\n";
6225 } elsif ($format eq 'atom') {
6226 $output .= <<XML;
6227 <feed xmlns="http://www.w3.org/2005/Atom">
6229 $output .= "<title>$title</title>\n" .
6230 "<subtitle>$descr</subtitle>\n" .
6231 '<link rel="alternate" type="text/html" href="' .
6232 $alt_url . '" />' . "\n" .
6233 '<link rel="self" type="' . $content_type . '" href="' .
6234 $cgi->self_url() . '" />' . "\n" .
6235 "<id>" . href(-full=>1) . "</id>\n" .
6236 # use project owner for feed author
6237 "<author><name>$owner</name></author>\n";
6238 if (defined $favicon) {
6239 $output .= "<icon>" . esc_url($favicon) . "</icon>\n";
6241 if (defined $logo_url) {
6242 # not twice as wide as tall: 72 x 27 pixels
6243 $output .= "<logo>" . esc_url($logo) . "</logo>\n";
6245 if (! %latest_date) {
6246 # dummy date to keep the feed valid until commits trickle in:
6247 $output .= "<updated>1970-01-01T00:00:00Z</updated>\n";
6248 } else {
6249 $output .= "<updated>$latest_date{'iso-8601'}</updated>\n";
6251 $output .= "<generator version='$version/$git_version'>gitweb</generator>\n";
6254 # contents
6255 for (my $i = 0; $i <= $#commitlist; $i++) {
6256 my %co = %{$commitlist[$i]};
6257 my $commit = $co{'id'};
6258 # we read 150, we always show 30 and the ones more recent than 48 hours
6259 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6260 last;
6262 my %cd = parse_date($co{'author_epoch'});
6264 # get list of changed files
6265 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6266 $co{'parent'} || "--root",
6267 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6268 or next;
6269 my @difftree = map { chomp; $_ } <$fd>;
6270 close $fd
6271 or next;
6273 # print element (entry, item)
6274 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6275 if ($format eq 'rss') {
6276 $output .= "<item>\n" .
6277 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6278 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6279 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6280 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6281 "<link>$co_url</link>\n" .
6282 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6283 "<content:encoded>" .
6284 "<![CDATA[\n";
6285 } elsif ($format eq 'atom') {
6286 $output .= "<entry>\n" .
6287 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6288 "<updated>$cd{'iso-8601'}</updated>\n" .
6289 "<author>\n" .
6290 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6291 if ($co{'author_email'}) {
6292 $output .= " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6294 $output .= "</author>\n" .
6295 # use committer for contributor
6296 "<contributor>\n" .
6297 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6298 if ($co{'committer_email'}) {
6299 $output .= " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6301 $output .= "</contributor>\n" .
6302 "<published>$cd{'iso-8601'}</published>\n" .
6303 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6304 "<id>$co_url</id>\n" .
6305 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6306 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6308 my $comment = $co{'comment'};
6309 $output .= "<pre>\n";
6310 foreach my $line (@$comment) {
6311 $line = esc_html($line);
6312 $output .= "$line\n";
6314 $output .= "</pre><ul>\n";
6315 foreach my $difftree_line (@difftree) {
6316 my %difftree = parse_difftree_raw_line($difftree_line);
6317 next if !$difftree{'from_id'};
6319 my $file = $difftree{'file'} || $difftree{'to_file'};
6321 $output .= "<li>" .
6322 "[" .
6323 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6324 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6325 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6326 file_name=>$file, file_parent=>$difftree{'from_file'}),
6327 -title => "diff"}, 'D');
6328 if ($have_blame) {
6329 $output .= $cgi->a({-href => href(-full=>1, action=>"blame",
6330 file_name=>$file, hash_base=>$commit),
6331 -title => "blame"}, 'B');
6333 # if this is not a feed of a file history
6334 if (!defined $file_name || $file_name ne $file) {
6335 $output .= $cgi->a({-href => href(-full=>1, action=>"history",
6336 file_name=>$file, hash=>$commit),
6337 -title => "history"}, 'H');
6339 $file = esc_path($file);
6340 $output .= "] ".
6341 "$file</li>\n";
6343 if ($format eq 'rss') {
6344 $output .= "</ul>]]>\n" .
6345 "</content:encoded>\n" .
6346 "</item>\n";
6347 } elsif ($format eq 'atom') {
6348 $output .= "</ul>\n</div>\n" .
6349 "</content>\n" .
6350 "</entry>\n";
6354 # end of feed
6355 if ($format eq 'rss') {
6356 $output .= "</channel>\n</rss>\n";
6357 } elsif ($format eq 'atom') {
6358 $output .= "</feed>\n";
6361 return $output;
6364 sub git_rss {
6365 return git_feed('rss');
6368 sub git_atom {
6369 return git_feed('atom');
6372 sub git_opml {
6373 my @list = git_get_projects_list();
6374 my $output = "";
6376 $output .= $cgi->header(
6377 -type => 'text/xml',
6378 -charset => 'utf-8',
6379 -content_disposition => 'inline; filename="opml.xml"');
6381 $output .= <<XML;
6382 <?xml version="1.0" encoding="utf-8"?>
6383 <opml version="1.0">
6384 <head>
6385 <title>$site_name OPML Export</title>
6386 </head>
6387 <body>
6388 <outline text="git RSS feeds">
6391 foreach my $pr (@list) {
6392 my %proj = %$pr;
6393 my $head = git_get_head_hash($proj{'path'});
6394 if (!defined $head) {
6395 next;
6397 $git_dir = "$projectroot/$proj{'path'}";
6398 my %co = parse_commit($head);
6399 if (!%co) {
6400 next;
6403 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6404 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6405 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6406 $output .= "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6408 $output .= <<XML;
6409 </outline>
6410 </body>
6411 </opml>
6414 return $output;