]> Lady’s Gitweb - Gitweb/blob - gitweb.perl
gitweb: More about how gitweb gets 'owner' of repository
[Gitweb] / gitweb.perl
1 #!/usr/bin/perl
2
3 # gitweb - simple web interface to track changes in git repositories
4 #
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
7 #
8 # This program is licensed under the GPLv2
9
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
20
21 BEGIN {
22 CGI->compile() if $ENV{'MOD_PERL'};
23 }
24
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
29
30 # core git executable to use
31 # this can just be "git" if your webserver has a sensible PATH
32 our $GIT = "++GIT_BINDIR++/git";
33
34 # absolute fs-path which will be prepended to the project path
35 #our $projectroot = "/pub/scm";
36 our $projectroot = "++GITWEB_PROJECTROOT++";
37
38 # fs traversing limit for getting project list
39 # the number is relative to the projectroot
40 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
41
42 # target of the home link on top of all pages
43 our $home_link = $my_uri || "/";
44
45 # string of the home link on top of all pages
46 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
47
48 # name of your site or organization to appear in page titles
49 # replace this with something more descriptive for clearer bookmarks
50 our $site_name = "++GITWEB_SITENAME++"
51 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
52
53 # filename of html text to include at top of each page
54 our $site_header = "++GITWEB_SITE_HEADER++";
55 # html text to include at home page
56 our $home_text = "++GITWEB_HOMETEXT++";
57 # filename of html text to include at bottom of each page
58 our $site_footer = "++GITWEB_SITE_FOOTER++";
59
60 # URI of stylesheets
61 our @stylesheets = ("++GITWEB_CSS++");
62 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
63 our $stylesheet = undef;
64
65 # URI of GIT logo (72x27 size)
66 our $logo = "++GITWEB_LOGO++";
67 # URI of GIT favicon, assumed to be image/png type
68 our $favicon = "++GITWEB_FAVICON++";
69
70 # URI and label (title) of GIT logo link
71 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
72 #our $logo_label = "git documentation";
73 our $logo_url = "http://git.or.cz/";
74 our $logo_label = "git homepage";
75
76 # source of projects list
77 our $projects_list = "++GITWEB_LIST++";
78
79 # the width (in characters) of the projects list "Description" column
80 our $projects_list_description_width = 25;
81
82 # default order of projects list
83 # valid values are none, project, descr, owner, and age
84 our $default_projects_order = "project";
85
86 # show repository only if this file exists
87 # (only effective if this variable evaluates to true)
88 our $export_ok = "++GITWEB_EXPORT_OK++";
89
90 # only allow viewing of repositories also shown on the overview page
91 our $strict_export = "++GITWEB_STRICT_EXPORT++";
92
93 # list of git base URLs used for URL to where fetch project from,
94 # i.e. full URL is "$git_base_url/$project"
95 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
96
97 # default blob_plain mimetype and default charset for text/plain blob
98 our $default_blob_plain_mimetype = 'text/plain';
99 our $default_text_plain_charset = undef;
100
101 # file to use for guessing MIME types before trying /etc/mime.types
102 # (relative to the current git repository)
103 our $mimetypes_file = undef;
104
105 # assume this charset if line contains non-UTF-8 characters;
106 # it should be valid encoding (see Encoding::Supported(3pm) for list),
107 # for which encoding all byte sequences are valid, for example
108 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
109 # could be even 'utf-8' for the old behavior)
110 our $fallback_encoding = 'latin1';
111
112 # rename detection options for git-diff and git-diff-tree
113 # - default is '-M', with the cost proportional to
114 # (number of removed files) * (number of new files).
115 # - more costly is '-C' (which implies '-M'), with the cost proportional to
116 # (number of changed files + number of removed files) * (number of new files)
117 # - even more costly is '-C', '--find-copies-harder' with cost
118 # (number of files in the original tree) * (number of new files)
119 # - one might want to include '-B' option, e.g. '-B', '-M'
120 our @diff_opts = ('-M'); # taken from git_commit
121
122 # information about snapshot formats that gitweb is capable of serving
123 our %known_snapshot_formats = (
124 # name => {
125 # 'display' => display name,
126 # 'type' => mime type,
127 # 'suffix' => filename suffix,
128 # 'format' => --format for git-archive,
129 # 'compressor' => [compressor command and arguments]
130 # (array reference, optional)}
131 #
132 'tgz' => {
133 'display' => 'tar.gz',
134 'type' => 'application/x-gzip',
135 'suffix' => '.tar.gz',
136 'format' => 'tar',
137 'compressor' => ['gzip']},
138
139 'tbz2' => {
140 'display' => 'tar.bz2',
141 'type' => 'application/x-bzip2',
142 'suffix' => '.tar.bz2',
143 'format' => 'tar',
144 'compressor' => ['bzip2']},
145
146 'zip' => {
147 'display' => 'zip',
148 'type' => 'application/x-zip',
149 'suffix' => '.zip',
150 'format' => 'zip'},
151 );
152
153 # Aliases so we understand old gitweb.snapshot values in repository
154 # configuration.
155 our %known_snapshot_format_aliases = (
156 'gzip' => 'tgz',
157 'bzip2' => 'tbz2',
158
159 # backward compatibility: legacy gitweb config support
160 'x-gzip' => undef, 'gz' => undef,
161 'x-bzip2' => undef, 'bz2' => undef,
162 'x-zip' => undef, '' => undef,
163 );
164
165 # You define site-wide feature defaults here; override them with
166 # $GITWEB_CONFIG as necessary.
167 our %feature = (
168 # feature => {
169 # 'sub' => feature-sub (subroutine),
170 # 'override' => allow-override (boolean),
171 # 'default' => [ default options...] (array reference)}
172 #
173 # if feature is overridable (it means that allow-override has true value),
174 # then feature-sub will be called with default options as parameters;
175 # return value of feature-sub indicates if to enable specified feature
176 #
177 # if there is no 'sub' key (no feature-sub), then feature cannot be
178 # overriden
179 #
180 # use gitweb_check_feature(<feature>) to check if <feature> is enabled
181
182 # Enable the 'blame' blob view, showing the last commit that modified
183 # each line in the file. This can be very CPU-intensive.
184
185 # To enable system wide have in $GITWEB_CONFIG
186 # $feature{'blame'}{'default'} = [1];
187 # To have project specific config enable override in $GITWEB_CONFIG
188 # $feature{'blame'}{'override'} = 1;
189 # and in project config gitweb.blame = 0|1;
190 'blame' => {
191 'sub' => \&feature_blame,
192 'override' => 0,
193 'default' => [0]},
194
195 # Enable the 'snapshot' link, providing a compressed archive of any
196 # tree. This can potentially generate high traffic if you have large
197 # project.
198
199 # Value is a list of formats defined in %known_snapshot_formats that
200 # you wish to offer.
201 # To disable system wide have in $GITWEB_CONFIG
202 # $feature{'snapshot'}{'default'} = [];
203 # To have project specific config enable override in $GITWEB_CONFIG
204 # $feature{'snapshot'}{'override'} = 1;
205 # and in project config, a comma-separated list of formats or "none"
206 # to disable. Example: gitweb.snapshot = tbz2,zip;
207 'snapshot' => {
208 'sub' => \&feature_snapshot,
209 'override' => 0,
210 'default' => ['tgz']},
211
212 # Enable text search, which will list the commits which match author,
213 # committer or commit text to a given string. Enabled by default.
214 # Project specific override is not supported.
215 'search' => {
216 'override' => 0,
217 'default' => [1]},
218
219 # Enable grep search, which will list the files in currently selected
220 # tree containing the given string. Enabled by default. This can be
221 # potentially CPU-intensive, of course.
222
223 # To enable system wide have in $GITWEB_CONFIG
224 # $feature{'grep'}{'default'} = [1];
225 # To have project specific config enable override in $GITWEB_CONFIG
226 # $feature{'grep'}{'override'} = 1;
227 # and in project config gitweb.grep = 0|1;
228 'grep' => {
229 'override' => 0,
230 'default' => [1]},
231
232 # Enable the pickaxe search, which will list the commits that modified
233 # a given string in a file. This can be practical and quite faster
234 # alternative to 'blame', but still potentially CPU-intensive.
235
236 # To enable system wide have in $GITWEB_CONFIG
237 # $feature{'pickaxe'}{'default'} = [1];
238 # To have project specific config enable override in $GITWEB_CONFIG
239 # $feature{'pickaxe'}{'override'} = 1;
240 # and in project config gitweb.pickaxe = 0|1;
241 'pickaxe' => {
242 'sub' => \&feature_pickaxe,
243 'override' => 0,
244 'default' => [1]},
245
246 # Make gitweb use an alternative format of the URLs which can be
247 # more readable and natural-looking: project name is embedded
248 # directly in the path and the query string contains other
249 # auxiliary information. All gitweb installations recognize
250 # URL in either format; this configures in which formats gitweb
251 # generates links.
252
253 # To enable system wide have in $GITWEB_CONFIG
254 # $feature{'pathinfo'}{'default'} = [1];
255 # Project specific override is not supported.
256
257 # Note that you will need to change the default location of CSS,
258 # favicon, logo and possibly other files to an absolute URL. Also,
259 # if gitweb.cgi serves as your indexfile, you will need to force
260 # $my_uri to contain the script name in your $GITWEB_CONFIG.
261 'pathinfo' => {
262 'override' => 0,
263 'default' => [0]},
264
265 # Make gitweb consider projects in project root subdirectories
266 # to be forks of existing projects. Given project $projname.git,
267 # projects matching $projname/*.git will not be shown in the main
268 # projects list, instead a '+' mark will be added to $projname
269 # there and a 'forks' view will be enabled for the project, listing
270 # all the forks. If project list is taken from a file, forks have
271 # to be listed after the main project.
272
273 # To enable system wide have in $GITWEB_CONFIG
274 # $feature{'forks'}{'default'} = [1];
275 # Project specific override is not supported.
276 'forks' => {
277 'override' => 0,
278 'default' => [0]},
279 );
280
281 sub gitweb_check_feature {
282 my ($name) = @_;
283 return unless exists $feature{$name};
284 my ($sub, $override, @defaults) = (
285 $feature{$name}{'sub'},
286 $feature{$name}{'override'},
287 @{$feature{$name}{'default'}});
288 if (!$override) { return @defaults; }
289 if (!defined $sub) {
290 warn "feature $name is not overrideable";
291 return @defaults;
292 }
293 return $sub->(@defaults);
294 }
295
296 sub feature_blame {
297 my ($val) = git_get_project_config('blame', '--bool');
298
299 if ($val eq 'true') {
300 return 1;
301 } elsif ($val eq 'false') {
302 return 0;
303 }
304
305 return $_[0];
306 }
307
308 sub feature_snapshot {
309 my (@fmts) = @_;
310
311 my ($val) = git_get_project_config('snapshot');
312
313 if ($val) {
314 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
315 }
316
317 return @fmts;
318 }
319
320 sub feature_grep {
321 my ($val) = git_get_project_config('grep', '--bool');
322
323 if ($val eq 'true') {
324 return (1);
325 } elsif ($val eq 'false') {
326 return (0);
327 }
328
329 return ($_[0]);
330 }
331
332 sub feature_pickaxe {
333 my ($val) = git_get_project_config('pickaxe', '--bool');
334
335 if ($val eq 'true') {
336 return (1);
337 } elsif ($val eq 'false') {
338 return (0);
339 }
340
341 return ($_[0]);
342 }
343
344 # checking HEAD file with -e is fragile if the repository was
345 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
346 # and then pruned.
347 sub check_head_link {
348 my ($dir) = @_;
349 my $headfile = "$dir/HEAD";
350 return ((-e $headfile) ||
351 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
352 }
353
354 sub check_export_ok {
355 my ($dir) = @_;
356 return (check_head_link($dir) &&
357 (!$export_ok || -e "$dir/$export_ok"));
358 }
359
360 # process alternate names for backward compatibility
361 # filter out unsupported (unknown) snapshot formats
362 sub filter_snapshot_fmts {
363 my @fmts = @_;
364
365 @fmts = map {
366 exists $known_snapshot_format_aliases{$_} ?
367 $known_snapshot_format_aliases{$_} : $_} @fmts;
368 @fmts = grep(exists $known_snapshot_formats{$_}, @fmts);
369
370 }
371
372 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
373 if (-e $GITWEB_CONFIG) {
374 do $GITWEB_CONFIG;
375 } else {
376 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
377 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
378 }
379
380 # version of the core git binary
381 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
382
383 $projects_list ||= $projectroot;
384
385 # ======================================================================
386 # input validation and dispatch
387 our $action = $cgi->param('a');
388 if (defined $action) {
389 if ($action =~ m/[^0-9a-zA-Z\.\-_]/) {
390 die_error(400, "Invalid action parameter");
391 }
392 }
393
394 # parameters which are pathnames
395 our $project = $cgi->param('p');
396 if (defined $project) {
397 if (!validate_pathname($project) ||
398 !(-d "$projectroot/$project") ||
399 !check_head_link("$projectroot/$project") ||
400 ($export_ok && !(-e "$projectroot/$project/$export_ok")) ||
401 ($strict_export && !project_in_list($project))) {
402 undef $project;
403 die_error(404, "No such project");
404 }
405 }
406
407 our $file_name = $cgi->param('f');
408 if (defined $file_name) {
409 if (!validate_pathname($file_name)) {
410 die_error(400, "Invalid file parameter");
411 }
412 }
413
414 our $file_parent = $cgi->param('fp');
415 if (defined $file_parent) {
416 if (!validate_pathname($file_parent)) {
417 die_error(400, "Invalid file parent parameter");
418 }
419 }
420
421 # parameters which are refnames
422 our $hash = $cgi->param('h');
423 if (defined $hash) {
424 if (!validate_refname($hash)) {
425 die_error(400, "Invalid hash parameter");
426 }
427 }
428
429 our $hash_parent = $cgi->param('hp');
430 if (defined $hash_parent) {
431 if (!validate_refname($hash_parent)) {
432 die_error(400, "Invalid hash parent parameter");
433 }
434 }
435
436 our $hash_base = $cgi->param('hb');
437 if (defined $hash_base) {
438 if (!validate_refname($hash_base)) {
439 die_error(400, "Invalid hash base parameter");
440 }
441 }
442
443 my %allowed_options = (
444 "--no-merges" => [ qw(rss atom log shortlog history) ],
445 );
446
447 our @extra_options = $cgi->param('opt');
448 if (defined @extra_options) {
449 foreach my $opt (@extra_options) {
450 if (not exists $allowed_options{$opt}) {
451 die_error(400, "Invalid option parameter");
452 }
453 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
454 die_error(400, "Invalid option parameter for this action");
455 }
456 }
457 }
458
459 our $hash_parent_base = $cgi->param('hpb');
460 if (defined $hash_parent_base) {
461 if (!validate_refname($hash_parent_base)) {
462 die_error(400, "Invalid hash parent base parameter");
463 }
464 }
465
466 # other parameters
467 our $page = $cgi->param('pg');
468 if (defined $page) {
469 if ($page =~ m/[^0-9]/) {
470 die_error(400, "Invalid page parameter");
471 }
472 }
473
474 our $searchtype = $cgi->param('st');
475 if (defined $searchtype) {
476 if ($searchtype =~ m/[^a-z]/) {
477 die_error(400, "Invalid searchtype parameter");
478 }
479 }
480
481 our $search_use_regexp = $cgi->param('sr');
482
483 our $searchtext = $cgi->param('s');
484 our $search_regexp;
485 if (defined $searchtext) {
486 if (length($searchtext) < 2) {
487 die_error(403, "At least two characters are required for search parameter");
488 }
489 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
490 }
491
492 # now read PATH_INFO and use it as alternative to parameters
493 sub evaluate_path_info {
494 return if defined $project;
495 my $path_info = $ENV{"PATH_INFO"};
496 return if !$path_info;
497 $path_info =~ s,^/+,,;
498 return if !$path_info;
499 # find which part of PATH_INFO is project
500 $project = $path_info;
501 $project =~ s,/+$,,;
502 while ($project && !check_head_link("$projectroot/$project")) {
503 $project =~ s,/*[^/]*$,,;
504 }
505 # validate project
506 $project = validate_pathname($project);
507 if (!$project ||
508 ($export_ok && !-e "$projectroot/$project/$export_ok") ||
509 ($strict_export && !project_in_list($project))) {
510 undef $project;
511 return;
512 }
513 # do not change any parameters if an action is given using the query string
514 return if $action;
515 $path_info =~ s,^\Q$project\E/*,,;
516 my ($refname, $pathname) = split(/:/, $path_info, 2);
517 if (defined $pathname) {
518 # we got "project.git/branch:filename" or "project.git/branch:dir/"
519 # we could use git_get_type(branch:pathname), but it needs $git_dir
520 $pathname =~ s,^/+,,;
521 if (!$pathname || substr($pathname, -1) eq "/") {
522 $action ||= "tree";
523 $pathname =~ s,/$,,;
524 } else {
525 $action ||= "blob_plain";
526 }
527 $hash_base ||= validate_refname($refname);
528 $file_name ||= validate_pathname($pathname);
529 } elsif (defined $refname) {
530 # we got "project.git/branch"
531 $action ||= "shortlog";
532 $hash ||= validate_refname($refname);
533 }
534 }
535 evaluate_path_info();
536
537 # path to the current git repository
538 our $git_dir;
539 $git_dir = "$projectroot/$project" if $project;
540
541 # dispatch
542 my %actions = (
543 "blame" => \&git_blame,
544 "blobdiff" => \&git_blobdiff,
545 "blobdiff_plain" => \&git_blobdiff_plain,
546 "blob" => \&git_blob,
547 "blob_plain" => \&git_blob_plain,
548 "commitdiff" => \&git_commitdiff,
549 "commitdiff_plain" => \&git_commitdiff_plain,
550 "commit" => \&git_commit,
551 "forks" => \&git_forks,
552 "heads" => \&git_heads,
553 "history" => \&git_history,
554 "log" => \&git_log,
555 "rss" => \&git_rss,
556 "atom" => \&git_atom,
557 "search" => \&git_search,
558 "search_help" => \&git_search_help,
559 "shortlog" => \&git_shortlog,
560 "summary" => \&git_summary,
561 "tag" => \&git_tag,
562 "tags" => \&git_tags,
563 "tree" => \&git_tree,
564 "snapshot" => \&git_snapshot,
565 "object" => \&git_object,
566 # those below don't need $project
567 "opml" => \&git_opml,
568 "project_list" => \&git_project_list,
569 "project_index" => \&git_project_index,
570 );
571
572 if (!defined $action) {
573 if (defined $hash) {
574 $action = git_get_type($hash);
575 } elsif (defined $hash_base && defined $file_name) {
576 $action = git_get_type("$hash_base:$file_name");
577 } elsif (defined $project) {
578 $action = 'summary';
579 } else {
580 $action = 'project_list';
581 }
582 }
583 if (!defined($actions{$action})) {
584 die_error(400, "Unknown action");
585 }
586 if ($action !~ m/^(opml|project_list|project_index)$/ &&
587 !$project) {
588 die_error(400, "Project needed");
589 }
590 $actions{$action}->();
591 exit;
592
593 ## ======================================================================
594 ## action links
595
596 sub href (%) {
597 my %params = @_;
598 # default is to use -absolute url() i.e. $my_uri
599 my $href = $params{-full} ? $my_url : $my_uri;
600
601 # XXX: Warning: If you touch this, check the search form for updating,
602 # too.
603
604 my @mapping = (
605 project => "p",
606 action => "a",
607 file_name => "f",
608 file_parent => "fp",
609 hash => "h",
610 hash_parent => "hp",
611 hash_base => "hb",
612 hash_parent_base => "hpb",
613 page => "pg",
614 order => "o",
615 searchtext => "s",
616 searchtype => "st",
617 snapshot_format => "sf",
618 extra_options => "opt",
619 search_use_regexp => "sr",
620 );
621 my %mapping = @mapping;
622
623 $params{'project'} = $project unless exists $params{'project'};
624
625 if ($params{-replay}) {
626 while (my ($name, $symbol) = each %mapping) {
627 if (!exists $params{$name}) {
628 # to allow for multivalued params we use arrayref form
629 $params{$name} = [ $cgi->param($symbol) ];
630 }
631 }
632 }
633
634 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
635 if ($use_pathinfo) {
636 # use PATH_INFO for project name
637 $href .= "/".esc_url($params{'project'}) if defined $params{'project'};
638 delete $params{'project'};
639
640 # Summary just uses the project path URL
641 if (defined $params{'action'} && $params{'action'} eq 'summary') {
642 delete $params{'action'};
643 }
644 }
645
646 # now encode the parameters explicitly
647 my @result = ();
648 for (my $i = 0; $i < @mapping; $i += 2) {
649 my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]);
650 if (defined $params{$name}) {
651 if (ref($params{$name}) eq "ARRAY") {
652 foreach my $par (@{$params{$name}}) {
653 push @result, $symbol . "=" . esc_param($par);
654 }
655 } else {
656 push @result, $symbol . "=" . esc_param($params{$name});
657 }
658 }
659 }
660 $href .= "?" . join(';', @result) if scalar @result;
661
662 return $href;
663 }
664
665
666 ## ======================================================================
667 ## validation, quoting/unquoting and escaping
668
669 sub validate_pathname {
670 my $input = shift || return undef;
671
672 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
673 # at the beginning, at the end, and between slashes.
674 # also this catches doubled slashes
675 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
676 return undef;
677 }
678 # no null characters
679 if ($input =~ m!\0!) {
680 return undef;
681 }
682 return $input;
683 }
684
685 sub validate_refname {
686 my $input = shift || return undef;
687
688 # textual hashes are O.K.
689 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
690 return $input;
691 }
692 # it must be correct pathname
693 $input = validate_pathname($input)
694 or return undef;
695 # restrictions on ref name according to git-check-ref-format
696 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
697 return undef;
698 }
699 return $input;
700 }
701
702 # decode sequences of octets in utf8 into Perl's internal form,
703 # which is utf-8 with utf8 flag set if needed. gitweb writes out
704 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
705 sub to_utf8 {
706 my $str = shift;
707 if (utf8::valid($str)) {
708 utf8::decode($str);
709 return $str;
710 } else {
711 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
712 }
713 }
714
715 # quote unsafe chars, but keep the slash, even when it's not
716 # correct, but quoted slashes look too horrible in bookmarks
717 sub esc_param {
718 my $str = shift;
719 $str =~ s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X", ord($1))/eg;
720 $str =~ s/\+/%2B/g;
721 $str =~ s/ /\+/g;
722 return $str;
723 }
724
725 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
726 sub esc_url {
727 my $str = shift;
728 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
729 $str =~ s/\+/%2B/g;
730 $str =~ s/ /\+/g;
731 return $str;
732 }
733
734 # replace invalid utf8 character with SUBSTITUTION sequence
735 sub esc_html ($;%) {
736 my $str = shift;
737 my %opts = @_;
738
739 $str = to_utf8($str);
740 $str = $cgi->escapeHTML($str);
741 if ($opts{'-nbsp'}) {
742 $str =~ s/ /&nbsp;/g;
743 }
744 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
745 return $str;
746 }
747
748 # quote control characters and escape filename to HTML
749 sub esc_path {
750 my $str = shift;
751 my %opts = @_;
752
753 $str = to_utf8($str);
754 $str = $cgi->escapeHTML($str);
755 if ($opts{'-nbsp'}) {
756 $str =~ s/ /&nbsp;/g;
757 }
758 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
759 return $str;
760 }
761
762 # Make control characters "printable", using character escape codes (CEC)
763 sub quot_cec {
764 my $cntrl = shift;
765 my %opts = @_;
766 my %es = ( # character escape codes, aka escape sequences
767 "\t" => '\t', # tab (HT)
768 "\n" => '\n', # line feed (LF)
769 "\r" => '\r', # carrige return (CR)
770 "\f" => '\f', # form feed (FF)
771 "\b" => '\b', # backspace (BS)
772 "\a" => '\a', # alarm (bell) (BEL)
773 "\e" => '\e', # escape (ESC)
774 "\013" => '\v', # vertical tab (VT)
775 "\000" => '\0', # nul character (NUL)
776 );
777 my $chr = ( (exists $es{$cntrl})
778 ? $es{$cntrl}
779 : sprintf('\%03o', ord($cntrl)) );
780 if ($opts{-nohtml}) {
781 return $chr;
782 } else {
783 return "<span class=\"cntrl\">$chr</span>";
784 }
785 }
786
787 # Alternatively use unicode control pictures codepoints,
788 # Unicode "printable representation" (PR)
789 sub quot_upr {
790 my $cntrl = shift;
791 my %opts = @_;
792
793 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
794 if ($opts{-nohtml}) {
795 return $chr;
796 } else {
797 return "<span class=\"cntrl\">$chr</span>";
798 }
799 }
800
801 # git may return quoted and escaped filenames
802 sub unquote {
803 my $str = shift;
804
805 sub unq {
806 my $seq = shift;
807 my %es = ( # character escape codes, aka escape sequences
808 't' => "\t", # tab (HT, TAB)
809 'n' => "\n", # newline (NL)
810 'r' => "\r", # return (CR)
811 'f' => "\f", # form feed (FF)
812 'b' => "\b", # backspace (BS)
813 'a' => "\a", # alarm (bell) (BEL)
814 'e' => "\e", # escape (ESC)
815 'v' => "\013", # vertical tab (VT)
816 );
817
818 if ($seq =~ m/^[0-7]{1,3}$/) {
819 # octal char sequence
820 return chr(oct($seq));
821 } elsif (exists $es{$seq}) {
822 # C escape sequence, aka character escape code
823 return $es{$seq};
824 }
825 # quoted ordinary character
826 return $seq;
827 }
828
829 if ($str =~ m/^"(.*)"$/) {
830 # needs unquoting
831 $str = $1;
832 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
833 }
834 return $str;
835 }
836
837 # escape tabs (convert tabs to spaces)
838 sub untabify {
839 my $line = shift;
840
841 while ((my $pos = index($line, "\t")) != -1) {
842 if (my $count = (8 - ($pos % 8))) {
843 my $spaces = ' ' x $count;
844 $line =~ s/\t/$spaces/;
845 }
846 }
847
848 return $line;
849 }
850
851 sub project_in_list {
852 my $project = shift;
853 my @list = git_get_projects_list();
854 return @list && scalar(grep { $_->{'path'} eq $project } @list);
855 }
856
857 ## ----------------------------------------------------------------------
858 ## HTML aware string manipulation
859
860 # Try to chop given string on a word boundary between position
861 # $len and $len+$add_len. If there is no word boundary there,
862 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
863 # (marking chopped part) would be longer than given string.
864 sub chop_str {
865 my $str = shift;
866 my $len = shift;
867 my $add_len = shift || 10;
868 my $where = shift || 'right'; # 'left' | 'center' | 'right'
869
870 # Make sure perl knows it is utf8 encoded so we don't
871 # cut in the middle of a utf8 multibyte char.
872 $str = to_utf8($str);
873
874 # allow only $len chars, but don't cut a word if it would fit in $add_len
875 # if it doesn't fit, cut it if it's still longer than the dots we would add
876 # remove chopped character entities entirely
877
878 # when chopping in the middle, distribute $len into left and right part
879 # return early if chopping wouldn't make string shorter
880 if ($where eq 'center') {
881 return $str if ($len + 5 >= length($str)); # filler is length 5
882 $len = int($len/2);
883 } else {
884 return $str if ($len + 4 >= length($str)); # filler is length 4
885 }
886
887 # regexps: ending and beginning with word part up to $add_len
888 my $endre = qr/.{$len}\w{0,$add_len}/;
889 my $begre = qr/\w{0,$add_len}.{$len}/;
890
891 if ($where eq 'left') {
892 $str =~ m/^(.*?)($begre)$/;
893 my ($lead, $body) = ($1, $2);
894 if (length($lead) > 4) {
895 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
896 $lead = " ...";
897 }
898 return "$lead$body";
899
900 } elsif ($where eq 'center') {
901 $str =~ m/^($endre)(.*)$/;
902 my ($left, $str) = ($1, $2);
903 $str =~ m/^(.*?)($begre)$/;
904 my ($mid, $right) = ($1, $2);
905 if (length($mid) > 5) {
906 $left =~ s/&[^;]*$//;
907 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
908 $mid = " ... ";
909 }
910 return "$left$mid$right";
911
912 } else {
913 $str =~ m/^($endre)(.*)$/;
914 my $body = $1;
915 my $tail = $2;
916 if (length($tail) > 4) {
917 $body =~ s/&[^;]*$//;
918 $tail = "... ";
919 }
920 return "$body$tail";
921 }
922 }
923
924 # takes the same arguments as chop_str, but also wraps a <span> around the
925 # result with a title attribute if it does get chopped. Additionally, the
926 # string is HTML-escaped.
927 sub chop_and_escape_str {
928 my ($str) = @_;
929
930 my $chopped = chop_str(@_);
931 if ($chopped eq $str) {
932 return esc_html($chopped);
933 } else {
934 $str =~ s/([[:cntrl:]])/?/g;
935 return $cgi->span({-title=>$str}, esc_html($chopped));
936 }
937 }
938
939 ## ----------------------------------------------------------------------
940 ## functions returning short strings
941
942 # CSS class for given age value (in seconds)
943 sub age_class {
944 my $age = shift;
945
946 if (!defined $age) {
947 return "noage";
948 } elsif ($age < 60*60*2) {
949 return "age0";
950 } elsif ($age < 60*60*24*2) {
951 return "age1";
952 } else {
953 return "age2";
954 }
955 }
956
957 # convert age in seconds to "nn units ago" string
958 sub age_string {
959 my $age = shift;
960 my $age_str;
961
962 if ($age > 60*60*24*365*2) {
963 $age_str = (int $age/60/60/24/365);
964 $age_str .= " years ago";
965 } elsif ($age > 60*60*24*(365/12)*2) {
966 $age_str = int $age/60/60/24/(365/12);
967 $age_str .= " months ago";
968 } elsif ($age > 60*60*24*7*2) {
969 $age_str = int $age/60/60/24/7;
970 $age_str .= " weeks ago";
971 } elsif ($age > 60*60*24*2) {
972 $age_str = int $age/60/60/24;
973 $age_str .= " days ago";
974 } elsif ($age > 60*60*2) {
975 $age_str = int $age/60/60;
976 $age_str .= " hours ago";
977 } elsif ($age > 60*2) {
978 $age_str = int $age/60;
979 $age_str .= " min ago";
980 } elsif ($age > 2) {
981 $age_str = int $age;
982 $age_str .= " sec ago";
983 } else {
984 $age_str .= " right now";
985 }
986 return $age_str;
987 }
988
989 use constant {
990 S_IFINVALID => 0030000,
991 S_IFGITLINK => 0160000,
992 };
993
994 # submodule/subproject, a commit object reference
995 sub S_ISGITLINK($) {
996 my $mode = shift;
997
998 return (($mode & S_IFMT) == S_IFGITLINK)
999 }
1000
1001 # convert file mode in octal to symbolic file mode string
1002 sub mode_str {
1003 my $mode = oct shift;
1004
1005 if (S_ISGITLINK($mode)) {
1006 return 'm---------';
1007 } elsif (S_ISDIR($mode & S_IFMT)) {
1008 return 'drwxr-xr-x';
1009 } elsif (S_ISLNK($mode)) {
1010 return 'lrwxrwxrwx';
1011 } elsif (S_ISREG($mode)) {
1012 # git cares only about the executable bit
1013 if ($mode & S_IXUSR) {
1014 return '-rwxr-xr-x';
1015 } else {
1016 return '-rw-r--r--';
1017 };
1018 } else {
1019 return '----------';
1020 }
1021 }
1022
1023 # convert file mode in octal to file type string
1024 sub file_type {
1025 my $mode = shift;
1026
1027 if ($mode !~ m/^[0-7]+$/) {
1028 return $mode;
1029 } else {
1030 $mode = oct $mode;
1031 }
1032
1033 if (S_ISGITLINK($mode)) {
1034 return "submodule";
1035 } elsif (S_ISDIR($mode & S_IFMT)) {
1036 return "directory";
1037 } elsif (S_ISLNK($mode)) {
1038 return "symlink";
1039 } elsif (S_ISREG($mode)) {
1040 return "file";
1041 } else {
1042 return "unknown";
1043 }
1044 }
1045
1046 # convert file mode in octal to file type description string
1047 sub file_type_long {
1048 my $mode = shift;
1049
1050 if ($mode !~ m/^[0-7]+$/) {
1051 return $mode;
1052 } else {
1053 $mode = oct $mode;
1054 }
1055
1056 if (S_ISGITLINK($mode)) {
1057 return "submodule";
1058 } elsif (S_ISDIR($mode & S_IFMT)) {
1059 return "directory";
1060 } elsif (S_ISLNK($mode)) {
1061 return "symlink";
1062 } elsif (S_ISREG($mode)) {
1063 if ($mode & S_IXUSR) {
1064 return "executable";
1065 } else {
1066 return "file";
1067 };
1068 } else {
1069 return "unknown";
1070 }
1071 }
1072
1073
1074 ## ----------------------------------------------------------------------
1075 ## functions returning short HTML fragments, or transforming HTML fragments
1076 ## which don't belong to other sections
1077
1078 # format line of commit message.
1079 sub format_log_line_html {
1080 my $line = shift;
1081
1082 $line = esc_html($line, -nbsp=>1);
1083 if ($line =~ m/([0-9a-fA-F]{8,40})/) {
1084 my $hash_text = $1;
1085 my $link =
1086 $cgi->a({-href => href(action=>"object", hash=>$hash_text),
1087 -class => "text"}, $hash_text);
1088 $line =~ s/$hash_text/$link/;
1089 }
1090 return $line;
1091 }
1092
1093 # format marker of refs pointing to given object
1094 sub format_ref_marker {
1095 my ($refs, $id) = @_;
1096 my $markers = '';
1097
1098 if (defined $refs->{$id}) {
1099 foreach my $ref (@{$refs->{$id}}) {
1100 my ($type, $name) = qw();
1101 # e.g. tags/v2.6.11 or heads/next
1102 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1103 $type = $1;
1104 $name = $2;
1105 } else {
1106 $type = "ref";
1107 $name = $ref;
1108 }
1109
1110 $markers .= " <span class=\"$type\" title=\"$ref\">" .
1111 esc_html($name) . "</span>";
1112 }
1113 }
1114
1115 if ($markers) {
1116 return ' <span class="refs">'. $markers . '</span>';
1117 } else {
1118 return "";
1119 }
1120 }
1121
1122 # format, perhaps shortened and with markers, title line
1123 sub format_subject_html {
1124 my ($long, $short, $href, $extra) = @_;
1125 $extra = '' unless defined($extra);
1126
1127 if (length($short) < length($long)) {
1128 return $cgi->a({-href => $href, -class => "list subject",
1129 -title => to_utf8($long)},
1130 esc_html($short) . $extra);
1131 } else {
1132 return $cgi->a({-href => $href, -class => "list subject"},
1133 esc_html($long) . $extra);
1134 }
1135 }
1136
1137 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1138 sub format_git_diff_header_line {
1139 my $line = shift;
1140 my $diffinfo = shift;
1141 my ($from, $to) = @_;
1142
1143 if ($diffinfo->{'nparents'}) {
1144 # combined diff
1145 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1146 if ($to->{'href'}) {
1147 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1148 esc_path($to->{'file'}));
1149 } else { # file was deleted (no href)
1150 $line .= esc_path($to->{'file'});
1151 }
1152 } else {
1153 # "ordinary" diff
1154 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1155 if ($from->{'href'}) {
1156 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1157 'a/' . esc_path($from->{'file'}));
1158 } else { # file was added (no href)
1159 $line .= 'a/' . esc_path($from->{'file'});
1160 }
1161 $line .= ' ';
1162 if ($to->{'href'}) {
1163 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1164 'b/' . esc_path($to->{'file'}));
1165 } else { # file was deleted
1166 $line .= 'b/' . esc_path($to->{'file'});
1167 }
1168 }
1169
1170 return "<div class=\"diff header\">$line</div>\n";
1171 }
1172
1173 # format extended diff header line, before patch itself
1174 sub format_extended_diff_header_line {
1175 my $line = shift;
1176 my $diffinfo = shift;
1177 my ($from, $to) = @_;
1178
1179 # match <path>
1180 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1181 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1182 esc_path($from->{'file'}));
1183 }
1184 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1185 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1186 esc_path($to->{'file'}));
1187 }
1188 # match single <mode>
1189 if ($line =~ m/\s(\d{6})$/) {
1190 $line .= '<span class="info"> (' .
1191 file_type_long($1) .
1192 ')</span>';
1193 }
1194 # match <hash>
1195 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1196 # can match only for combined diff
1197 $line = 'index ';
1198 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1199 if ($from->{'href'}[$i]) {
1200 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1201 -class=>"hash"},
1202 substr($diffinfo->{'from_id'}[$i],0,7));
1203 } else {
1204 $line .= '0' x 7;
1205 }
1206 # separator
1207 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1208 }
1209 $line .= '..';
1210 if ($to->{'href'}) {
1211 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1212 substr($diffinfo->{'to_id'},0,7));
1213 } else {
1214 $line .= '0' x 7;
1215 }
1216
1217 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1218 # can match only for ordinary diff
1219 my ($from_link, $to_link);
1220 if ($from->{'href'}) {
1221 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1222 substr($diffinfo->{'from_id'},0,7));
1223 } else {
1224 $from_link = '0' x 7;
1225 }
1226 if ($to->{'href'}) {
1227 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1228 substr($diffinfo->{'to_id'},0,7));
1229 } else {
1230 $to_link = '0' x 7;
1231 }
1232 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1233 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1234 }
1235
1236 return $line . "<br/>\n";
1237 }
1238
1239 # format from-file/to-file diff header
1240 sub format_diff_from_to_header {
1241 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1242 my $line;
1243 my $result = '';
1244
1245 $line = $from_line;
1246 #assert($line =~ m/^---/) if DEBUG;
1247 # no extra formatting for "^--- /dev/null"
1248 if (! $diffinfo->{'nparents'}) {
1249 # ordinary (single parent) diff
1250 if ($line =~ m!^--- "?a/!) {
1251 if ($from->{'href'}) {
1252 $line = '--- a/' .
1253 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1254 esc_path($from->{'file'}));
1255 } else {
1256 $line = '--- a/' .
1257 esc_path($from->{'file'});
1258 }
1259 }
1260 $result .= qq!<div class="diff from_file">$line</div>\n!;
1261
1262 } else {
1263 # combined diff (merge commit)
1264 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1265 if ($from->{'href'}[$i]) {
1266 $line = '--- ' .
1267 $cgi->a({-href=>href(action=>"blobdiff",
1268 hash_parent=>$diffinfo->{'from_id'}[$i],
1269 hash_parent_base=>$parents[$i],
1270 file_parent=>$from->{'file'}[$i],
1271 hash=>$diffinfo->{'to_id'},
1272 hash_base=>$hash,
1273 file_name=>$to->{'file'}),
1274 -class=>"path",
1275 -title=>"diff" . ($i+1)},
1276 $i+1) .
1277 '/' .
1278 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1279 esc_path($from->{'file'}[$i]));
1280 } else {
1281 $line = '--- /dev/null';
1282 }
1283 $result .= qq!<div class="diff from_file">$line</div>\n!;
1284 }
1285 }
1286
1287 $line = $to_line;
1288 #assert($line =~ m/^\+\+\+/) if DEBUG;
1289 # no extra formatting for "^+++ /dev/null"
1290 if ($line =~ m!^\+\+\+ "?b/!) {
1291 if ($to->{'href'}) {
1292 $line = '+++ b/' .
1293 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1294 esc_path($to->{'file'}));
1295 } else {
1296 $line = '+++ b/' .
1297 esc_path($to->{'file'});
1298 }
1299 }
1300 $result .= qq!<div class="diff to_file">$line</div>\n!;
1301
1302 return $result;
1303 }
1304
1305 # create note for patch simplified by combined diff
1306 sub format_diff_cc_simplified {
1307 my ($diffinfo, @parents) = @_;
1308 my $result = '';
1309
1310 $result .= "<div class=\"diff header\">" .
1311 "diff --cc ";
1312 if (!is_deleted($diffinfo)) {
1313 $result .= $cgi->a({-href => href(action=>"blob",
1314 hash_base=>$hash,
1315 hash=>$diffinfo->{'to_id'},
1316 file_name=>$diffinfo->{'to_file'}),
1317 -class => "path"},
1318 esc_path($diffinfo->{'to_file'}));
1319 } else {
1320 $result .= esc_path($diffinfo->{'to_file'});
1321 }
1322 $result .= "</div>\n" . # class="diff header"
1323 "<div class=\"diff nodifferences\">" .
1324 "Simple merge" .
1325 "</div>\n"; # class="diff nodifferences"
1326
1327 return $result;
1328 }
1329
1330 # format patch (diff) line (not to be used for diff headers)
1331 sub format_diff_line {
1332 my $line = shift;
1333 my ($from, $to) = @_;
1334 my $diff_class = "";
1335
1336 chomp $line;
1337
1338 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1339 # combined diff
1340 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1341 if ($line =~ m/^\@{3}/) {
1342 $diff_class = " chunk_header";
1343 } elsif ($line =~ m/^\\/) {
1344 $diff_class = " incomplete";
1345 } elsif ($prefix =~ tr/+/+/) {
1346 $diff_class = " add";
1347 } elsif ($prefix =~ tr/-/-/) {
1348 $diff_class = " rem";
1349 }
1350 } else {
1351 # assume ordinary diff
1352 my $char = substr($line, 0, 1);
1353 if ($char eq '+') {
1354 $diff_class = " add";
1355 } elsif ($char eq '-') {
1356 $diff_class = " rem";
1357 } elsif ($char eq '@') {
1358 $diff_class = " chunk_header";
1359 } elsif ($char eq "\\") {
1360 $diff_class = " incomplete";
1361 }
1362 }
1363 $line = untabify($line);
1364 if ($from && $to && $line =~ m/^\@{2} /) {
1365 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1366 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1367
1368 $from_lines = 0 unless defined $from_lines;
1369 $to_lines = 0 unless defined $to_lines;
1370
1371 if ($from->{'href'}) {
1372 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1373 -class=>"list"}, $from_text);
1374 }
1375 if ($to->{'href'}) {
1376 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1377 -class=>"list"}, $to_text);
1378 }
1379 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1380 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1381 return "<div class=\"diff$diff_class\">$line</div>\n";
1382 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1383 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1384 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1385
1386 @from_text = split(' ', $ranges);
1387 for (my $i = 0; $i < @from_text; ++$i) {
1388 ($from_start[$i], $from_nlines[$i]) =
1389 (split(',', substr($from_text[$i], 1)), 0);
1390 }
1391
1392 $to_text = pop @from_text;
1393 $to_start = pop @from_start;
1394 $to_nlines = pop @from_nlines;
1395
1396 $line = "<span class=\"chunk_info\">$prefix ";
1397 for (my $i = 0; $i < @from_text; ++$i) {
1398 if ($from->{'href'}[$i]) {
1399 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1400 -class=>"list"}, $from_text[$i]);
1401 } else {
1402 $line .= $from_text[$i];
1403 }
1404 $line .= " ";
1405 }
1406 if ($to->{'href'}) {
1407 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1408 -class=>"list"}, $to_text);
1409 } else {
1410 $line .= $to_text;
1411 }
1412 $line .= " $prefix</span>" .
1413 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1414 return "<div class=\"diff$diff_class\">$line</div>\n";
1415 }
1416 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1417 }
1418
1419 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1420 # linked. Pass the hash of the tree/commit to snapshot.
1421 sub format_snapshot_links {
1422 my ($hash) = @_;
1423 my @snapshot_fmts = gitweb_check_feature('snapshot');
1424 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1425 my $num_fmts = @snapshot_fmts;
1426 if ($num_fmts > 1) {
1427 # A parenthesized list of links bearing format names.
1428 # e.g. "snapshot (_tar.gz_ _zip_)"
1429 return "snapshot (" . join(' ', map
1430 $cgi->a({
1431 -href => href(
1432 action=>"snapshot",
1433 hash=>$hash,
1434 snapshot_format=>$_
1435 )
1436 }, $known_snapshot_formats{$_}{'display'})
1437 , @snapshot_fmts) . ")";
1438 } elsif ($num_fmts == 1) {
1439 # A single "snapshot" link whose tooltip bears the format name.
1440 # i.e. "_snapshot_"
1441 my ($fmt) = @snapshot_fmts;
1442 return
1443 $cgi->a({
1444 -href => href(
1445 action=>"snapshot",
1446 hash=>$hash,
1447 snapshot_format=>$fmt
1448 ),
1449 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1450 }, "snapshot");
1451 } else { # $num_fmts == 0
1452 return undef;
1453 }
1454 }
1455
1456 ## ......................................................................
1457 ## functions returning values to be passed, perhaps after some
1458 ## transformation, to other functions; e.g. returning arguments to href()
1459
1460 # returns hash to be passed to href to generate gitweb URL
1461 # in -title key it returns description of link
1462 sub get_feed_info {
1463 my $format = shift || 'Atom';
1464 my %res = (action => lc($format));
1465
1466 # feed links are possible only for project views
1467 return unless (defined $project);
1468 # some views should link to OPML, or to generic project feed,
1469 # or don't have specific feed yet (so they should use generic)
1470 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
1471
1472 my $branch;
1473 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
1474 # from tag links; this also makes possible to detect branch links
1475 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
1476 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
1477 $branch = $1;
1478 }
1479 # find log type for feed description (title)
1480 my $type = 'log';
1481 if (defined $file_name) {
1482 $type = "history of $file_name";
1483 $type .= "/" if ($action eq 'tree');
1484 $type .= " on '$branch'" if (defined $branch);
1485 } else {
1486 $type = "log of $branch" if (defined $branch);
1487 }
1488
1489 $res{-title} = $type;
1490 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
1491 $res{'file_name'} = $file_name;
1492
1493 return %res;
1494 }
1495
1496 ## ----------------------------------------------------------------------
1497 ## git utility subroutines, invoking git commands
1498
1499 # returns path to the core git executable and the --git-dir parameter as list
1500 sub git_cmd {
1501 return $GIT, '--git-dir='.$git_dir;
1502 }
1503
1504 # quote the given arguments for passing them to the shell
1505 # quote_command("command", "arg 1", "arg with ' and ! characters")
1506 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
1507 # Try to avoid using this function wherever possible.
1508 sub quote_command {
1509 return join(' ',
1510 map( { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ ));
1511 }
1512
1513 # get HEAD ref of given project as hash
1514 sub git_get_head_hash {
1515 my $project = shift;
1516 my $o_git_dir = $git_dir;
1517 my $retval = undef;
1518 $git_dir = "$projectroot/$project";
1519 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
1520 my $head = <$fd>;
1521 close $fd;
1522 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
1523 $retval = $1;
1524 }
1525 }
1526 if (defined $o_git_dir) {
1527 $git_dir = $o_git_dir;
1528 }
1529 return $retval;
1530 }
1531
1532 # get type of given object
1533 sub git_get_type {
1534 my $hash = shift;
1535
1536 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
1537 my $type = <$fd>;
1538 close $fd or return;
1539 chomp $type;
1540 return $type;
1541 }
1542
1543 # repository configuration
1544 our $config_file = '';
1545 our %config;
1546
1547 # store multiple values for single key as anonymous array reference
1548 # single values stored directly in the hash, not as [ <value> ]
1549 sub hash_set_multi {
1550 my ($hash, $key, $value) = @_;
1551
1552 if (!exists $hash->{$key}) {
1553 $hash->{$key} = $value;
1554 } elsif (!ref $hash->{$key}) {
1555 $hash->{$key} = [ $hash->{$key}, $value ];
1556 } else {
1557 push @{$hash->{$key}}, $value;
1558 }
1559 }
1560
1561 # return hash of git project configuration
1562 # optionally limited to some section, e.g. 'gitweb'
1563 sub git_parse_project_config {
1564 my $section_regexp = shift;
1565 my %config;
1566
1567 local $/ = "\0";
1568
1569 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
1570 or return;
1571
1572 while (my $keyval = <$fh>) {
1573 chomp $keyval;
1574 my ($key, $value) = split(/\n/, $keyval, 2);
1575
1576 hash_set_multi(\%config, $key, $value)
1577 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
1578 }
1579 close $fh;
1580
1581 return %config;
1582 }
1583
1584 # convert config value to boolean, 'true' or 'false'
1585 # no value, number > 0, 'true' and 'yes' values are true
1586 # rest of values are treated as false (never as error)
1587 sub config_to_bool {
1588 my $val = shift;
1589
1590 # strip leading and trailing whitespace
1591 $val =~ s/^\s+//;
1592 $val =~ s/\s+$//;
1593
1594 return (!defined $val || # section.key
1595 ($val =~ /^\d+$/ && $val) || # section.key = 1
1596 ($val =~ /^(?:true|yes)$/i)); # section.key = true
1597 }
1598
1599 # convert config value to simple decimal number
1600 # an optional value suffix of 'k', 'm', or 'g' will cause the value
1601 # to be multiplied by 1024, 1048576, or 1073741824
1602 sub config_to_int {
1603 my $val = shift;
1604
1605 # strip leading and trailing whitespace
1606 $val =~ s/^\s+//;
1607 $val =~ s/\s+$//;
1608
1609 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
1610 $unit = lc($unit);
1611 # unknown unit is treated as 1
1612 return $num * ($unit eq 'g' ? 1073741824 :
1613 $unit eq 'm' ? 1048576 :
1614 $unit eq 'k' ? 1024 : 1);
1615 }
1616 return $val;
1617 }
1618
1619 # convert config value to array reference, if needed
1620 sub config_to_multi {
1621 my $val = shift;
1622
1623 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
1624 }
1625
1626 sub git_get_project_config {
1627 my ($key, $type) = @_;
1628
1629 # key sanity check
1630 return unless ($key);
1631 $key =~ s/^gitweb\.//;
1632 return if ($key =~ m/\W/);
1633
1634 # type sanity check
1635 if (defined $type) {
1636 $type =~ s/^--//;
1637 $type = undef
1638 unless ($type eq 'bool' || $type eq 'int');
1639 }
1640
1641 # get config
1642 if (!defined $config_file ||
1643 $config_file ne "$git_dir/config") {
1644 %config = git_parse_project_config('gitweb');
1645 $config_file = "$git_dir/config";
1646 }
1647
1648 # ensure given type
1649 if (!defined $type) {
1650 return $config{"gitweb.$key"};
1651 } elsif ($type eq 'bool') {
1652 # backward compatibility: 'git config --bool' returns true/false
1653 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
1654 } elsif ($type eq 'int') {
1655 return config_to_int($config{"gitweb.$key"});
1656 }
1657 return $config{"gitweb.$key"};
1658 }
1659
1660 # get hash of given path at given ref
1661 sub git_get_hash_by_path {
1662 my $base = shift;
1663 my $path = shift || return undef;
1664 my $type = shift;
1665
1666 $path =~ s,/+$,,;
1667
1668 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
1669 or die_error(500, "Open git-ls-tree failed");
1670 my $line = <$fd>;
1671 close $fd or return undef;
1672
1673 if (!defined $line) {
1674 # there is no tree or hash given by $path at $base
1675 return undef;
1676 }
1677
1678 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
1679 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
1680 if (defined $type && $type ne $2) {
1681 # type doesn't match
1682 return undef;
1683 }
1684 return $3;
1685 }
1686
1687 # get path of entry with given hash at given tree-ish (ref)
1688 # used to get 'from' filename for combined diff (merge commit) for renames
1689 sub git_get_path_by_hash {
1690 my $base = shift || return;
1691 my $hash = shift || return;
1692
1693 local $/ = "\0";
1694
1695 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
1696 or return undef;
1697 while (my $line = <$fd>) {
1698 chomp $line;
1699
1700 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
1701 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
1702 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
1703 close $fd;
1704 return $1;
1705 }
1706 }
1707 close $fd;
1708 return undef;
1709 }
1710
1711 ## ......................................................................
1712 ## git utility functions, directly accessing git repository
1713
1714 sub git_get_project_description {
1715 my $path = shift;
1716
1717 $git_dir = "$projectroot/$path";
1718 open my $fd, "$git_dir/description"
1719 or return git_get_project_config('description');
1720 my $descr = <$fd>;
1721 close $fd;
1722 if (defined $descr) {
1723 chomp $descr;
1724 }
1725 return $descr;
1726 }
1727
1728 sub git_get_project_url_list {
1729 my $path = shift;
1730
1731 $git_dir = "$projectroot/$path";
1732 open my $fd, "$git_dir/cloneurl"
1733 or return wantarray ?
1734 @{ config_to_multi(git_get_project_config('url')) } :
1735 config_to_multi(git_get_project_config('url'));
1736 my @git_project_url_list = map { chomp; $_ } <$fd>;
1737 close $fd;
1738
1739 return wantarray ? @git_project_url_list : \@git_project_url_list;
1740 }
1741
1742 sub git_get_projects_list {
1743 my ($filter) = @_;
1744 my @list;
1745
1746 $filter ||= '';
1747 $filter =~ s/\.git$//;
1748
1749 my ($check_forks) = gitweb_check_feature('forks');
1750
1751 if (-d $projects_list) {
1752 # search in directory
1753 my $dir = $projects_list . ($filter ? "/$filter" : '');
1754 # remove the trailing "/"
1755 $dir =~ s!/+$!!;
1756 my $pfxlen = length("$dir");
1757 my $pfxdepth = ($dir =~ tr!/!!);
1758
1759 File::Find::find({
1760 follow_fast => 1, # follow symbolic links
1761 follow_skip => 2, # ignore duplicates
1762 dangling_symlinks => 0, # ignore dangling symlinks, silently
1763 wanted => sub {
1764 # skip project-list toplevel, if we get it.
1765 return if (m!^[/.]$!);
1766 # only directories can be git repositories
1767 return unless (-d $_);
1768 # don't traverse too deep (Find is super slow on os x)
1769 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
1770 $File::Find::prune = 1;
1771 return;
1772 }
1773
1774 my $subdir = substr($File::Find::name, $pfxlen + 1);
1775 # we check related file in $projectroot
1776 if ($check_forks and $subdir =~ m#/.#) {
1777 $File::Find::prune = 1;
1778 } elsif (check_export_ok("$projectroot/$filter/$subdir")) {
1779 push @list, { path => ($filter ? "$filter/" : '') . $subdir };
1780 $File::Find::prune = 1;
1781 }
1782 },
1783 }, "$dir");
1784
1785 } elsif (-f $projects_list) {
1786 # read from file(url-encoded):
1787 # 'git%2Fgit.git Linus+Torvalds'
1788 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1789 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1790 my %paths;
1791 open my ($fd), $projects_list or return;
1792 PROJECT:
1793 while (my $line = <$fd>) {
1794 chomp $line;
1795 my ($path, $owner) = split ' ', $line;
1796 $path = unescape($path);
1797 $owner = unescape($owner);
1798 if (!defined $path) {
1799 next;
1800 }
1801 if ($filter ne '') {
1802 # looking for forks;
1803 my $pfx = substr($path, 0, length($filter));
1804 if ($pfx ne $filter) {
1805 next PROJECT;
1806 }
1807 my $sfx = substr($path, length($filter));
1808 if ($sfx !~ /^\/.*\.git$/) {
1809 next PROJECT;
1810 }
1811 } elsif ($check_forks) {
1812 PATH:
1813 foreach my $filter (keys %paths) {
1814 # looking for forks;
1815 my $pfx = substr($path, 0, length($filter));
1816 if ($pfx ne $filter) {
1817 next PATH;
1818 }
1819 my $sfx = substr($path, length($filter));
1820 if ($sfx !~ /^\/.*\.git$/) {
1821 next PATH;
1822 }
1823 # is a fork, don't include it in
1824 # the list
1825 next PROJECT;
1826 }
1827 }
1828 if (check_export_ok("$projectroot/$path")) {
1829 my $pr = {
1830 path => $path,
1831 owner => to_utf8($owner),
1832 };
1833 push @list, $pr;
1834 (my $forks_path = $path) =~ s/\.git$//;
1835 $paths{$forks_path}++;
1836 }
1837 }
1838 close $fd;
1839 }
1840 return @list;
1841 }
1842
1843 our $gitweb_project_owner = undef;
1844 sub git_get_project_list_from_file {
1845
1846 return if (defined $gitweb_project_owner);
1847
1848 $gitweb_project_owner = {};
1849 # read from file (url-encoded):
1850 # 'git%2Fgit.git Linus+Torvalds'
1851 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
1852 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
1853 if (-f $projects_list) {
1854 open (my $fd , $projects_list);
1855 while (my $line = <$fd>) {
1856 chomp $line;
1857 my ($pr, $ow) = split ' ', $line;
1858 $pr = unescape($pr);
1859 $ow = unescape($ow);
1860 $gitweb_project_owner->{$pr} = to_utf8($ow);
1861 }
1862 close $fd;
1863 }
1864 }
1865
1866 sub git_get_project_owner {
1867 my $project = shift;
1868 my $owner;
1869
1870 return undef unless $project;
1871 $git_dir = "$projectroot/$project";
1872
1873 if (!defined $gitweb_project_owner) {
1874 git_get_project_list_from_file();
1875 }
1876
1877 if (exists $gitweb_project_owner->{$project}) {
1878 $owner = $gitweb_project_owner->{$project};
1879 }
1880 if (!defined $owner){
1881 $owner = git_get_project_config('owner');
1882 }
1883 if (!defined $owner) {
1884 $owner = get_file_owner("$git_dir");
1885 }
1886
1887 return $owner;
1888 }
1889
1890 sub git_get_last_activity {
1891 my ($path) = @_;
1892 my $fd;
1893
1894 $git_dir = "$projectroot/$path";
1895 open($fd, "-|", git_cmd(), 'for-each-ref',
1896 '--format=%(committer)',
1897 '--sort=-committerdate',
1898 '--count=1',
1899 'refs/heads') or return;
1900 my $most_recent = <$fd>;
1901 close $fd or return;
1902 if (defined $most_recent &&
1903 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
1904 my $timestamp = $1;
1905 my $age = time - $timestamp;
1906 return ($age, age_string($age));
1907 }
1908 return (undef, undef);
1909 }
1910
1911 sub git_get_references {
1912 my $type = shift || "";
1913 my %refs;
1914 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
1915 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
1916 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
1917 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
1918 or return;
1919
1920 while (my $line = <$fd>) {
1921 chomp $line;
1922 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type/?[^^]+)!) {
1923 if (defined $refs{$1}) {
1924 push @{$refs{$1}}, $2;
1925 } else {
1926 $refs{$1} = [ $2 ];
1927 }
1928 }
1929 }
1930 close $fd or return;
1931 return \%refs;
1932 }
1933
1934 sub git_get_rev_name_tags {
1935 my $hash = shift || return undef;
1936
1937 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
1938 or return;
1939 my $name_rev = <$fd>;
1940 close $fd;
1941
1942 if ($name_rev =~ m|^$hash tags/(.*)$|) {
1943 return $1;
1944 } else {
1945 # catches also '$hash undefined' output
1946 return undef;
1947 }
1948 }
1949
1950 ## ----------------------------------------------------------------------
1951 ## parse to hash functions
1952
1953 sub parse_date {
1954 my $epoch = shift;
1955 my $tz = shift || "-0000";
1956
1957 my %date;
1958 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
1959 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
1960 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
1961 $date{'hour'} = $hour;
1962 $date{'minute'} = $min;
1963 $date{'mday'} = $mday;
1964 $date{'day'} = $days[$wday];
1965 $date{'month'} = $months[$mon];
1966 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
1967 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
1968 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
1969 $mday, $months[$mon], $hour ,$min;
1970 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
1971 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
1972
1973 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
1974 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
1975 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
1976 $date{'hour_local'} = $hour;
1977 $date{'minute_local'} = $min;
1978 $date{'tz_local'} = $tz;
1979 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
1980 1900+$year, $mon+1, $mday,
1981 $hour, $min, $sec, $tz);
1982 return %date;
1983 }
1984
1985 sub parse_tag {
1986 my $tag_id = shift;
1987 my %tag;
1988 my @comment;
1989
1990 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
1991 $tag{'id'} = $tag_id;
1992 while (my $line = <$fd>) {
1993 chomp $line;
1994 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
1995 $tag{'object'} = $1;
1996 } elsif ($line =~ m/^type (.+)$/) {
1997 $tag{'type'} = $1;
1998 } elsif ($line =~ m/^tag (.+)$/) {
1999 $tag{'name'} = $1;
2000 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2001 $tag{'author'} = $1;
2002 $tag{'epoch'} = $2;
2003 $tag{'tz'} = $3;
2004 } elsif ($line =~ m/--BEGIN/) {
2005 push @comment, $line;
2006 last;
2007 } elsif ($line eq "") {
2008 last;
2009 }
2010 }
2011 push @comment, <$fd>;
2012 $tag{'comment'} = \@comment;
2013 close $fd or return;
2014 if (!defined $tag{'name'}) {
2015 return
2016 };
2017 return %tag
2018 }
2019
2020 sub parse_commit_text {
2021 my ($commit_text, $withparents) = @_;
2022 my @commit_lines = split '\n', $commit_text;
2023 my %co;
2024
2025 pop @commit_lines; # Remove '\0'
2026
2027 if (! @commit_lines) {
2028 return;
2029 }
2030
2031 my $header = shift @commit_lines;
2032 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2033 return;
2034 }
2035 ($co{'id'}, my @parents) = split ' ', $header;
2036 while (my $line = shift @commit_lines) {
2037 last if $line eq "\n";
2038 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2039 $co{'tree'} = $1;
2040 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2041 push @parents, $1;
2042 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2043 $co{'author'} = $1;
2044 $co{'author_epoch'} = $2;
2045 $co{'author_tz'} = $3;
2046 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2047 $co{'author_name'} = $1;
2048 $co{'author_email'} = $2;
2049 } else {
2050 $co{'author_name'} = $co{'author'};
2051 }
2052 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2053 $co{'committer'} = $1;
2054 $co{'committer_epoch'} = $2;
2055 $co{'committer_tz'} = $3;
2056 $co{'committer_name'} = $co{'committer'};
2057 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2058 $co{'committer_name'} = $1;
2059 $co{'committer_email'} = $2;
2060 } else {
2061 $co{'committer_name'} = $co{'committer'};
2062 }
2063 }
2064 }
2065 if (!defined $co{'tree'}) {
2066 return;
2067 };
2068 $co{'parents'} = \@parents;
2069 $co{'parent'} = $parents[0];
2070
2071 foreach my $title (@commit_lines) {
2072 $title =~ s/^ //;
2073 if ($title ne "") {
2074 $co{'title'} = chop_str($title, 80, 5);
2075 # remove leading stuff of merges to make the interesting part visible
2076 if (length($title) > 50) {
2077 $title =~ s/^Automatic //;
2078 $title =~ s/^merge (of|with) /Merge ... /i;
2079 if (length($title) > 50) {
2080 $title =~ s/(http|rsync):\/\///;
2081 }
2082 if (length($title) > 50) {
2083 $title =~ s/(master|www|rsync)\.//;
2084 }
2085 if (length($title) > 50) {
2086 $title =~ s/kernel.org:?//;
2087 }
2088 if (length($title) > 50) {
2089 $title =~ s/\/pub\/scm//;
2090 }
2091 }
2092 $co{'title_short'} = chop_str($title, 50, 5);
2093 last;
2094 }
2095 }
2096 if ($co{'title'} eq "") {
2097 $co{'title'} = $co{'title_short'} = '(no commit message)';
2098 }
2099 # remove added spaces
2100 foreach my $line (@commit_lines) {
2101 $line =~ s/^ //;
2102 }
2103 $co{'comment'} = \@commit_lines;
2104
2105 my $age = time - $co{'committer_epoch'};
2106 $co{'age'} = $age;
2107 $co{'age_string'} = age_string($age);
2108 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2109 if ($age > 60*60*24*7*2) {
2110 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2111 $co{'age_string_age'} = $co{'age_string'};
2112 } else {
2113 $co{'age_string_date'} = $co{'age_string'};
2114 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2115 }
2116 return %co;
2117 }
2118
2119 sub parse_commit {
2120 my ($commit_id) = @_;
2121 my %co;
2122
2123 local $/ = "\0";
2124
2125 open my $fd, "-|", git_cmd(), "rev-list",
2126 "--parents",
2127 "--header",
2128 "--max-count=1",
2129 $commit_id,
2130 "--",
2131 or die_error(500, "Open git-rev-list failed");
2132 %co = parse_commit_text(<$fd>, 1);
2133 close $fd;
2134
2135 return %co;
2136 }
2137
2138 sub parse_commits {
2139 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2140 my @cos;
2141
2142 $maxcount ||= 1;
2143 $skip ||= 0;
2144
2145 local $/ = "\0";
2146
2147 open my $fd, "-|", git_cmd(), "rev-list",
2148 "--header",
2149 @args,
2150 ("--max-count=" . $maxcount),
2151 ("--skip=" . $skip),
2152 @extra_options,
2153 $commit_id,
2154 "--",
2155 ($filename ? ($filename) : ())
2156 or die_error(500, "Open git-rev-list failed");
2157 while (my $line = <$fd>) {
2158 my %co = parse_commit_text($line);
2159 push @cos, \%co;
2160 }
2161 close $fd;
2162
2163 return wantarray ? @cos : \@cos;
2164 }
2165
2166 # parse line of git-diff-tree "raw" output
2167 sub parse_difftree_raw_line {
2168 my $line = shift;
2169 my %res;
2170
2171 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2172 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2173 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2174 $res{'from_mode'} = $1;
2175 $res{'to_mode'} = $2;
2176 $res{'from_id'} = $3;
2177 $res{'to_id'} = $4;
2178 $res{'status'} = $5;
2179 $res{'similarity'} = $6;
2180 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2181 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2182 } else {
2183 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2184 }
2185 }
2186 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2187 # combined diff (for merge commit)
2188 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2189 $res{'nparents'} = length($1);
2190 $res{'from_mode'} = [ split(' ', $2) ];
2191 $res{'to_mode'} = pop @{$res{'from_mode'}};
2192 $res{'from_id'} = [ split(' ', $3) ];
2193 $res{'to_id'} = pop @{$res{'from_id'}};
2194 $res{'status'} = [ split('', $4) ];
2195 $res{'to_file'} = unquote($5);
2196 }
2197 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2198 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2199 $res{'commit'} = $1;
2200 }
2201
2202 return wantarray ? %res : \%res;
2203 }
2204
2205 # wrapper: return parsed line of git-diff-tree "raw" output
2206 # (the argument might be raw line, or parsed info)
2207 sub parsed_difftree_line {
2208 my $line_or_ref = shift;
2209
2210 if (ref($line_or_ref) eq "HASH") {
2211 # pre-parsed (or generated by hand)
2212 return $line_or_ref;
2213 } else {
2214 return parse_difftree_raw_line($line_or_ref);
2215 }
2216 }
2217
2218 # parse line of git-ls-tree output
2219 sub parse_ls_tree_line ($;%) {
2220 my $line = shift;
2221 my %opts = @_;
2222 my %res;
2223
2224 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2225 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2226
2227 $res{'mode'} = $1;
2228 $res{'type'} = $2;
2229 $res{'hash'} = $3;
2230 if ($opts{'-z'}) {
2231 $res{'name'} = $4;
2232 } else {
2233 $res{'name'} = unquote($4);
2234 }
2235
2236 return wantarray ? %res : \%res;
2237 }
2238
2239 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2240 sub parse_from_to_diffinfo {
2241 my ($diffinfo, $from, $to, @parents) = @_;
2242
2243 if ($diffinfo->{'nparents'}) {
2244 # combined diff
2245 $from->{'file'} = [];
2246 $from->{'href'} = [];
2247 fill_from_file_info($diffinfo, @parents)
2248 unless exists $diffinfo->{'from_file'};
2249 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2250 $from->{'file'}[$i] =
2251 defined $diffinfo->{'from_file'}[$i] ?
2252 $diffinfo->{'from_file'}[$i] :
2253 $diffinfo->{'to_file'};
2254 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2255 $from->{'href'}[$i] = href(action=>"blob",
2256 hash_base=>$parents[$i],
2257 hash=>$diffinfo->{'from_id'}[$i],
2258 file_name=>$from->{'file'}[$i]);
2259 } else {
2260 $from->{'href'}[$i] = undef;
2261 }
2262 }
2263 } else {
2264 # ordinary (not combined) diff
2265 $from->{'file'} = $diffinfo->{'from_file'};
2266 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2267 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2268 hash=>$diffinfo->{'from_id'},
2269 file_name=>$from->{'file'});
2270 } else {
2271 delete $from->{'href'};
2272 }
2273 }
2274
2275 $to->{'file'} = $diffinfo->{'to_file'};
2276 if (!is_deleted($diffinfo)) { # file exists in result
2277 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2278 hash=>$diffinfo->{'to_id'},
2279 file_name=>$to->{'file'});
2280 } else {
2281 delete $to->{'href'};
2282 }
2283 }
2284
2285 ## ......................................................................
2286 ## parse to array of hashes functions
2287
2288 sub git_get_heads_list {
2289 my $limit = shift;
2290 my @headslist;
2291
2292 open my $fd, '-|', git_cmd(), 'for-each-ref',
2293 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2294 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2295 'refs/heads'
2296 or return;
2297 while (my $line = <$fd>) {
2298 my %ref_item;
2299
2300 chomp $line;
2301 my ($refinfo, $committerinfo) = split(/\0/, $line);
2302 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2303 my ($committer, $epoch, $tz) =
2304 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2305 $ref_item{'fullname'} = $name;
2306 $name =~ s!^refs/heads/!!;
2307
2308 $ref_item{'name'} = $name;
2309 $ref_item{'id'} = $hash;
2310 $ref_item{'title'} = $title || '(no commit message)';
2311 $ref_item{'epoch'} = $epoch;
2312 if ($epoch) {
2313 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2314 } else {
2315 $ref_item{'age'} = "unknown";
2316 }
2317
2318 push @headslist, \%ref_item;
2319 }
2320 close $fd;
2321
2322 return wantarray ? @headslist : \@headslist;
2323 }
2324
2325 sub git_get_tags_list {
2326 my $limit = shift;
2327 my @tagslist;
2328
2329 open my $fd, '-|', git_cmd(), 'for-each-ref',
2330 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2331 '--format=%(objectname) %(objecttype) %(refname) '.
2332 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2333 'refs/tags'
2334 or return;
2335 while (my $line = <$fd>) {
2336 my %ref_item;
2337
2338 chomp $line;
2339 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2340 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2341 my ($creator, $epoch, $tz) =
2342 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2343 $ref_item{'fullname'} = $name;
2344 $name =~ s!^refs/tags/!!;
2345
2346 $ref_item{'type'} = $type;
2347 $ref_item{'id'} = $id;
2348 $ref_item{'name'} = $name;
2349 if ($type eq "tag") {
2350 $ref_item{'subject'} = $title;
2351 $ref_item{'reftype'} = $reftype;
2352 $ref_item{'refid'} = $refid;
2353 } else {
2354 $ref_item{'reftype'} = $type;
2355 $ref_item{'refid'} = $id;
2356 }
2357
2358 if ($type eq "tag" || $type eq "commit") {
2359 $ref_item{'epoch'} = $epoch;
2360 if ($epoch) {
2361 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2362 } else {
2363 $ref_item{'age'} = "unknown";
2364 }
2365 }
2366
2367 push @tagslist, \%ref_item;
2368 }
2369 close $fd;
2370
2371 return wantarray ? @tagslist : \@tagslist;
2372 }
2373
2374 ## ----------------------------------------------------------------------
2375 ## filesystem-related functions
2376
2377 sub get_file_owner {
2378 my $path = shift;
2379
2380 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2381 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2382 if (!defined $gcos) {
2383 return undef;
2384 }
2385 my $owner = $gcos;
2386 $owner =~ s/[,;].*$//;
2387 return to_utf8($owner);
2388 }
2389
2390 ## ......................................................................
2391 ## mimetype related functions
2392
2393 sub mimetype_guess_file {
2394 my $filename = shift;
2395 my $mimemap = shift;
2396 -r $mimemap or return undef;
2397
2398 my %mimemap;
2399 open(MIME, $mimemap) or return undef;
2400 while (<MIME>) {
2401 next if m/^#/; # skip comments
2402 my ($mime, $exts) = split(/\t+/);
2403 if (defined $exts) {
2404 my @exts = split(/\s+/, $exts);
2405 foreach my $ext (@exts) {
2406 $mimemap{$ext} = $mime;
2407 }
2408 }
2409 }
2410 close(MIME);
2411
2412 $filename =~ /\.([^.]*)$/;
2413 return $mimemap{$1};
2414 }
2415
2416 sub mimetype_guess {
2417 my $filename = shift;
2418 my $mime;
2419 $filename =~ /\./ or return undef;
2420
2421 if ($mimetypes_file) {
2422 my $file = $mimetypes_file;
2423 if ($file !~ m!^/!) { # if it is relative path
2424 # it is relative to project
2425 $file = "$projectroot/$project/$file";
2426 }
2427 $mime = mimetype_guess_file($filename, $file);
2428 }
2429 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
2430 return $mime;
2431 }
2432
2433 sub blob_mimetype {
2434 my $fd = shift;
2435 my $filename = shift;
2436
2437 if ($filename) {
2438 my $mime = mimetype_guess($filename);
2439 $mime and return $mime;
2440 }
2441
2442 # just in case
2443 return $default_blob_plain_mimetype unless $fd;
2444
2445 if (-T $fd) {
2446 return 'text/plain';
2447 } elsif (! $filename) {
2448 return 'application/octet-stream';
2449 } elsif ($filename =~ m/\.png$/i) {
2450 return 'image/png';
2451 } elsif ($filename =~ m/\.gif$/i) {
2452 return 'image/gif';
2453 } elsif ($filename =~ m/\.jpe?g$/i) {
2454 return 'image/jpeg';
2455 } else {
2456 return 'application/octet-stream';
2457 }
2458 }
2459
2460 sub blob_contenttype {
2461 my ($fd, $file_name, $type) = @_;
2462
2463 $type ||= blob_mimetype($fd, $file_name);
2464 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
2465 $type .= "; charset=$default_text_plain_charset";
2466 }
2467
2468 return $type;
2469 }
2470
2471 ## ======================================================================
2472 ## functions printing HTML: header, footer, error page
2473
2474 sub git_header_html {
2475 my $status = shift || "200 OK";
2476 my $expires = shift;
2477
2478 my $title = "$site_name";
2479 if (defined $project) {
2480 $title .= " - " . to_utf8($project);
2481 if (defined $action) {
2482 $title .= "/$action";
2483 if (defined $file_name) {
2484 $title .= " - " . esc_path($file_name);
2485 if ($action eq "tree" && $file_name !~ m|/$|) {
2486 $title .= "/";
2487 }
2488 }
2489 }
2490 }
2491 my $content_type;
2492 # require explicit support from the UA if we are to send the page as
2493 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
2494 # we have to do this because MSIE sometimes globs '*/*', pretending to
2495 # support xhtml+xml but choking when it gets what it asked for.
2496 if (defined $cgi->http('HTTP_ACCEPT') &&
2497 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
2498 $cgi->Accept('application/xhtml+xml') != 0) {
2499 $content_type = 'application/xhtml+xml';
2500 } else {
2501 $content_type = 'text/html';
2502 }
2503 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
2504 -status=> $status, -expires => $expires);
2505 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
2506 print <<EOF;
2507 <?xml version="1.0" encoding="utf-8"?>
2508 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2509 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
2510 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
2511 <!-- git core binaries version $git_version -->
2512 <head>
2513 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
2514 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
2515 <meta name="robots" content="index, nofollow"/>
2516 <title>$title</title>
2517 EOF
2518 # print out each stylesheet that exist
2519 if (defined $stylesheet) {
2520 #provides backwards capability for those people who define style sheet in a config file
2521 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2522 } else {
2523 foreach my $stylesheet (@stylesheets) {
2524 next unless $stylesheet;
2525 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
2526 }
2527 }
2528 if (defined $project) {
2529 my %href_params = get_feed_info();
2530 if (!exists $href_params{'-title'}) {
2531 $href_params{'-title'} = 'log';
2532 }
2533
2534 foreach my $format qw(RSS Atom) {
2535 my $type = lc($format);
2536 my %link_attr = (
2537 '-rel' => 'alternate',
2538 '-title' => "$project - $href_params{'-title'} - $format feed",
2539 '-type' => "application/$type+xml"
2540 );
2541
2542 $href_params{'action'} = $type;
2543 $link_attr{'-href'} = href(%href_params);
2544 print "<link ".
2545 "rel=\"$link_attr{'-rel'}\" ".
2546 "title=\"$link_attr{'-title'}\" ".
2547 "href=\"$link_attr{'-href'}\" ".
2548 "type=\"$link_attr{'-type'}\" ".
2549 "/>\n";
2550
2551 $href_params{'extra_options'} = '--no-merges';
2552 $link_attr{'-href'} = href(%href_params);
2553 $link_attr{'-title'} .= ' (no merges)';
2554 print "<link ".
2555 "rel=\"$link_attr{'-rel'}\" ".
2556 "title=\"$link_attr{'-title'}\" ".
2557 "href=\"$link_attr{'-href'}\" ".
2558 "type=\"$link_attr{'-type'}\" ".
2559 "/>\n";
2560 }
2561
2562 } else {
2563 printf('<link rel="alternate" title="%s projects list" '.
2564 'href="%s" type="text/plain; charset=utf-8" />'."\n",
2565 $site_name, href(project=>undef, action=>"project_index"));
2566 printf('<link rel="alternate" title="%s projects feeds" '.
2567 'href="%s" type="text/x-opml" />'."\n",
2568 $site_name, href(project=>undef, action=>"opml"));
2569 }
2570 if (defined $favicon) {
2571 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
2572 }
2573
2574 print "</head>\n" .
2575 "<body>\n";
2576
2577 if (-f $site_header) {
2578 open (my $fd, $site_header);
2579 print <$fd>;
2580 close $fd;
2581 }
2582
2583 print "<div class=\"page_header\">\n" .
2584 $cgi->a({-href => esc_url($logo_url),
2585 -title => $logo_label},
2586 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
2587 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
2588 if (defined $project) {
2589 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
2590 if (defined $action) {
2591 print " / $action";
2592 }
2593 print "\n";
2594 }
2595 print "</div>\n";
2596
2597 my ($have_search) = gitweb_check_feature('search');
2598 if (defined $project && $have_search) {
2599 if (!defined $searchtext) {
2600 $searchtext = "";
2601 }
2602 my $search_hash;
2603 if (defined $hash_base) {
2604 $search_hash = $hash_base;
2605 } elsif (defined $hash) {
2606 $search_hash = $hash;
2607 } else {
2608 $search_hash = "HEAD";
2609 }
2610 my $action = $my_uri;
2611 my ($use_pathinfo) = gitweb_check_feature('pathinfo');
2612 if ($use_pathinfo) {
2613 $action .= "/".esc_url($project);
2614 }
2615 print $cgi->startform(-method => "get", -action => $action) .
2616 "<div class=\"search\">\n" .
2617 (!$use_pathinfo &&
2618 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
2619 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
2620 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
2621 $cgi->popup_menu(-name => 'st', -default => 'commit',
2622 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
2623 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
2624 " search:\n",
2625 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
2626 "<span title=\"Extended regular expression\">" .
2627 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
2628 -checked => $search_use_regexp) .
2629 "</span>" .
2630 "</div>" .
2631 $cgi->end_form() . "\n";
2632 }
2633 }
2634
2635 sub git_footer_html {
2636 my $feed_class = 'rss_logo';
2637
2638 print "<div class=\"page_footer\">\n";
2639 if (defined $project) {
2640 my $descr = git_get_project_description($project);
2641 if (defined $descr) {
2642 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
2643 }
2644
2645 my %href_params = get_feed_info();
2646 if (!%href_params) {
2647 $feed_class .= ' generic';
2648 }
2649 $href_params{'-title'} ||= 'log';
2650
2651 foreach my $format qw(RSS Atom) {
2652 $href_params{'action'} = lc($format);
2653 print $cgi->a({-href => href(%href_params),
2654 -title => "$href_params{'-title'} $format feed",
2655 -class => $feed_class}, $format)."\n";
2656 }
2657
2658 } else {
2659 print $cgi->a({-href => href(project=>undef, action=>"opml"),
2660 -class => $feed_class}, "OPML") . " ";
2661 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
2662 -class => $feed_class}, "TXT") . "\n";
2663 }
2664 print "</div>\n"; # class="page_footer"
2665
2666 if (-f $site_footer) {
2667 open (my $fd, $site_footer);
2668 print <$fd>;
2669 close $fd;
2670 }
2671
2672 print "</body>\n" .
2673 "</html>";
2674 }
2675
2676 # die_error(<http_status_code>, <error_message>)
2677 # Example: die_error(404, 'Hash not found')
2678 # By convention, use the following status codes (as defined in RFC 2616):
2679 # 400: Invalid or missing CGI parameters, or
2680 # requested object exists but has wrong type.
2681 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
2682 # this server or project.
2683 # 404: Requested object/revision/project doesn't exist.
2684 # 500: The server isn't configured properly, or
2685 # an internal error occurred (e.g. failed assertions caused by bugs), or
2686 # an unknown error occurred (e.g. the git binary died unexpectedly).
2687 sub die_error {
2688 my $status = shift || 500;
2689 my $error = shift || "Internal server error";
2690
2691 my %http_responses = (400 => '400 Bad Request',
2692 403 => '403 Forbidden',
2693 404 => '404 Not Found',
2694 500 => '500 Internal Server Error');
2695 git_header_html($http_responses{$status});
2696 print <<EOF;
2697 <div class="page_body">
2698 <br /><br />
2699 $status - $error
2700 <br />
2701 </div>
2702 EOF
2703 git_footer_html();
2704 exit;
2705 }
2706
2707 ## ----------------------------------------------------------------------
2708 ## functions printing or outputting HTML: navigation
2709
2710 sub git_print_page_nav {
2711 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
2712 $extra = '' if !defined $extra; # pager or formats
2713
2714 my @navs = qw(summary shortlog log commit commitdiff tree);
2715 if ($suppress) {
2716 @navs = grep { $_ ne $suppress } @navs;
2717 }
2718
2719 my %arg = map { $_ => {action=>$_} } @navs;
2720 if (defined $head) {
2721 for (qw(commit commitdiff)) {
2722 $arg{$_}{'hash'} = $head;
2723 }
2724 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
2725 for (qw(shortlog log)) {
2726 $arg{$_}{'hash'} = $head;
2727 }
2728 }
2729 }
2730 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
2731 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
2732
2733 print "<div class=\"page_nav\">\n" .
2734 (join " | ",
2735 map { $_ eq $current ?
2736 $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_")
2737 } @navs);
2738 print "<br/>\n$extra<br/>\n" .
2739 "</div>\n";
2740 }
2741
2742 sub format_paging_nav {
2743 my ($action, $hash, $head, $page, $has_next_link) = @_;
2744 my $paging_nav;
2745
2746
2747 if ($hash ne $head || $page) {
2748 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
2749 } else {
2750 $paging_nav .= "HEAD";
2751 }
2752
2753 if ($page > 0) {
2754 $paging_nav .= " &sdot; " .
2755 $cgi->a({-href => href(-replay=>1, page=>$page-1),
2756 -accesskey => "p", -title => "Alt-p"}, "prev");
2757 } else {
2758 $paging_nav .= " &sdot; prev";
2759 }
2760
2761 if ($has_next_link) {
2762 $paging_nav .= " &sdot; " .
2763 $cgi->a({-href => href(-replay=>1, page=>$page+1),
2764 -accesskey => "n", -title => "Alt-n"}, "next");
2765 } else {
2766 $paging_nav .= " &sdot; next";
2767 }
2768
2769 return $paging_nav;
2770 }
2771
2772 ## ......................................................................
2773 ## functions printing or outputting HTML: div
2774
2775 sub git_print_header_div {
2776 my ($action, $title, $hash, $hash_base) = @_;
2777 my %args = ();
2778
2779 $args{'action'} = $action;
2780 $args{'hash'} = $hash if $hash;
2781 $args{'hash_base'} = $hash_base if $hash_base;
2782
2783 print "<div class=\"header\">\n" .
2784 $cgi->a({-href => href(%args), -class => "title"},
2785 $title ? $title : $action) .
2786 "\n</div>\n";
2787 }
2788
2789 #sub git_print_authorship (\%) {
2790 sub git_print_authorship {
2791 my $co = shift;
2792
2793 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
2794 print "<div class=\"author_date\">" .
2795 esc_html($co->{'author_name'}) .
2796 " [$ad{'rfc2822'}";
2797 if ($ad{'hour_local'} < 6) {
2798 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
2799 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2800 } else {
2801 printf(" (%02d:%02d %s)",
2802 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
2803 }
2804 print "]</div>\n";
2805 }
2806
2807 sub git_print_page_path {
2808 my $name = shift;
2809 my $type = shift;
2810 my $hb = shift;
2811
2812
2813 print "<div class=\"page_path\">";
2814 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
2815 -title => 'tree root'}, to_utf8("[$project]"));
2816 print " / ";
2817 if (defined $name) {
2818 my @dirname = split '/', $name;
2819 my $basename = pop @dirname;
2820 my $fullname = '';
2821
2822 foreach my $dir (@dirname) {
2823 $fullname .= ($fullname ? '/' : '') . $dir;
2824 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
2825 hash_base=>$hb),
2826 -title => $fullname}, esc_path($dir));
2827 print " / ";
2828 }
2829 if (defined $type && $type eq 'blob') {
2830 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
2831 hash_base=>$hb),
2832 -title => $name}, esc_path($basename));
2833 } elsif (defined $type && $type eq 'tree') {
2834 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
2835 hash_base=>$hb),
2836 -title => $name}, esc_path($basename));
2837 print " / ";
2838 } else {
2839 print esc_path($basename);
2840 }
2841 }
2842 print "<br/></div>\n";
2843 }
2844
2845 # sub git_print_log (\@;%) {
2846 sub git_print_log ($;%) {
2847 my $log = shift;
2848 my %opts = @_;
2849
2850 if ($opts{'-remove_title'}) {
2851 # remove title, i.e. first line of log
2852 shift @$log;
2853 }
2854 # remove leading empty lines
2855 while (defined $log->[0] && $log->[0] eq "") {
2856 shift @$log;
2857 }
2858
2859 # print log
2860 my $signoff = 0;
2861 my $empty = 0;
2862 foreach my $line (@$log) {
2863 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
2864 $signoff = 1;
2865 $empty = 0;
2866 if (! $opts{'-remove_signoff'}) {
2867 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
2868 next;
2869 } else {
2870 # remove signoff lines
2871 next;
2872 }
2873 } else {
2874 $signoff = 0;
2875 }
2876
2877 # print only one empty line
2878 # do not print empty line after signoff
2879 if ($line eq "") {
2880 next if ($empty || $signoff);
2881 $empty = 1;
2882 } else {
2883 $empty = 0;
2884 }
2885
2886 print format_log_line_html($line) . "<br/>\n";
2887 }
2888
2889 if ($opts{'-final_empty_line'}) {
2890 # end with single empty line
2891 print "<br/>\n" unless $empty;
2892 }
2893 }
2894
2895 # return link target (what link points to)
2896 sub git_get_link_target {
2897 my $hash = shift;
2898 my $link_target;
2899
2900 # read link
2901 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
2902 or return;
2903 {
2904 local $/;
2905 $link_target = <$fd>;
2906 }
2907 close $fd
2908 or return;
2909
2910 return $link_target;
2911 }
2912
2913 # given link target, and the directory (basedir) the link is in,
2914 # return target of link relative to top directory (top tree);
2915 # return undef if it is not possible (including absolute links).
2916 sub normalize_link_target {
2917 my ($link_target, $basedir, $hash_base) = @_;
2918
2919 # we can normalize symlink target only if $hash_base is provided
2920 return unless $hash_base;
2921
2922 # absolute symlinks (beginning with '/') cannot be normalized
2923 return if (substr($link_target, 0, 1) eq '/');
2924
2925 # normalize link target to path from top (root) tree (dir)
2926 my $path;
2927 if ($basedir) {
2928 $path = $basedir . '/' . $link_target;
2929 } else {
2930 # we are in top (root) tree (dir)
2931 $path = $link_target;
2932 }
2933
2934 # remove //, /./, and /../
2935 my @path_parts;
2936 foreach my $part (split('/', $path)) {
2937 # discard '.' and ''
2938 next if (!$part || $part eq '.');
2939 # handle '..'
2940 if ($part eq '..') {
2941 if (@path_parts) {
2942 pop @path_parts;
2943 } else {
2944 # link leads outside repository (outside top dir)
2945 return;
2946 }
2947 } else {
2948 push @path_parts, $part;
2949 }
2950 }
2951 $path = join('/', @path_parts);
2952
2953 return $path;
2954 }
2955
2956 # print tree entry (row of git_tree), but without encompassing <tr> element
2957 sub git_print_tree_entry {
2958 my ($t, $basedir, $hash_base, $have_blame) = @_;
2959
2960 my %base_key = ();
2961 $base_key{'hash_base'} = $hash_base if defined $hash_base;
2962
2963 # The format of a table row is: mode list link. Where mode is
2964 # the mode of the entry, list is the name of the entry, an href,
2965 # and link is the action links of the entry.
2966
2967 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
2968 if ($t->{'type'} eq "blob") {
2969 print "<td class=\"list\">" .
2970 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2971 file_name=>"$basedir$t->{'name'}", %base_key),
2972 -class => "list"}, esc_path($t->{'name'}));
2973 if (S_ISLNK(oct $t->{'mode'})) {
2974 my $link_target = git_get_link_target($t->{'hash'});
2975 if ($link_target) {
2976 my $norm_target = normalize_link_target($link_target, $basedir, $hash_base);
2977 if (defined $norm_target) {
2978 print " -> " .
2979 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
2980 file_name=>$norm_target),
2981 -title => $norm_target}, esc_path($link_target));
2982 } else {
2983 print " -> " . esc_path($link_target);
2984 }
2985 }
2986 }
2987 print "</td>\n";
2988 print "<td class=\"link\">";
2989 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
2990 file_name=>"$basedir$t->{'name'}", %base_key)},
2991 "blob");
2992 if ($have_blame) {
2993 print " | " .
2994 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
2995 file_name=>"$basedir$t->{'name'}", %base_key)},
2996 "blame");
2997 }
2998 if (defined $hash_base) {
2999 print " | " .
3000 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3001 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3002 "history");
3003 }
3004 print " | " .
3005 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3006 file_name=>"$basedir$t->{'name'}")},
3007 "raw");
3008 print "</td>\n";
3009
3010 } elsif ($t->{'type'} eq "tree") {
3011 print "<td class=\"list\">";
3012 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3013 file_name=>"$basedir$t->{'name'}", %base_key)},
3014 esc_path($t->{'name'}));
3015 print "</td>\n";
3016 print "<td class=\"link\">";
3017 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3018 file_name=>"$basedir$t->{'name'}", %base_key)},
3019 "tree");
3020 if (defined $hash_base) {
3021 print " | " .
3022 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3023 file_name=>"$basedir$t->{'name'}")},
3024 "history");
3025 }
3026 print "</td>\n";
3027 } else {
3028 # unknown object: we can only present history for it
3029 # (this includes 'commit' object, i.e. submodule support)
3030 print "<td class=\"list\">" .
3031 esc_path($t->{'name'}) .
3032 "</td>\n";
3033 print "<td class=\"link\">";
3034 if (defined $hash_base) {
3035 print $cgi->a({-href => href(action=>"history",
3036 hash_base=>$hash_base,
3037 file_name=>"$basedir$t->{'name'}")},
3038 "history");
3039 }
3040 print "</td>\n";
3041 }
3042 }
3043
3044 ## ......................................................................
3045 ## functions printing large fragments of HTML
3046
3047 # get pre-image filenames for merge (combined) diff
3048 sub fill_from_file_info {
3049 my ($diff, @parents) = @_;
3050
3051 $diff->{'from_file'} = [ ];
3052 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3053 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3054 if ($diff->{'status'}[$i] eq 'R' ||
3055 $diff->{'status'}[$i] eq 'C') {
3056 $diff->{'from_file'}[$i] =
3057 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3058 }
3059 }
3060
3061 return $diff;
3062 }
3063
3064 # is current raw difftree line of file deletion
3065 sub is_deleted {
3066 my $diffinfo = shift;
3067
3068 return $diffinfo->{'to_id'} eq ('0' x 40);
3069 }
3070
3071 # does patch correspond to [previous] difftree raw line
3072 # $diffinfo - hashref of parsed raw diff format
3073 # $patchinfo - hashref of parsed patch diff format
3074 # (the same keys as in $diffinfo)
3075 sub is_patch_split {
3076 my ($diffinfo, $patchinfo) = @_;
3077
3078 return defined $diffinfo && defined $patchinfo
3079 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3080 }
3081
3082
3083 sub git_difftree_body {
3084 my ($difftree, $hash, @parents) = @_;
3085 my ($parent) = $parents[0];
3086 my ($have_blame) = gitweb_check_feature('blame');
3087 print "<div class=\"list_head\">\n";
3088 if ($#{$difftree} > 10) {
3089 print(($#{$difftree} + 1) . " files changed:\n");
3090 }
3091 print "</div>\n";
3092
3093 print "<table class=\"" .
3094 (@parents > 1 ? "combined " : "") .
3095 "diff_tree\">\n";
3096
3097 # header only for combined diff in 'commitdiff' view
3098 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3099 if ($has_header) {
3100 # table header
3101 print "<thead><tr>\n" .
3102 "<th></th><th></th>\n"; # filename, patchN link
3103 for (my $i = 0; $i < @parents; $i++) {
3104 my $par = $parents[$i];
3105 print "<th>" .
3106 $cgi->a({-href => href(action=>"commitdiff",
3107 hash=>$hash, hash_parent=>$par),
3108 -title => 'commitdiff to parent number ' .
3109 ($i+1) . ': ' . substr($par,0,7)},
3110 $i+1) .
3111 "&nbsp;</th>\n";
3112 }
3113 print "</tr></thead>\n<tbody>\n";
3114 }
3115
3116 my $alternate = 1;
3117 my $patchno = 0;
3118 foreach my $line (@{$difftree}) {
3119 my $diff = parsed_difftree_line($line);
3120
3121 if ($alternate) {
3122 print "<tr class=\"dark\">\n";
3123 } else {
3124 print "<tr class=\"light\">\n";
3125 }
3126 $alternate ^= 1;
3127
3128 if (exists $diff->{'nparents'}) { # combined diff
3129
3130 fill_from_file_info($diff, @parents)
3131 unless exists $diff->{'from_file'};
3132
3133 if (!is_deleted($diff)) {
3134 # file exists in the result (child) commit
3135 print "<td>" .
3136 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3137 file_name=>$diff->{'to_file'},
3138 hash_base=>$hash),
3139 -class => "list"}, esc_path($diff->{'to_file'})) .
3140 "</td>\n";
3141 } else {
3142 print "<td>" .
3143 esc_path($diff->{'to_file'}) .
3144 "</td>\n";
3145 }
3146
3147 if ($action eq 'commitdiff') {
3148 # link to patch
3149 $patchno++;
3150 print "<td class=\"link\">" .
3151 $cgi->a({-href => "#patch$patchno"}, "patch") .
3152 " | " .
3153 "</td>\n";
3154 }
3155
3156 my $has_history = 0;
3157 my $not_deleted = 0;
3158 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3159 my $hash_parent = $parents[$i];
3160 my $from_hash = $diff->{'from_id'}[$i];
3161 my $from_path = $diff->{'from_file'}[$i];
3162 my $status = $diff->{'status'}[$i];
3163
3164 $has_history ||= ($status ne 'A');
3165 $not_deleted ||= ($status ne 'D');
3166
3167 if ($status eq 'A') {
3168 print "<td class=\"link\" align=\"right\"> | </td>\n";
3169 } elsif ($status eq 'D') {
3170 print "<td class=\"link\">" .
3171 $cgi->a({-href => href(action=>"blob",
3172 hash_base=>$hash,
3173 hash=>$from_hash,
3174 file_name=>$from_path)},
3175 "blob" . ($i+1)) .
3176 " | </td>\n";
3177 } else {
3178 if ($diff->{'to_id'} eq $from_hash) {
3179 print "<td class=\"link nochange\">";
3180 } else {
3181 print "<td class=\"link\">";
3182 }
3183 print $cgi->a({-href => href(action=>"blobdiff",
3184 hash=>$diff->{'to_id'},
3185 hash_parent=>$from_hash,
3186 hash_base=>$hash,
3187 hash_parent_base=>$hash_parent,
3188 file_name=>$diff->{'to_file'},
3189 file_parent=>$from_path)},
3190 "diff" . ($i+1)) .
3191 " | </td>\n";
3192 }
3193 }
3194
3195 print "<td class=\"link\">";
3196 if ($not_deleted) {
3197 print $cgi->a({-href => href(action=>"blob",
3198 hash=>$diff->{'to_id'},
3199 file_name=>$diff->{'to_file'},
3200 hash_base=>$hash)},
3201 "blob");
3202 print " | " if ($has_history);
3203 }
3204 if ($has_history) {
3205 print $cgi->a({-href => href(action=>"history",
3206 file_name=>$diff->{'to_file'},
3207 hash_base=>$hash)},
3208 "history");
3209 }
3210 print "</td>\n";
3211
3212 print "</tr>\n";
3213 next; # instead of 'else' clause, to avoid extra indent
3214 }
3215 # else ordinary diff
3216
3217 my ($to_mode_oct, $to_mode_str, $to_file_type);
3218 my ($from_mode_oct, $from_mode_str, $from_file_type);
3219 if ($diff->{'to_mode'} ne ('0' x 6)) {
3220 $to_mode_oct = oct $diff->{'to_mode'};
3221 if (S_ISREG($to_mode_oct)) { # only for regular file
3222 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3223 }
3224 $to_file_type = file_type($diff->{'to_mode'});
3225 }
3226 if ($diff->{'from_mode'} ne ('0' x 6)) {
3227 $from_mode_oct = oct $diff->{'from_mode'};
3228 if (S_ISREG($to_mode_oct)) { # only for regular file
3229 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3230 }
3231 $from_file_type = file_type($diff->{'from_mode'});
3232 }
3233
3234 if ($diff->{'status'} eq "A") { # created
3235 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3236 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3237 $mode_chng .= "]</span>";
3238 print "<td>";
3239 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3240 hash_base=>$hash, file_name=>$diff->{'file'}),
3241 -class => "list"}, esc_path($diff->{'file'}));
3242 print "</td>\n";
3243 print "<td>$mode_chng</td>\n";
3244 print "<td class=\"link\">";
3245 if ($action eq 'commitdiff') {
3246 # link to patch
3247 $patchno++;
3248 print $cgi->a({-href => "#patch$patchno"}, "patch");
3249 print " | ";
3250 }
3251 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3252 hash_base=>$hash, file_name=>$diff->{'file'})},
3253 "blob");
3254 print "</td>\n";
3255
3256 } elsif ($diff->{'status'} eq "D") { # deleted
3257 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3258 print "<td>";
3259 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3260 hash_base=>$parent, file_name=>$diff->{'file'}),
3261 -class => "list"}, esc_path($diff->{'file'}));
3262 print "</td>\n";
3263 print "<td>$mode_chng</td>\n";
3264 print "<td class=\"link\">";
3265 if ($action eq 'commitdiff') {
3266 # link to patch
3267 $patchno++;
3268 print $cgi->a({-href => "#patch$patchno"}, "patch");
3269 print " | ";
3270 }
3271 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3272 hash_base=>$parent, file_name=>$diff->{'file'})},
3273 "blob") . " | ";
3274 if ($have_blame) {
3275 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3276 file_name=>$diff->{'file'})},
3277 "blame") . " | ";
3278 }
3279 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3280 file_name=>$diff->{'file'})},
3281 "history");
3282 print "</td>\n";
3283
3284 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3285 my $mode_chnge = "";
3286 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3287 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3288 if ($from_file_type ne $to_file_type) {
3289 $mode_chnge .= " from $from_file_type to $to_file_type";
3290 }
3291 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3292 if ($from_mode_str && $to_mode_str) {
3293 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3294 } elsif ($to_mode_str) {
3295 $mode_chnge .= " mode: $to_mode_str";
3296 }
3297 }
3298 $mode_chnge .= "]</span>\n";
3299 }
3300 print "<td>";
3301 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3302 hash_base=>$hash, file_name=>$diff->{'file'}),
3303 -class => "list"}, esc_path($diff->{'file'}));
3304 print "</td>\n";
3305 print "<td>$mode_chnge</td>\n";
3306 print "<td class=\"link\">";
3307 if ($action eq 'commitdiff') {
3308 # link to patch
3309 $patchno++;
3310 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3311 " | ";
3312 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3313 # "commit" view and modified file (not onlu mode changed)
3314 print $cgi->a({-href => href(action=>"blobdiff",
3315 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3316 hash_base=>$hash, hash_parent_base=>$parent,
3317 file_name=>$diff->{'file'})},
3318 "diff") .
3319 " | ";
3320 }
3321 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3322 hash_base=>$hash, file_name=>$diff->{'file'})},
3323 "blob") . " | ";
3324 if ($have_blame) {
3325 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3326 file_name=>$diff->{'file'})},
3327 "blame") . " | ";
3328 }
3329 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3330 file_name=>$diff->{'file'})},
3331 "history");
3332 print "</td>\n";
3333
3334 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
3335 my %status_name = ('R' => 'moved', 'C' => 'copied');
3336 my $nstatus = $status_name{$diff->{'status'}};
3337 my $mode_chng = "";
3338 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3339 # mode also for directories, so we cannot use $to_mode_str
3340 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
3341 }
3342 print "<td>" .
3343 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
3344 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
3345 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
3346 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
3347 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
3348 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
3349 -class => "list"}, esc_path($diff->{'from_file'})) .
3350 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
3351 "<td class=\"link\">";
3352 if ($action eq 'commitdiff') {
3353 # link to patch
3354 $patchno++;
3355 print $cgi->a({-href => "#patch$patchno"}, "patch") .
3356 " | ";
3357 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
3358 # "commit" view and modified file (not only pure rename or copy)
3359 print $cgi->a({-href => href(action=>"blobdiff",
3360 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
3361 hash_base=>$hash, hash_parent_base=>$parent,
3362 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
3363 "diff") .
3364 " | ";
3365 }
3366 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3367 hash_base=>$parent, file_name=>$diff->{'to_file'})},
3368 "blob") . " | ";
3369 if ($have_blame) {
3370 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
3371 file_name=>$diff->{'to_file'})},
3372 "blame") . " | ";
3373 }
3374 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
3375 file_name=>$diff->{'to_file'})},
3376 "history");
3377 print "</td>\n";
3378
3379 } # we should not encounter Unmerged (U) or Unknown (X) status
3380 print "</tr>\n";
3381 }
3382 print "</tbody>" if $has_header;
3383 print "</table>\n";
3384 }
3385
3386 sub git_patchset_body {
3387 my ($fd, $difftree, $hash, @hash_parents) = @_;
3388 my ($hash_parent) = $hash_parents[0];
3389
3390 my $is_combined = (@hash_parents > 1);
3391 my $patch_idx = 0;
3392 my $patch_number = 0;
3393 my $patch_line;
3394 my $diffinfo;
3395 my $to_name;
3396 my (%from, %to);
3397
3398 print "<div class=\"patchset\">\n";
3399
3400 # skip to first patch
3401 while ($patch_line = <$fd>) {
3402 chomp $patch_line;
3403
3404 last if ($patch_line =~ m/^diff /);
3405 }
3406
3407 PATCH:
3408 while ($patch_line) {
3409
3410 # parse "git diff" header line
3411 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
3412 # $1 is from_name, which we do not use
3413 $to_name = unquote($2);
3414 $to_name =~ s!^b/!!;
3415 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
3416 # $1 is 'cc' or 'combined', which we do not use
3417 $to_name = unquote($2);
3418 } else {
3419 $to_name = undef;
3420 }
3421
3422 # check if current patch belong to current raw line
3423 # and parse raw git-diff line if needed
3424 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
3425 # this is continuation of a split patch
3426 print "<div class=\"patch cont\">\n";
3427 } else {
3428 # advance raw git-diff output if needed
3429 $patch_idx++ if defined $diffinfo;
3430
3431 # read and prepare patch information
3432 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3433
3434 # compact combined diff output can have some patches skipped
3435 # find which patch (using pathname of result) we are at now;
3436 if ($is_combined) {
3437 while ($to_name ne $diffinfo->{'to_file'}) {
3438 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3439 format_diff_cc_simplified($diffinfo, @hash_parents) .
3440 "</div>\n"; # class="patch"
3441
3442 $patch_idx++;
3443 $patch_number++;
3444
3445 last if $patch_idx > $#$difftree;
3446 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3447 }
3448 }
3449
3450 # modifies %from, %to hashes
3451 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
3452
3453 # this is first patch for raw difftree line with $patch_idx index
3454 # we index @$difftree array from 0, but number patches from 1
3455 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
3456 }
3457
3458 # git diff header
3459 #assert($patch_line =~ m/^diff /) if DEBUG;
3460 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
3461 $patch_number++;
3462 # print "git diff" header
3463 print format_git_diff_header_line($patch_line, $diffinfo,
3464 \%from, \%to);
3465
3466 # print extended diff header
3467 print "<div class=\"diff extended_header\">\n";
3468 EXTENDED_HEADER:
3469 while ($patch_line = <$fd>) {
3470 chomp $patch_line;
3471
3472 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
3473
3474 print format_extended_diff_header_line($patch_line, $diffinfo,
3475 \%from, \%to);
3476 }
3477 print "</div>\n"; # class="diff extended_header"
3478
3479 # from-file/to-file diff header
3480 if (! $patch_line) {
3481 print "</div>\n"; # class="patch"
3482 last PATCH;
3483 }
3484 next PATCH if ($patch_line =~ m/^diff /);
3485 #assert($patch_line =~ m/^---/) if DEBUG;
3486
3487 my $last_patch_line = $patch_line;
3488 $patch_line = <$fd>;
3489 chomp $patch_line;
3490 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
3491
3492 print format_diff_from_to_header($last_patch_line, $patch_line,
3493 $diffinfo, \%from, \%to,
3494 @hash_parents);
3495
3496 # the patch itself
3497 LINE:
3498 while ($patch_line = <$fd>) {
3499 chomp $patch_line;
3500
3501 next PATCH if ($patch_line =~ m/^diff /);
3502
3503 print format_diff_line($patch_line, \%from, \%to);
3504 }
3505
3506 } continue {
3507 print "</div>\n"; # class="patch"
3508 }
3509
3510 # for compact combined (--cc) format, with chunk and patch simpliciaction
3511 # patchset might be empty, but there might be unprocessed raw lines
3512 for (++$patch_idx if $patch_number > 0;
3513 $patch_idx < @$difftree;
3514 ++$patch_idx) {
3515 # read and prepare patch information
3516 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
3517
3518 # generate anchor for "patch" links in difftree / whatchanged part
3519 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
3520 format_diff_cc_simplified($diffinfo, @hash_parents) .
3521 "</div>\n"; # class="patch"
3522
3523 $patch_number++;
3524 }
3525
3526 if ($patch_number == 0) {
3527 if (@hash_parents > 1) {
3528 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
3529 } else {
3530 print "<div class=\"diff nodifferences\">No differences found</div>\n";
3531 }
3532 }
3533
3534 print "</div>\n"; # class="patchset"
3535 }
3536
3537 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3538
3539 # fills project list info (age, description, owner, forks) for each
3540 # project in the list, removing invalid projects from returned list
3541 # NOTE: modifies $projlist, but does not remove entries from it
3542 sub fill_project_list_info {
3543 my ($projlist, $check_forks) = @_;
3544 my @projects;
3545
3546 PROJECT:
3547 foreach my $pr (@$projlist) {
3548 my (@activity) = git_get_last_activity($pr->{'path'});
3549 unless (@activity) {
3550 next PROJECT;
3551 }
3552 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
3553 if (!defined $pr->{'descr'}) {
3554 my $descr = git_get_project_description($pr->{'path'}) || "";
3555 $descr = to_utf8($descr);
3556 $pr->{'descr_long'} = $descr;
3557 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
3558 }
3559 if (!defined $pr->{'owner'}) {
3560 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
3561 }
3562 if ($check_forks) {
3563 my $pname = $pr->{'path'};
3564 if (($pname =~ s/\.git$//) &&
3565 ($pname !~ /\/$/) &&
3566 (-d "$projectroot/$pname")) {
3567 $pr->{'forks'} = "-d $projectroot/$pname";
3568 } else {
3569 $pr->{'forks'} = 0;
3570 }
3571 }
3572 push @projects, $pr;
3573 }
3574
3575 return @projects;
3576 }
3577
3578 # print 'sort by' <th> element, either sorting by $key if $name eq $order
3579 # (changing $list), or generating 'sort by $name' replay link otherwise
3580 sub print_sort_th {
3581 my ($str_sort, $name, $order, $key, $header, $list) = @_;
3582 $key ||= $name;
3583 $header ||= ucfirst($name);
3584
3585 if ($order eq $name) {
3586 if ($str_sort) {
3587 @$list = sort {$a->{$key} cmp $b->{$key}} @$list;
3588 } else {
3589 @$list = sort {$a->{$key} <=> $b->{$key}} @$list;
3590 }
3591 print "<th>$header</th>\n";
3592 } else {
3593 print "<th>" .
3594 $cgi->a({-href => href(-replay=>1, order=>$name),
3595 -class => "header"}, $header) .
3596 "</th>\n";
3597 }
3598 }
3599
3600 sub print_sort_th_str {
3601 print_sort_th(1, @_);
3602 }
3603
3604 sub print_sort_th_num {
3605 print_sort_th(0, @_);
3606 }
3607
3608 sub git_project_list_body {
3609 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
3610
3611 my ($check_forks) = gitweb_check_feature('forks');
3612 my @projects = fill_project_list_info($projlist, $check_forks);
3613
3614 $order ||= $default_projects_order;
3615 $from = 0 unless defined $from;
3616 $to = $#projects if (!defined $to || $#projects < $to);
3617
3618 print "<table class=\"project_list\">\n";
3619 unless ($no_header) {
3620 print "<tr>\n";
3621 if ($check_forks) {
3622 print "<th></th>\n";
3623 }
3624 print_sort_th_str('project', $order, 'path',
3625 'Project', \@projects);
3626 print_sort_th_str('descr', $order, 'descr_long',
3627 'Description', \@projects);
3628 print_sort_th_str('owner', $order, 'owner',
3629 'Owner', \@projects);
3630 print_sort_th_num('age', $order, 'age',
3631 'Last Change', \@projects);
3632 print "<th></th>\n" . # for links
3633 "</tr>\n";
3634 }
3635 my $alternate = 1;
3636 for (my $i = $from; $i <= $to; $i++) {
3637 my $pr = $projects[$i];
3638 if ($alternate) {
3639 print "<tr class=\"dark\">\n";
3640 } else {
3641 print "<tr class=\"light\">\n";
3642 }
3643 $alternate ^= 1;
3644 if ($check_forks) {
3645 print "<td>";
3646 if ($pr->{'forks'}) {
3647 print "<!-- $pr->{'forks'} -->\n";
3648 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
3649 }
3650 print "</td>\n";
3651 }
3652 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3653 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
3654 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
3655 -class => "list", -title => $pr->{'descr_long'}},
3656 esc_html($pr->{'descr'})) . "</td>\n" .
3657 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
3658 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
3659 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
3660 "<td class=\"link\">" .
3661 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
3662 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
3663 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
3664 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
3665 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
3666 "</td>\n" .
3667 "</tr>\n";
3668 }
3669 if (defined $extra) {
3670 print "<tr>\n";
3671 if ($check_forks) {
3672 print "<td></td>\n";
3673 }
3674 print "<td colspan=\"5\">$extra</td>\n" .
3675 "</tr>\n";
3676 }
3677 print "</table>\n";
3678 }
3679
3680 sub git_shortlog_body {
3681 # uses global variable $project
3682 my ($commitlist, $from, $to, $refs, $extra) = @_;
3683
3684 $from = 0 unless defined $from;
3685 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3686
3687 print "<table class=\"shortlog\">\n";
3688 my $alternate = 1;
3689 for (my $i = $from; $i <= $to; $i++) {
3690 my %co = %{$commitlist->[$i]};
3691 my $commit = $co{'id'};
3692 my $ref = format_ref_marker($refs, $commit);
3693 if ($alternate) {
3694 print "<tr class=\"dark\">\n";
3695 } else {
3696 print "<tr class=\"light\">\n";
3697 }
3698 $alternate ^= 1;
3699 my $author = chop_and_escape_str($co{'author_name'}, 10);
3700 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
3701 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3702 "<td><i>" . $author . "</i></td>\n" .
3703 "<td>";
3704 print format_subject_html($co{'title'}, $co{'title_short'},
3705 href(action=>"commit", hash=>$commit), $ref);
3706 print "</td>\n" .
3707 "<td class=\"link\">" .
3708 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
3709 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
3710 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
3711 my $snapshot_links = format_snapshot_links($commit);
3712 if (defined $snapshot_links) {
3713 print " | " . $snapshot_links;
3714 }
3715 print "</td>\n" .
3716 "</tr>\n";
3717 }
3718 if (defined $extra) {
3719 print "<tr>\n" .
3720 "<td colspan=\"4\">$extra</td>\n" .
3721 "</tr>\n";
3722 }
3723 print "</table>\n";
3724 }
3725
3726 sub git_history_body {
3727 # Warning: assumes constant type (blob or tree) during history
3728 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
3729
3730 $from = 0 unless defined $from;
3731 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
3732
3733 print "<table class=\"history\">\n";
3734 my $alternate = 1;
3735 for (my $i = $from; $i <= $to; $i++) {
3736 my %co = %{$commitlist->[$i]};
3737 if (!%co) {
3738 next;
3739 }
3740 my $commit = $co{'id'};
3741
3742 my $ref = format_ref_marker($refs, $commit);
3743
3744 if ($alternate) {
3745 print "<tr class=\"dark\">\n";
3746 } else {
3747 print "<tr class=\"light\">\n";
3748 }
3749 $alternate ^= 1;
3750 # shortlog uses chop_str($co{'author_name'}, 10)
3751 my $author = chop_and_escape_str($co{'author_name'}, 15, 3);
3752 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3753 "<td><i>" . $author . "</i></td>\n" .
3754 "<td>";
3755 # originally git_history used chop_str($co{'title'}, 50)
3756 print format_subject_html($co{'title'}, $co{'title_short'},
3757 href(action=>"commit", hash=>$commit), $ref);
3758 print "</td>\n" .
3759 "<td class=\"link\">" .
3760 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
3761 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
3762
3763 if ($ftype eq 'blob') {
3764 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
3765 my $blob_parent = git_get_hash_by_path($commit, $file_name);
3766 if (defined $blob_current && defined $blob_parent &&
3767 $blob_current ne $blob_parent) {
3768 print " | " .
3769 $cgi->a({-href => href(action=>"blobdiff",
3770 hash=>$blob_current, hash_parent=>$blob_parent,
3771 hash_base=>$hash_base, hash_parent_base=>$commit,
3772 file_name=>$file_name)},
3773 "diff to current");
3774 }
3775 }
3776 print "</td>\n" .
3777 "</tr>\n";
3778 }
3779 if (defined $extra) {
3780 print "<tr>\n" .
3781 "<td colspan=\"4\">$extra</td>\n" .
3782 "</tr>\n";
3783 }
3784 print "</table>\n";
3785 }
3786
3787 sub git_tags_body {
3788 # uses global variable $project
3789 my ($taglist, $from, $to, $extra) = @_;
3790 $from = 0 unless defined $from;
3791 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
3792
3793 print "<table class=\"tags\">\n";
3794 my $alternate = 1;
3795 for (my $i = $from; $i <= $to; $i++) {
3796 my $entry = $taglist->[$i];
3797 my %tag = %$entry;
3798 my $comment = $tag{'subject'};
3799 my $comment_short;
3800 if (defined $comment) {
3801 $comment_short = chop_str($comment, 30, 5);
3802 }
3803 if ($alternate) {
3804 print "<tr class=\"dark\">\n";
3805 } else {
3806 print "<tr class=\"light\">\n";
3807 }
3808 $alternate ^= 1;
3809 if (defined $tag{'age'}) {
3810 print "<td><i>$tag{'age'}</i></td>\n";
3811 } else {
3812 print "<td></td>\n";
3813 }
3814 print "<td>" .
3815 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
3816 -class => "list name"}, esc_html($tag{'name'})) .
3817 "</td>\n" .
3818 "<td>";
3819 if (defined $comment) {
3820 print format_subject_html($comment, $comment_short,
3821 href(action=>"tag", hash=>$tag{'id'}));
3822 }
3823 print "</td>\n" .
3824 "<td class=\"selflink\">";
3825 if ($tag{'type'} eq "tag") {
3826 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
3827 } else {
3828 print "&nbsp;";
3829 }
3830 print "</td>\n" .
3831 "<td class=\"link\">" . " | " .
3832 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
3833 if ($tag{'reftype'} eq "commit") {
3834 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
3835 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
3836 } elsif ($tag{'reftype'} eq "blob") {
3837 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
3838 }
3839 print "</td>\n" .
3840 "</tr>";
3841 }
3842 if (defined $extra) {
3843 print "<tr>\n" .
3844 "<td colspan=\"5\">$extra</td>\n" .
3845 "</tr>\n";
3846 }
3847 print "</table>\n";
3848 }
3849
3850 sub git_heads_body {
3851 # uses global variable $project
3852 my ($headlist, $head, $from, $to, $extra) = @_;
3853 $from = 0 unless defined $from;
3854 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
3855
3856 print "<table class=\"heads\">\n";
3857 my $alternate = 1;
3858 for (my $i = $from; $i <= $to; $i++) {
3859 my $entry = $headlist->[$i];
3860 my %ref = %$entry;
3861 my $curr = $ref{'id'} eq $head;
3862 if ($alternate) {
3863 print "<tr class=\"dark\">\n";
3864 } else {
3865 print "<tr class=\"light\">\n";
3866 }
3867 $alternate ^= 1;
3868 print "<td><i>$ref{'age'}</i></td>\n" .
3869 ($curr ? "<td class=\"current_head\">" : "<td>") .
3870 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
3871 -class => "list name"},esc_html($ref{'name'})) .
3872 "</td>\n" .
3873 "<td class=\"link\">" .
3874 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
3875 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
3876 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
3877 "</td>\n" .
3878 "</tr>";
3879 }
3880 if (defined $extra) {
3881 print "<tr>\n" .
3882 "<td colspan=\"3\">$extra</td>\n" .
3883 "</tr>\n";
3884 }
3885 print "</table>\n";
3886 }
3887
3888 sub git_search_grep_body {
3889 my ($commitlist, $from, $to, $extra) = @_;
3890 $from = 0 unless defined $from;
3891 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
3892
3893 print "<table class=\"commit_search\">\n";
3894 my $alternate = 1;
3895 for (my $i = $from; $i <= $to; $i++) {
3896 my %co = %{$commitlist->[$i]};
3897 if (!%co) {
3898 next;
3899 }
3900 my $commit = $co{'id'};
3901 if ($alternate) {
3902 print "<tr class=\"dark\">\n";
3903 } else {
3904 print "<tr class=\"light\">\n";
3905 }
3906 $alternate ^= 1;
3907 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
3908 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
3909 "<td><i>" . $author . "</i></td>\n" .
3910 "<td>" .
3911 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
3912 -class => "list subject"},
3913 chop_and_escape_str($co{'title'}, 50) . "<br/>");
3914 my $comment = $co{'comment'};
3915 foreach my $line (@$comment) {
3916 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
3917 my ($lead, $match, $trail) = ($1, $2, $3);
3918 $match = chop_str($match, 70, 5, 'center');
3919 my $contextlen = int((80 - length($match))/2);
3920 $contextlen = 30 if ($contextlen > 30);
3921 $lead = chop_str($lead, $contextlen, 10, 'left');
3922 $trail = chop_str($trail, $contextlen, 10, 'right');
3923
3924 $lead = esc_html($lead);
3925 $match = esc_html($match);
3926 $trail = esc_html($trail);
3927
3928 print "$lead<span class=\"match\">$match</span>$trail<br />";
3929 }
3930 }
3931 print "</td>\n" .
3932 "<td class=\"link\">" .
3933 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
3934 " | " .
3935 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
3936 " | " .
3937 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
3938 print "</td>\n" .
3939 "</tr>\n";
3940 }
3941 if (defined $extra) {
3942 print "<tr>\n" .
3943 "<td colspan=\"3\">$extra</td>\n" .
3944 "</tr>\n";
3945 }
3946 print "</table>\n";
3947 }
3948
3949 ## ======================================================================
3950 ## ======================================================================
3951 ## actions
3952
3953 sub git_project_list {
3954 my $order = $cgi->param('o');
3955 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3956 die_error(400, "Unknown order parameter");
3957 }
3958
3959 my @list = git_get_projects_list();
3960 if (!@list) {
3961 die_error(404, "No projects found");
3962 }
3963
3964 git_header_html();
3965 if (-f $home_text) {
3966 print "<div class=\"index_include\">\n";
3967 open (my $fd, $home_text);
3968 print <$fd>;
3969 close $fd;
3970 print "</div>\n";
3971 }
3972 git_project_list_body(\@list, $order);
3973 git_footer_html();
3974 }
3975
3976 sub git_forks {
3977 my $order = $cgi->param('o');
3978 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
3979 die_error(400, "Unknown order parameter");
3980 }
3981
3982 my @list = git_get_projects_list($project);
3983 if (!@list) {
3984 die_error(404, "No forks found");
3985 }
3986
3987 git_header_html();
3988 git_print_page_nav('','');
3989 git_print_header_div('summary', "$project forks");
3990 git_project_list_body(\@list, $order);
3991 git_footer_html();
3992 }
3993
3994 sub git_project_index {
3995 my @projects = git_get_projects_list($project);
3996
3997 print $cgi->header(
3998 -type => 'text/plain',
3999 -charset => 'utf-8',
4000 -content_disposition => 'inline; filename="index.aux"');
4001
4002 foreach my $pr (@projects) {
4003 if (!exists $pr->{'owner'}) {
4004 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4005 }
4006
4007 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4008 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4009 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4010 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4011 $path =~ s/ /\+/g;
4012 $owner =~ s/ /\+/g;
4013
4014 print "$path $owner\n";
4015 }
4016 }
4017
4018 sub git_summary {
4019 my $descr = git_get_project_description($project) || "none";
4020 my %co = parse_commit("HEAD");
4021 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4022 my $head = $co{'id'};
4023
4024 my $owner = git_get_project_owner($project);
4025
4026 my $refs = git_get_references();
4027 # These get_*_list functions return one more to allow us to see if
4028 # there are more ...
4029 my @taglist = git_get_tags_list(16);
4030 my @headlist = git_get_heads_list(16);
4031 my @forklist;
4032 my ($check_forks) = gitweb_check_feature('forks');
4033
4034 if ($check_forks) {
4035 @forklist = git_get_projects_list($project);
4036 }
4037
4038 git_header_html();
4039 git_print_page_nav('summary','', $head);
4040
4041 print "<div class=\"title\">&nbsp;</div>\n";
4042 print "<table class=\"projects_list\">\n" .
4043 "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4044 "<tr><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4045 if (defined $cd{'rfc2822'}) {
4046 print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4047 }
4048
4049 # use per project git URL list in $projectroot/$project/cloneurl
4050 # or make project git URL from git base URL and project name
4051 my $url_tag = "URL";
4052 my @url_list = git_get_project_url_list($project);
4053 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4054 foreach my $git_url (@url_list) {
4055 next unless $git_url;
4056 print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n";
4057 $url_tag = "";
4058 }
4059 print "</table>\n";
4060
4061 if (-s "$projectroot/$project/README.html") {
4062 if (open my $fd, "$projectroot/$project/README.html") {
4063 print "<div class=\"title\">readme</div>\n" .
4064 "<div class=\"readme\">\n";
4065 print $_ while (<$fd>);
4066 print "\n</div>\n"; # class="readme"
4067 close $fd;
4068 }
4069 }
4070
4071 # we need to request one more than 16 (0..15) to check if
4072 # those 16 are all
4073 my @commitlist = $head ? parse_commits($head, 17) : ();
4074 if (@commitlist) {
4075 git_print_header_div('shortlog');
4076 git_shortlog_body(\@commitlist, 0, 15, $refs,
4077 $#commitlist <= 15 ? undef :
4078 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4079 }
4080
4081 if (@taglist) {
4082 git_print_header_div('tags');
4083 git_tags_body(\@taglist, 0, 15,
4084 $#taglist <= 15 ? undef :
4085 $cgi->a({-href => href(action=>"tags")}, "..."));
4086 }
4087
4088 if (@headlist) {
4089 git_print_header_div('heads');
4090 git_heads_body(\@headlist, $head, 0, 15,
4091 $#headlist <= 15 ? undef :
4092 $cgi->a({-href => href(action=>"heads")}, "..."));
4093 }
4094
4095 if (@forklist) {
4096 git_print_header_div('forks');
4097 git_project_list_body(\@forklist, undef, 0, 15,
4098 $#forklist <= 15 ? undef :
4099 $cgi->a({-href => href(action=>"forks")}, "..."),
4100 'noheader');
4101 }
4102
4103 git_footer_html();
4104 }
4105
4106 sub git_tag {
4107 my $head = git_get_head_hash($project);
4108 git_header_html();
4109 git_print_page_nav('','', $head,undef,$head);
4110 my %tag = parse_tag($hash);
4111
4112 if (! %tag) {
4113 die_error(404, "Unknown tag object");
4114 }
4115
4116 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4117 print "<div class=\"title_text\">\n" .
4118 "<table class=\"object_header\">\n" .
4119 "<tr>\n" .
4120 "<td>object</td>\n" .
4121 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4122 $tag{'object'}) . "</td>\n" .
4123 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4124 $tag{'type'}) . "</td>\n" .
4125 "</tr>\n";
4126 if (defined($tag{'author'})) {
4127 my %ad = parse_date($tag{'epoch'}, $tag{'tz'});
4128 print "<tr><td>author</td><td>" . esc_html($tag{'author'}) . "</td></tr>\n";
4129 print "<tr><td></td><td>" . $ad{'rfc2822'} .
4130 sprintf(" (%02d:%02d %s)", $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'}) .
4131 "</td></tr>\n";
4132 }
4133 print "</table>\n\n" .
4134 "</div>\n";
4135 print "<div class=\"page_body\">";
4136 my $comment = $tag{'comment'};
4137 foreach my $line (@$comment) {
4138 chomp $line;
4139 print esc_html($line, -nbsp=>1) . "<br/>\n";
4140 }
4141 print "</div>\n";
4142 git_footer_html();
4143 }
4144
4145 sub git_blame {
4146 my $fd;
4147 my $ftype;
4148
4149 gitweb_check_feature('blame')
4150 or die_error(403, "Blame view not allowed");
4151
4152 die_error(400, "No file name given") unless $file_name;
4153 $hash_base ||= git_get_head_hash($project);
4154 die_error(404, "Couldn't find base commit") unless ($hash_base);
4155 my %co = parse_commit($hash_base)
4156 or die_error(404, "Commit not found");
4157 if (!defined $hash) {
4158 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4159 or die_error(404, "Error looking up file");
4160 }
4161 $ftype = git_get_type($hash);
4162 if ($ftype !~ "blob") {
4163 die_error(400, "Object is not a blob");
4164 }
4165 open ($fd, "-|", git_cmd(), "blame", '-p', '--',
4166 $file_name, $hash_base)
4167 or die_error(500, "Open git-blame failed");
4168 git_header_html();
4169 my $formats_nav =
4170 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4171 "blob") .
4172 " | " .
4173 $cgi->a({-href => href(action=>"history", -replay=>1)},
4174 "history") .
4175 " | " .
4176 $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
4177 "HEAD");
4178 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4179 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4180 git_print_page_path($file_name, $ftype, $hash_base);
4181 my @rev_color = (qw(light2 dark2));
4182 my $num_colors = scalar(@rev_color);
4183 my $current_color = 0;
4184 my $last_rev;
4185 print <<HTML;
4186 <div class="page_body">
4187 <table class="blame">
4188 <tr><th>Commit</th><th>Line</th><th>Data</th></tr>
4189 HTML
4190 my %metainfo = ();
4191 while (1) {
4192 $_ = <$fd>;
4193 last unless defined $_;
4194 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4195 /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/;
4196 if (!exists $metainfo{$full_rev}) {
4197 $metainfo{$full_rev} = {};
4198 }
4199 my $meta = $metainfo{$full_rev};
4200 while (<$fd>) {
4201 last if (s/^\t//);
4202 if (/^(\S+) (.*)$/) {
4203 $meta->{$1} = $2;
4204 }
4205 }
4206 my $data = $_;
4207 chomp $data;
4208 my $rev = substr($full_rev, 0, 8);
4209 my $author = $meta->{'author'};
4210 my %date = parse_date($meta->{'author-time'},
4211 $meta->{'author-tz'});
4212 my $date = $date{'iso-tz'};
4213 if ($group_size) {
4214 $current_color = ++$current_color % $num_colors;
4215 }
4216 print "<tr class=\"$rev_color[$current_color]\">\n";
4217 if ($group_size) {
4218 print "<td class=\"sha1\"";
4219 print " title=\"". esc_html($author) . ", $date\"";
4220 print " rowspan=\"$group_size\"" if ($group_size > 1);
4221 print ">";
4222 print $cgi->a({-href => href(action=>"commit",
4223 hash=>$full_rev,
4224 file_name=>$file_name)},
4225 esc_html($rev));
4226 print "</td>\n";
4227 }
4228 open (my $dd, "-|", git_cmd(), "rev-parse", "$full_rev^")
4229 or die_error(500, "Open git-rev-parse failed");
4230 my $parent_commit = <$dd>;
4231 close $dd;
4232 chomp($parent_commit);
4233 my $blamed = href(action => 'blame',
4234 file_name => $meta->{'filename'},
4235 hash_base => $parent_commit);
4236 print "<td class=\"linenr\">";
4237 print $cgi->a({ -href => "$blamed#l$orig_lineno",
4238 -id => "l$lineno",
4239 -class => "linenr" },
4240 esc_html($lineno));
4241 print "</td>";
4242 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
4243 print "</tr>\n";
4244 }
4245 print "</table>\n";
4246 print "</div>";
4247 close $fd
4248 or print "Reading blob failed\n";
4249 git_footer_html();
4250 }
4251
4252 sub git_tags {
4253 my $head = git_get_head_hash($project);
4254 git_header_html();
4255 git_print_page_nav('','', $head,undef,$head);
4256 git_print_header_div('summary', $project);
4257
4258 my @tagslist = git_get_tags_list();
4259 if (@tagslist) {
4260 git_tags_body(\@tagslist);
4261 }
4262 git_footer_html();
4263 }
4264
4265 sub git_heads {
4266 my $head = git_get_head_hash($project);
4267 git_header_html();
4268 git_print_page_nav('','', $head,undef,$head);
4269 git_print_header_div('summary', $project);
4270
4271 my @headslist = git_get_heads_list();
4272 if (@headslist) {
4273 git_heads_body(\@headslist, $head);
4274 }
4275 git_footer_html();
4276 }
4277
4278 sub git_blob_plain {
4279 my $type = shift;
4280 my $expires;
4281
4282 if (!defined $hash) {
4283 if (defined $file_name) {
4284 my $base = $hash_base || git_get_head_hash($project);
4285 $hash = git_get_hash_by_path($base, $file_name, "blob")
4286 or die_error(404, "Cannot find file");
4287 } else {
4288 die_error(400, "No file name defined");
4289 }
4290 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4291 # blobs defined by non-textual hash id's can be cached
4292 $expires = "+1d";
4293 }
4294
4295 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4296 or die_error(500, "Open git-cat-file blob '$hash' failed");
4297
4298 # content-type (can include charset)
4299 $type = blob_contenttype($fd, $file_name, $type);
4300
4301 # "save as" filename, even when no $file_name is given
4302 my $save_as = "$hash";
4303 if (defined $file_name) {
4304 $save_as = $file_name;
4305 } elsif ($type =~ m/^text\//) {
4306 $save_as .= '.txt';
4307 }
4308
4309 print $cgi->header(
4310 -type => $type,
4311 -expires => $expires,
4312 -content_disposition => 'inline; filename="' . $save_as . '"');
4313 undef $/;
4314 binmode STDOUT, ':raw';
4315 print <$fd>;
4316 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4317 $/ = "\n";
4318 close $fd;
4319 }
4320
4321 sub git_blob {
4322 my $expires;
4323
4324 if (!defined $hash) {
4325 if (defined $file_name) {
4326 my $base = $hash_base || git_get_head_hash($project);
4327 $hash = git_get_hash_by_path($base, $file_name, "blob")
4328 or die_error(404, "Cannot find file");
4329 } else {
4330 die_error(400, "No file name defined");
4331 }
4332 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4333 # blobs defined by non-textual hash id's can be cached
4334 $expires = "+1d";
4335 }
4336
4337 my ($have_blame) = gitweb_check_feature('blame');
4338 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4339 or die_error(500, "Couldn't cat $file_name, $hash");
4340 my $mimetype = blob_mimetype($fd, $file_name);
4341 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
4342 close $fd;
4343 return git_blob_plain($mimetype);
4344 }
4345 # we can have blame only for text/* mimetype
4346 $have_blame &&= ($mimetype =~ m!^text/!);
4347
4348 git_header_html(undef, $expires);
4349 my $formats_nav = '';
4350 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4351 if (defined $file_name) {
4352 if ($have_blame) {
4353 $formats_nav .=
4354 $cgi->a({-href => href(action=>"blame", -replay=>1)},
4355 "blame") .
4356 " | ";
4357 }
4358 $formats_nav .=
4359 $cgi->a({-href => href(action=>"history", -replay=>1)},
4360 "history") .
4361 " | " .
4362 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4363 "raw") .
4364 " | " .
4365 $cgi->a({-href => href(action=>"blob",
4366 hash_base=>"HEAD", file_name=>$file_name)},
4367 "HEAD");
4368 } else {
4369 $formats_nav .=
4370 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
4371 "raw");
4372 }
4373 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4374 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4375 } else {
4376 print "<div class=\"page_nav\">\n" .
4377 "<br/><br/></div>\n" .
4378 "<div class=\"title\">$hash</div>\n";
4379 }
4380 git_print_page_path($file_name, "blob", $hash_base);
4381 print "<div class=\"page_body\">\n";
4382 if ($mimetype =~ m!^image/!) {
4383 print qq!<img type="$mimetype"!;
4384 if ($file_name) {
4385 print qq! alt="$file_name" title="$file_name"!;
4386 }
4387 print qq! src="! .
4388 href(action=>"blob_plain", hash=>$hash,
4389 hash_base=>$hash_base, file_name=>$file_name) .
4390 qq!" />\n!;
4391 } else {
4392 my $nr;
4393 while (my $line = <$fd>) {
4394 chomp $line;
4395 $nr++;
4396 $line = untabify($line);
4397 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
4398 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
4399 }
4400 }
4401 close $fd
4402 or print "Reading blob failed.\n";
4403 print "</div>";
4404 git_footer_html();
4405 }
4406
4407 sub git_tree {
4408 if (!defined $hash_base) {
4409 $hash_base = "HEAD";
4410 }
4411 if (!defined $hash) {
4412 if (defined $file_name) {
4413 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
4414 } else {
4415 $hash = $hash_base;
4416 }
4417 }
4418 $/ = "\0";
4419 open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash
4420 or die_error(500, "Open git-ls-tree failed");
4421 my @entries = map { chomp; $_ } <$fd>;
4422 close $fd or die_error(404, "Reading tree failed");
4423 $/ = "\n";
4424
4425 my $refs = git_get_references();
4426 my $ref = format_ref_marker($refs, $hash_base);
4427 git_header_html();
4428 my $basedir = '';
4429 my ($have_blame) = gitweb_check_feature('blame');
4430 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4431 my @views_nav = ();
4432 if (defined $file_name) {
4433 push @views_nav,
4434 $cgi->a({-href => href(action=>"history", -replay=>1)},
4435 "history"),
4436 $cgi->a({-href => href(action=>"tree",
4437 hash_base=>"HEAD", file_name=>$file_name)},
4438 "HEAD"),
4439 }
4440 my $snapshot_links = format_snapshot_links($hash);
4441 if (defined $snapshot_links) {
4442 # FIXME: Should be available when we have no hash base as well.
4443 push @views_nav, $snapshot_links;
4444 }
4445 git_print_page_nav('tree','', $hash_base, undef, undef, join(' | ', @views_nav));
4446 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
4447 } else {
4448 undef $hash_base;
4449 print "<div class=\"page_nav\">\n";
4450 print "<br/><br/></div>\n";
4451 print "<div class=\"title\">$hash</div>\n";
4452 }
4453 if (defined $file_name) {
4454 $basedir = $file_name;
4455 if ($basedir ne '' && substr($basedir, -1) ne '/') {
4456 $basedir .= '/';
4457 }
4458 }
4459 git_print_page_path($file_name, 'tree', $hash_base);
4460 print "<div class=\"page_body\">\n";
4461 print "<table class=\"tree\">\n";
4462 my $alternate = 1;
4463 # '..' (top directory) link if possible
4464 if (defined $hash_base &&
4465 defined $file_name && $file_name =~ m![^/]+$!) {
4466 if ($alternate) {
4467 print "<tr class=\"dark\">\n";
4468 } else {
4469 print "<tr class=\"light\">\n";
4470 }
4471 $alternate ^= 1;
4472
4473 my $up = $file_name;
4474 $up =~ s!/?[^/]+$!!;
4475 undef $up unless $up;
4476 # based on git_print_tree_entry
4477 print '<td class="mode">' . mode_str('040000') . "</td>\n";
4478 print '<td class="list">';
4479 print $cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,
4480 file_name=>$up)},
4481 "..");
4482 print "</td>\n";
4483 print "<td class=\"link\"></td>\n";
4484
4485 print "</tr>\n";
4486 }
4487 foreach my $line (@entries) {
4488 my %t = parse_ls_tree_line($line, -z => 1);
4489
4490 if ($alternate) {
4491 print "<tr class=\"dark\">\n";
4492 } else {
4493 print "<tr class=\"light\">\n";
4494 }
4495 $alternate ^= 1;
4496
4497 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
4498
4499 print "</tr>\n";
4500 }
4501 print "</table>\n" .
4502 "</div>";
4503 git_footer_html();
4504 }
4505
4506 sub git_snapshot {
4507 my @supported_fmts = gitweb_check_feature('snapshot');
4508 @supported_fmts = filter_snapshot_fmts(@supported_fmts);
4509
4510 my $format = $cgi->param('sf');
4511 if (!@supported_fmts) {
4512 die_error(403, "Snapshots not allowed");
4513 }
4514 # default to first supported snapshot format
4515 $format ||= $supported_fmts[0];
4516 if ($format !~ m/^[a-z0-9]+$/) {
4517 die_error(400, "Invalid snapshot format parameter");
4518 } elsif (!exists($known_snapshot_formats{$format})) {
4519 die_error(400, "Unknown snapshot format");
4520 } elsif (!grep($_ eq $format, @supported_fmts)) {
4521 die_error(403, "Unsupported snapshot format");
4522 }
4523
4524 if (!defined $hash) {
4525 $hash = git_get_head_hash($project);
4526 }
4527
4528 my $name = $project;
4529 $name =~ s,([^/])/*\.git$,$1,;
4530 $name = basename($name);
4531 my $filename = to_utf8($name);
4532 $name =~ s/\047/\047\\\047\047/g;
4533 my $cmd;
4534 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
4535 $cmd = quote_command(
4536 git_cmd(), 'archive',
4537 "--format=$known_snapshot_formats{$format}{'format'}",
4538 "--prefix=$name/", $hash);
4539 if (exists $known_snapshot_formats{$format}{'compressor'}) {
4540 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
4541 }
4542
4543 print $cgi->header(
4544 -type => $known_snapshot_formats{$format}{'type'},
4545 -content_disposition => 'inline; filename="' . "$filename" . '"',
4546 -status => '200 OK');
4547
4548 open my $fd, "-|", $cmd
4549 or die_error(500, "Execute git-archive failed");
4550 binmode STDOUT, ':raw';
4551 print <$fd>;
4552 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
4553 close $fd;
4554 }
4555
4556 sub git_log {
4557 my $head = git_get_head_hash($project);
4558 if (!defined $hash) {
4559 $hash = $head;
4560 }
4561 if (!defined $page) {
4562 $page = 0;
4563 }
4564 my $refs = git_get_references();
4565
4566 my @commitlist = parse_commits($hash, 101, (100 * $page));
4567
4568 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
4569
4570 git_header_html();
4571 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
4572
4573 if (!@commitlist) {
4574 my %co = parse_commit($hash);
4575
4576 git_print_header_div('summary', $project);
4577 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
4578 }
4579 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
4580 for (my $i = 0; $i <= $to; $i++) {
4581 my %co = %{$commitlist[$i]};
4582 next if !%co;
4583 my $commit = $co{'id'};
4584 my $ref = format_ref_marker($refs, $commit);
4585 my %ad = parse_date($co{'author_epoch'});
4586 git_print_header_div('commit',
4587 "<span class=\"age\">$co{'age_string'}</span>" .
4588 esc_html($co{'title'}) . $ref,
4589 $commit);
4590 print "<div class=\"title_text\">\n" .
4591 "<div class=\"log_link\">\n" .
4592 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
4593 " | " .
4594 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
4595 " | " .
4596 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
4597 "<br/>\n" .
4598 "</div>\n" .
4599 "<i>" . esc_html($co{'author_name'}) . " [$ad{'rfc2822'}]</i><br/>\n" .
4600 "</div>\n";
4601
4602 print "<div class=\"log_body\">\n";
4603 git_print_log($co{'comment'}, -final_empty_line=> 1);
4604 print "</div>\n";
4605 }
4606 if ($#commitlist >= 100) {
4607 print "<div class=\"page_nav\">\n";
4608 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
4609 -accesskey => "n", -title => "Alt-n"}, "next");
4610 print "</div>\n";
4611 }
4612 git_footer_html();
4613 }
4614
4615 sub git_commit {
4616 $hash ||= $hash_base || "HEAD";
4617 my %co = parse_commit($hash)
4618 or die_error(404, "Unknown commit object");
4619 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
4620 my %cd = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
4621
4622 my $parent = $co{'parent'};
4623 my $parents = $co{'parents'}; # listref
4624
4625 # we need to prepare $formats_nav before any parameter munging
4626 my $formats_nav;
4627 if (!defined $parent) {
4628 # --root commitdiff
4629 $formats_nav .= '(initial)';
4630 } elsif (@$parents == 1) {
4631 # single parent commit
4632 $formats_nav .=
4633 '(parent: ' .
4634 $cgi->a({-href => href(action=>"commit",
4635 hash=>$parent)},
4636 esc_html(substr($parent, 0, 7))) .
4637 ')';
4638 } else {
4639 # merge commit
4640 $formats_nav .=
4641 '(merge: ' .
4642 join(' ', map {
4643 $cgi->a({-href => href(action=>"commit",
4644 hash=>$_)},
4645 esc_html(substr($_, 0, 7)));
4646 } @$parents ) .
4647 ')';
4648 }
4649
4650 if (!defined $parent) {
4651 $parent = "--root";
4652 }
4653 my @difftree;
4654 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
4655 @diff_opts,
4656 (@$parents <= 1 ? $parent : '-c'),
4657 $hash, "--"
4658 or die_error(500, "Open git-diff-tree failed");
4659 @difftree = map { chomp; $_ } <$fd>;
4660 close $fd or die_error(404, "Reading git-diff-tree failed");
4661
4662 # non-textual hash id's can be cached
4663 my $expires;
4664 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
4665 $expires = "+1d";
4666 }
4667 my $refs = git_get_references();
4668 my $ref = format_ref_marker($refs, $co{'id'});
4669
4670 git_header_html(undef, $expires);
4671 git_print_page_nav('commit', '',
4672 $hash, $co{'tree'}, $hash,
4673 $formats_nav);
4674
4675 if (defined $co{'parent'}) {
4676 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
4677 } else {
4678 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
4679 }
4680 print "<div class=\"title_text\">\n" .
4681 "<table class=\"object_header\">\n";
4682 print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
4683 "<tr>" .
4684 "<td></td><td> $ad{'rfc2822'}";
4685 if ($ad{'hour_local'} < 6) {
4686 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
4687 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4688 } else {
4689 printf(" (%02d:%02d %s)",
4690 $ad{'hour_local'}, $ad{'minute_local'}, $ad{'tz_local'});
4691 }
4692 print "</td>" .
4693 "</tr>\n";
4694 print "<tr><td>committer</td><td>" . esc_html($co{'committer'}) . "</td></tr>\n";
4695 print "<tr><td></td><td> $cd{'rfc2822'}" .
4696 sprintf(" (%02d:%02d %s)", $cd{'hour_local'}, $cd{'minute_local'}, $cd{'tz_local'}) .
4697 "</td></tr>\n";
4698 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
4699 print "<tr>" .
4700 "<td>tree</td>" .
4701 "<td class=\"sha1\">" .
4702 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
4703 class => "list"}, $co{'tree'}) .
4704 "</td>" .
4705 "<td class=\"link\">" .
4706 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
4707 "tree");
4708 my $snapshot_links = format_snapshot_links($hash);
4709 if (defined $snapshot_links) {
4710 print " | " . $snapshot_links;
4711 }
4712 print "</td>" .
4713 "</tr>\n";
4714
4715 foreach my $par (@$parents) {
4716 print "<tr>" .
4717 "<td>parent</td>" .
4718 "<td class=\"sha1\">" .
4719 $cgi->a({-href => href(action=>"commit", hash=>$par),
4720 class => "list"}, $par) .
4721 "</td>" .
4722 "<td class=\"link\">" .
4723 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
4724 " | " .
4725 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
4726 "</td>" .
4727 "</tr>\n";
4728 }
4729 print "</table>".
4730 "</div>\n";
4731
4732 print "<div class=\"page_body\">\n";
4733 git_print_log($co{'comment'});
4734 print "</div>\n";
4735
4736 git_difftree_body(\@difftree, $hash, @$parents);
4737
4738 git_footer_html();
4739 }
4740
4741 sub git_object {
4742 # object is defined by:
4743 # - hash or hash_base alone
4744 # - hash_base and file_name
4745 my $type;
4746
4747 # - hash or hash_base alone
4748 if ($hash || ($hash_base && !defined $file_name)) {
4749 my $object_id = $hash || $hash_base;
4750
4751 open my $fd, "-|", quote_command(
4752 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
4753 or die_error(404, "Object does not exist");
4754 $type = <$fd>;
4755 chomp $type;
4756 close $fd
4757 or die_error(404, "Object does not exist");
4758
4759 # - hash_base and file_name
4760 } elsif ($hash_base && defined $file_name) {
4761 $file_name =~ s,/+$,,;
4762
4763 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
4764 or die_error(404, "Base object does not exist");
4765
4766 # here errors should not hapen
4767 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
4768 or die_error(500, "Open git-ls-tree failed");
4769 my $line = <$fd>;
4770 close $fd;
4771
4772 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
4773 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
4774 die_error(404, "File or directory for given base does not exist");
4775 }
4776 $type = $2;
4777 $hash = $3;
4778 } else {
4779 die_error(400, "Not enough information to find object");
4780 }
4781
4782 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
4783 hash=>$hash, hash_base=>$hash_base,
4784 file_name=>$file_name),
4785 -status => '302 Found');
4786 }
4787
4788 sub git_blobdiff {
4789 my $format = shift || 'html';
4790
4791 my $fd;
4792 my @difftree;
4793 my %diffinfo;
4794 my $expires;
4795
4796 # preparing $fd and %diffinfo for git_patchset_body
4797 # new style URI
4798 if (defined $hash_base && defined $hash_parent_base) {
4799 if (defined $file_name) {
4800 # read raw output
4801 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4802 $hash_parent_base, $hash_base,
4803 "--", (defined $file_parent ? $file_parent : ()), $file_name
4804 or die_error(500, "Open git-diff-tree failed");
4805 @difftree = map { chomp; $_ } <$fd>;
4806 close $fd
4807 or die_error(404, "Reading git-diff-tree failed");
4808 @difftree
4809 or die_error(404, "Blob diff not found");
4810
4811 } elsif (defined $hash &&
4812 $hash =~ /[0-9a-fA-F]{40}/) {
4813 # try to find filename from $hash
4814
4815 # read filtered raw output
4816 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4817 $hash_parent_base, $hash_base, "--"
4818 or die_error(500, "Open git-diff-tree failed");
4819 @difftree =
4820 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
4821 # $hash == to_id
4822 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
4823 map { chomp; $_ } <$fd>;
4824 close $fd
4825 or die_error(404, "Reading git-diff-tree failed");
4826 @difftree
4827 or die_error(404, "Blob diff not found");
4828
4829 } else {
4830 die_error(400, "Missing one of the blob diff parameters");
4831 }
4832
4833 if (@difftree > 1) {
4834 die_error(400, "Ambiguous blob diff specification");
4835 }
4836
4837 %diffinfo = parse_difftree_raw_line($difftree[0]);
4838 $file_parent ||= $diffinfo{'from_file'} || $file_name;
4839 $file_name ||= $diffinfo{'to_file'};
4840
4841 $hash_parent ||= $diffinfo{'from_id'};
4842 $hash ||= $diffinfo{'to_id'};
4843
4844 # non-textual hash id's can be cached
4845 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
4846 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
4847 $expires = '+1d';
4848 }
4849
4850 # open patch output
4851 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
4852 '-p', ($format eq 'html' ? "--full-index" : ()),
4853 $hash_parent_base, $hash_base,
4854 "--", (defined $file_parent ? $file_parent : ()), $file_name
4855 or die_error(500, "Open git-diff-tree failed");
4856 }
4857
4858 # old/legacy style URI
4859 if (!%diffinfo && # if new style URI failed
4860 defined $hash && defined $hash_parent) {
4861 # fake git-diff-tree raw output
4862 $diffinfo{'from_mode'} = $diffinfo{'to_mode'} = "blob";
4863 $diffinfo{'from_id'} = $hash_parent;
4864 $diffinfo{'to_id'} = $hash;
4865 if (defined $file_name) {
4866 if (defined $file_parent) {
4867 $diffinfo{'status'} = '2';
4868 $diffinfo{'from_file'} = $file_parent;
4869 $diffinfo{'to_file'} = $file_name;
4870 } else { # assume not renamed
4871 $diffinfo{'status'} = '1';
4872 $diffinfo{'from_file'} = $file_name;
4873 $diffinfo{'to_file'} = $file_name;
4874 }
4875 } else { # no filename given
4876 $diffinfo{'status'} = '2';
4877 $diffinfo{'from_file'} = $hash_parent;
4878 $diffinfo{'to_file'} = $hash;
4879 }
4880
4881 # non-textual hash id's can be cached
4882 if ($hash =~ m/^[0-9a-fA-F]{40}$/ &&
4883 $hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4884 $expires = '+1d';
4885 }
4886
4887 # open patch output
4888 open $fd, "-|", git_cmd(), "diff", @diff_opts,
4889 '-p', ($format eq 'html' ? "--full-index" : ()),
4890 $hash_parent, $hash, "--"
4891 or die_error(500, "Open git-diff failed");
4892 } else {
4893 die_error(400, "Missing one of the blob diff parameters")
4894 unless %diffinfo;
4895 }
4896
4897 # header
4898 if ($format eq 'html') {
4899 my $formats_nav =
4900 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
4901 "raw");
4902 git_header_html(undef, $expires);
4903 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
4904 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4905 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4906 } else {
4907 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
4908 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
4909 }
4910 if (defined $file_name) {
4911 git_print_page_path($file_name, "blob", $hash_base);
4912 } else {
4913 print "<div class=\"page_path\"></div>\n";
4914 }
4915
4916 } elsif ($format eq 'plain') {
4917 print $cgi->header(
4918 -type => 'text/plain',
4919 -charset => 'utf-8',
4920 -expires => $expires,
4921 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
4922
4923 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
4924
4925 } else {
4926 die_error(400, "Unknown blobdiff format");
4927 }
4928
4929 # patch
4930 if ($format eq 'html') {
4931 print "<div class=\"page_body\">\n";
4932
4933 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
4934 close $fd;
4935
4936 print "</div>\n"; # class="page_body"
4937 git_footer_html();
4938
4939 } else {
4940 while (my $line = <$fd>) {
4941 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
4942 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
4943
4944 print $line;
4945
4946 last if $line =~ m!^\+\+\+!;
4947 }
4948 local $/ = undef;
4949 print <$fd>;
4950 close $fd;
4951 }
4952 }
4953
4954 sub git_blobdiff_plain {
4955 git_blobdiff('plain');
4956 }
4957
4958 sub git_commitdiff {
4959 my $format = shift || 'html';
4960 $hash ||= $hash_base || "HEAD";
4961 my %co = parse_commit($hash)
4962 or die_error(404, "Unknown commit object");
4963
4964 # choose format for commitdiff for merge
4965 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
4966 $hash_parent = '--cc';
4967 }
4968 # we need to prepare $formats_nav before almost any parameter munging
4969 my $formats_nav;
4970 if ($format eq 'html') {
4971 $formats_nav =
4972 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
4973 "raw");
4974
4975 if (defined $hash_parent &&
4976 $hash_parent ne '-c' && $hash_parent ne '--cc') {
4977 # commitdiff with two commits given
4978 my $hash_parent_short = $hash_parent;
4979 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
4980 $hash_parent_short = substr($hash_parent, 0, 7);
4981 }
4982 $formats_nav .=
4983 ' (from';
4984 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
4985 if ($co{'parents'}[$i] eq $hash_parent) {
4986 $formats_nav .= ' parent ' . ($i+1);
4987 last;
4988 }
4989 }
4990 $formats_nav .= ': ' .
4991 $cgi->a({-href => href(action=>"commitdiff",
4992 hash=>$hash_parent)},
4993 esc_html($hash_parent_short)) .
4994 ')';
4995 } elsif (!$co{'parent'}) {
4996 # --root commitdiff
4997 $formats_nav .= ' (initial)';
4998 } elsif (scalar @{$co{'parents'}} == 1) {
4999 # single parent commit
5000 $formats_nav .=
5001 ' (parent: ' .
5002 $cgi->a({-href => href(action=>"commitdiff",
5003 hash=>$co{'parent'})},
5004 esc_html(substr($co{'parent'}, 0, 7))) .
5005 ')';
5006 } else {
5007 # merge commit
5008 if ($hash_parent eq '--cc') {
5009 $formats_nav .= ' | ' .
5010 $cgi->a({-href => href(action=>"commitdiff",
5011 hash=>$hash, hash_parent=>'-c')},
5012 'combined');
5013 } else { # $hash_parent eq '-c'
5014 $formats_nav .= ' | ' .
5015 $cgi->a({-href => href(action=>"commitdiff",
5016 hash=>$hash, hash_parent=>'--cc')},
5017 'compact');
5018 }
5019 $formats_nav .=
5020 ' (merge: ' .
5021 join(' ', map {
5022 $cgi->a({-href => href(action=>"commitdiff",
5023 hash=>$_)},
5024 esc_html(substr($_, 0, 7)));
5025 } @{$co{'parents'}} ) .
5026 ')';
5027 }
5028 }
5029
5030 my $hash_parent_param = $hash_parent;
5031 if (!defined $hash_parent_param) {
5032 # --cc for multiple parents, --root for parentless
5033 $hash_parent_param =
5034 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5035 }
5036
5037 # read commitdiff
5038 my $fd;
5039 my @difftree;
5040 if ($format eq 'html') {
5041 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5042 "--no-commit-id", "--patch-with-raw", "--full-index",
5043 $hash_parent_param, $hash, "--"
5044 or die_error(500, "Open git-diff-tree failed");
5045
5046 while (my $line = <$fd>) {
5047 chomp $line;
5048 # empty line ends raw part of diff-tree output
5049 last unless $line;
5050 push @difftree, scalar parse_difftree_raw_line($line);
5051 }
5052
5053 } elsif ($format eq 'plain') {
5054 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5055 '-p', $hash_parent_param, $hash, "--"
5056 or die_error(500, "Open git-diff-tree failed");
5057
5058 } else {
5059 die_error(400, "Unknown commitdiff format");
5060 }
5061
5062 # non-textual hash id's can be cached
5063 my $expires;
5064 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5065 $expires = "+1d";
5066 }
5067
5068 # write commit message
5069 if ($format eq 'html') {
5070 my $refs = git_get_references();
5071 my $ref = format_ref_marker($refs, $co{'id'});
5072
5073 git_header_html(undef, $expires);
5074 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5075 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5076 git_print_authorship(\%co);
5077 print "<div class=\"page_body\">\n";
5078 if (@{$co{'comment'}} > 1) {
5079 print "<div class=\"log\">\n";
5080 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5081 print "</div>\n"; # class="log"
5082 }
5083
5084 } elsif ($format eq 'plain') {
5085 my $refs = git_get_references("tags");
5086 my $tagname = git_get_rev_name_tags($hash);
5087 my $filename = basename($project) . "-$hash.patch";
5088
5089 print $cgi->header(
5090 -type => 'text/plain',
5091 -charset => 'utf-8',
5092 -expires => $expires,
5093 -content_disposition => 'inline; filename="' . "$filename" . '"');
5094 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5095 print "From: " . to_utf8($co{'author'}) . "\n";
5096 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5097 print "Subject: " . to_utf8($co{'title'}) . "\n";
5098
5099 print "X-Git-Tag: $tagname\n" if $tagname;
5100 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5101
5102 foreach my $line (@{$co{'comment'}}) {
5103 print to_utf8($line) . "\n";
5104 }
5105 print "---\n\n";
5106 }
5107
5108 # write patch
5109 if ($format eq 'html') {
5110 my $use_parents = !defined $hash_parent ||
5111 $hash_parent eq '-c' || $hash_parent eq '--cc';
5112 git_difftree_body(\@difftree, $hash,
5113 $use_parents ? @{$co{'parents'}} : $hash_parent);
5114 print "<br/>\n";
5115
5116 git_patchset_body($fd, \@difftree, $hash,
5117 $use_parents ? @{$co{'parents'}} : $hash_parent);
5118 close $fd;
5119 print "</div>\n"; # class="page_body"
5120 git_footer_html();
5121
5122 } elsif ($format eq 'plain') {
5123 local $/ = undef;
5124 print <$fd>;
5125 close $fd
5126 or print "Reading git-diff-tree failed\n";
5127 }
5128 }
5129
5130 sub git_commitdiff_plain {
5131 git_commitdiff('plain');
5132 }
5133
5134 sub git_history {
5135 if (!defined $hash_base) {
5136 $hash_base = git_get_head_hash($project);
5137 }
5138 if (!defined $page) {
5139 $page = 0;
5140 }
5141 my $ftype;
5142 my %co = parse_commit($hash_base)
5143 or die_error(404, "Unknown commit object");
5144
5145 my $refs = git_get_references();
5146 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
5147
5148 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
5149 $file_name, "--full-history")
5150 or die_error(404, "No such file or directory on given branch");
5151
5152 if (!defined $hash && defined $file_name) {
5153 # some commits could have deleted file in question,
5154 # and not have it in tree, but one of them has to have it
5155 for (my $i = 0; $i <= @commitlist; $i++) {
5156 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
5157 last if defined $hash;
5158 }
5159 }
5160 if (defined $hash) {
5161 $ftype = git_get_type($hash);
5162 }
5163 if (!defined $ftype) {
5164 die_error(500, "Unknown type of object");
5165 }
5166
5167 my $paging_nav = '';
5168 if ($page > 0) {
5169 $paging_nav .=
5170 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
5171 file_name=>$file_name)},
5172 "first");
5173 $paging_nav .= " &sdot; " .
5174 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5175 -accesskey => "p", -title => "Alt-p"}, "prev");
5176 } else {
5177 $paging_nav .= "first";
5178 $paging_nav .= " &sdot; prev";
5179 }
5180 my $next_link = '';
5181 if ($#commitlist >= 100) {
5182 $next_link =
5183 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5184 -accesskey => "n", -title => "Alt-n"}, "next");
5185 $paging_nav .= " &sdot; $next_link";
5186 } else {
5187 $paging_nav .= " &sdot; next";
5188 }
5189
5190 git_header_html();
5191 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
5192 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5193 git_print_page_path($file_name, $ftype, $hash_base);
5194
5195 git_history_body(\@commitlist, 0, 99,
5196 $refs, $hash_base, $ftype, $next_link);
5197
5198 git_footer_html();
5199 }
5200
5201 sub git_search {
5202 gitweb_check_feature('search') or die_error(403, "Search is disabled");
5203 if (!defined $searchtext) {
5204 die_error(400, "Text field is empty");
5205 }
5206 if (!defined $hash) {
5207 $hash = git_get_head_hash($project);
5208 }
5209 my %co = parse_commit($hash);
5210 if (!%co) {
5211 die_error(404, "Unknown commit object");
5212 }
5213 if (!defined $page) {
5214 $page = 0;
5215 }
5216
5217 $searchtype ||= 'commit';
5218 if ($searchtype eq 'pickaxe') {
5219 # pickaxe may take all resources of your box and run for several minutes
5220 # with every query - so decide by yourself how public you make this feature
5221 gitweb_check_feature('pickaxe')
5222 or die_error(403, "Pickaxe is disabled");
5223 }
5224 if ($searchtype eq 'grep') {
5225 gitweb_check_feature('grep')
5226 or die_error(403, "Grep is disabled");
5227 }
5228
5229 git_header_html();
5230
5231 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
5232 my $greptype;
5233 if ($searchtype eq 'commit') {
5234 $greptype = "--grep=";
5235 } elsif ($searchtype eq 'author') {
5236 $greptype = "--author=";
5237 } elsif ($searchtype eq 'committer') {
5238 $greptype = "--committer=";
5239 }
5240 $greptype .= $searchtext;
5241 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5242 $greptype, '--regexp-ignore-case',
5243 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5244
5245 my $paging_nav = '';
5246 if ($page > 0) {
5247 $paging_nav .=
5248 $cgi->a({-href => href(action=>"search", hash=>$hash,
5249 searchtext=>$searchtext,
5250 searchtype=>$searchtype)},
5251 "first");
5252 $paging_nav .= " &sdot; " .
5253 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5254 -accesskey => "p", -title => "Alt-p"}, "prev");
5255 } else {
5256 $paging_nav .= "first";
5257 $paging_nav .= " &sdot; prev";
5258 }
5259 my $next_link = '';
5260 if ($#commitlist >= 100) {
5261 $next_link =
5262 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5263 -accesskey => "n", -title => "Alt-n"}, "next");
5264 $paging_nav .= " &sdot; $next_link";
5265 } else {
5266 $paging_nav .= " &sdot; next";
5267 }
5268
5269 if ($#commitlist >= 100) {
5270 }
5271
5272 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5273 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5274 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5275 }
5276
5277 if ($searchtype eq 'pickaxe') {
5278 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5279 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5280
5281 print "<table class=\"pickaxe search\">\n";
5282 my $alternate = 1;
5283 $/ = "\n";
5284 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5285 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5286 ($search_use_regexp ? '--pickaxe-regex' : ());
5287 undef %co;
5288 my @files;
5289 while (my $line = <$fd>) {
5290 chomp $line;
5291 next unless $line;
5292
5293 my %set = parse_difftree_raw_line($line);
5294 if (defined $set{'commit'}) {
5295 # finish previous commit
5296 if (%co) {
5297 print "</td>\n" .
5298 "<td class=\"link\">" .
5299 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5300 " | " .
5301 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5302 print "</td>\n" .
5303 "</tr>\n";
5304 }
5305
5306 if ($alternate) {
5307 print "<tr class=\"dark\">\n";
5308 } else {
5309 print "<tr class=\"light\">\n";
5310 }
5311 $alternate ^= 1;
5312 %co = parse_commit($set{'commit'});
5313 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5314 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5315 "<td><i>$author</i></td>\n" .
5316 "<td>" .
5317 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5318 -class => "list subject"},
5319 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5320 } elsif (defined $set{'to_id'}) {
5321 next if ($set{'to_id'} =~ m/^0{40}$/);
5322
5323 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5324 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5325 -class => "list"},
5326 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5327 "<br/>\n";
5328 }
5329 }
5330 close $fd;
5331
5332 # finish last commit (warning: repetition!)
5333 if (%co) {
5334 print "</td>\n" .
5335 "<td class=\"link\">" .
5336 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5337 " | " .
5338 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5339 print "</td>\n" .
5340 "</tr>\n";
5341 }
5342
5343 print "</table>\n";
5344 }
5345
5346 if ($searchtype eq 'grep') {
5347 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5348 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5349
5350 print "<table class=\"grep_search\">\n";
5351 my $alternate = 1;
5352 my $matches = 0;
5353 $/ = "\n";
5354 open my $fd, "-|", git_cmd(), 'grep', '-n',
5355 $search_use_regexp ? ('-E', '-i') : '-F',
5356 $searchtext, $co{'tree'};
5357 my $lastfile = '';
5358 while (my $line = <$fd>) {
5359 chomp $line;
5360 my ($file, $lno, $ltext, $binary);
5361 last if ($matches++ > 1000);
5362 if ($line =~ /^Binary file (.+) matches$/) {
5363 $file = $1;
5364 $binary = 1;
5365 } else {
5366 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5367 }
5368 if ($file ne $lastfile) {
5369 $lastfile and print "</td></tr>\n";
5370 if ($alternate++) {
5371 print "<tr class=\"dark\">\n";
5372 } else {
5373 print "<tr class=\"light\">\n";
5374 }
5375 print "<td class=\"list\">".
5376 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5377 file_name=>"$file"),
5378 -class => "list"}, esc_path($file));
5379 print "</td><td>\n";
5380 $lastfile = $file;
5381 }
5382 if ($binary) {
5383 print "<div class=\"binary\">Binary file</div>\n";
5384 } else {
5385 $ltext = untabify($ltext);
5386 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5387 $ltext = esc_html($1, -nbsp=>1);
5388 $ltext .= '<span class="match">';
5389 $ltext .= esc_html($2, -nbsp=>1);
5390 $ltext .= '</span>';
5391 $ltext .= esc_html($3, -nbsp=>1);
5392 } else {
5393 $ltext = esc_html($ltext, -nbsp=>1);
5394 }
5395 print "<div class=\"pre\">" .
5396 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5397 file_name=>"$file").'#l'.$lno,
5398 -class => "linenr"}, sprintf('%4i', $lno))
5399 . ' ' . $ltext . "</div>\n";
5400 }
5401 }
5402 if ($lastfile) {
5403 print "</td></tr>\n";
5404 if ($matches > 1000) {
5405 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5406 }
5407 } else {
5408 print "<div class=\"diff nodifferences\">No matches found</div>\n";
5409 }
5410 close $fd;
5411
5412 print "</table>\n";
5413 }
5414 git_footer_html();
5415 }
5416
5417 sub git_search_help {
5418 git_header_html();
5419 git_print_page_nav('','', $hash,$hash,$hash);
5420 print <<EOT;
5421 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
5422 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
5423 the pattern entered is recognized as the POSIX extended
5424 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
5425 insensitive).</p>
5426 <dl>
5427 <dt><b>commit</b></dt>
5428 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
5429 EOT
5430 my ($have_grep) = gitweb_check_feature('grep');
5431 if ($have_grep) {
5432 print <<EOT;
5433 <dt><b>grep</b></dt>
5434 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
5435 a different one) are searched for the given pattern. On large trees, this search can take
5436 a while and put some strain on the server, so please use it with some consideration. Note that
5437 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
5438 case-sensitive.</dd>
5439 EOT
5440 }
5441 print <<EOT;
5442 <dt><b>author</b></dt>
5443 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
5444 <dt><b>committer</b></dt>
5445 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
5446 EOT
5447 my ($have_pickaxe) = gitweb_check_feature('pickaxe');
5448 if ($have_pickaxe) {
5449 print <<EOT;
5450 <dt><b>pickaxe</b></dt>
5451 <dd>All commits that caused the string to appear or disappear from any file (changes that
5452 added, removed or "modified" the string) will be listed. This search can take a while and
5453 takes a lot of strain on the server, so please use it wisely. Note that since you may be
5454 interested even in changes just changing the case as well, this search is case sensitive.</dd>
5455 EOT
5456 }
5457 print "</dl>\n";
5458 git_footer_html();
5459 }
5460
5461 sub git_shortlog {
5462 my $head = git_get_head_hash($project);
5463 if (!defined $hash) {
5464 $hash = $head;
5465 }
5466 if (!defined $page) {
5467 $page = 0;
5468 }
5469 my $refs = git_get_references();
5470
5471 my @commitlist = parse_commits($hash, 101, (100 * $page));
5472
5473 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
5474 my $next_link = '';
5475 if ($#commitlist >= 100) {
5476 $next_link =
5477 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5478 -accesskey => "n", -title => "Alt-n"}, "next");
5479 }
5480
5481 git_header_html();
5482 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
5483 git_print_header_div('summary', $project);
5484
5485 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
5486
5487 git_footer_html();
5488 }
5489
5490 ## ......................................................................
5491 ## feeds (RSS, Atom; OPML)
5492
5493 sub git_feed {
5494 my $format = shift || 'atom';
5495 my ($have_blame) = gitweb_check_feature('blame');
5496
5497 # Atom: http://www.atomenabled.org/developers/syndication/
5498 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
5499 if ($format ne 'rss' && $format ne 'atom') {
5500 die_error(400, "Unknown web feed format");
5501 }
5502
5503 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
5504 my $head = $hash || 'HEAD';
5505 my @commitlist = parse_commits($head, 150, 0, $file_name);
5506
5507 my %latest_commit;
5508 my %latest_date;
5509 my $content_type = "application/$format+xml";
5510 if (defined $cgi->http('HTTP_ACCEPT') &&
5511 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
5512 # browser (feed reader) prefers text/xml
5513 $content_type = 'text/xml';
5514 }
5515 if (defined($commitlist[0])) {
5516 %latest_commit = %{$commitlist[0]};
5517 %latest_date = parse_date($latest_commit{'author_epoch'});
5518 print $cgi->header(
5519 -type => $content_type,
5520 -charset => 'utf-8',
5521 -last_modified => $latest_date{'rfc2822'});
5522 } else {
5523 print $cgi->header(
5524 -type => $content_type,
5525 -charset => 'utf-8');
5526 }
5527
5528 # Optimization: skip generating the body if client asks only
5529 # for Last-Modified date.
5530 return if ($cgi->request_method() eq 'HEAD');
5531
5532 # header variables
5533 my $title = "$site_name - $project/$action";
5534 my $feed_type = 'log';
5535 if (defined $hash) {
5536 $title .= " - '$hash'";
5537 $feed_type = 'branch log';
5538 if (defined $file_name) {
5539 $title .= " :: $file_name";
5540 $feed_type = 'history';
5541 }
5542 } elsif (defined $file_name) {
5543 $title .= " - $file_name";
5544 $feed_type = 'history';
5545 }
5546 $title .= " $feed_type";
5547 my $descr = git_get_project_description($project);
5548 if (defined $descr) {
5549 $descr = esc_html($descr);
5550 } else {
5551 $descr = "$project " .
5552 ($format eq 'rss' ? 'RSS' : 'Atom') .
5553 " feed";
5554 }
5555 my $owner = git_get_project_owner($project);
5556 $owner = esc_html($owner);
5557
5558 #header
5559 my $alt_url;
5560 if (defined $file_name) {
5561 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
5562 } elsif (defined $hash) {
5563 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
5564 } else {
5565 $alt_url = href(-full=>1, action=>"summary");
5566 }
5567 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
5568 if ($format eq 'rss') {
5569 print <<XML;
5570 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
5571 <channel>
5572 XML
5573 print "<title>$title</title>\n" .
5574 "<link>$alt_url</link>\n" .
5575 "<description>$descr</description>\n" .
5576 "<language>en</language>\n";
5577 } elsif ($format eq 'atom') {
5578 print <<XML;
5579 <feed xmlns="http://www.w3.org/2005/Atom">
5580 XML
5581 print "<title>$title</title>\n" .
5582 "<subtitle>$descr</subtitle>\n" .
5583 '<link rel="alternate" type="text/html" href="' .
5584 $alt_url . '" />' . "\n" .
5585 '<link rel="self" type="' . $content_type . '" href="' .
5586 $cgi->self_url() . '" />' . "\n" .
5587 "<id>" . href(-full=>1) . "</id>\n" .
5588 # use project owner for feed author
5589 "<author><name>$owner</name></author>\n";
5590 if (defined $favicon) {
5591 print "<icon>" . esc_url($favicon) . "</icon>\n";
5592 }
5593 if (defined $logo_url) {
5594 # not twice as wide as tall: 72 x 27 pixels
5595 print "<logo>" . esc_url($logo) . "</logo>\n";
5596 }
5597 if (! %latest_date) {
5598 # dummy date to keep the feed valid until commits trickle in:
5599 print "<updated>1970-01-01T00:00:00Z</updated>\n";
5600 } else {
5601 print "<updated>$latest_date{'iso-8601'}</updated>\n";
5602 }
5603 }
5604
5605 # contents
5606 for (my $i = 0; $i <= $#commitlist; $i++) {
5607 my %co = %{$commitlist[$i]};
5608 my $commit = $co{'id'};
5609 # we read 150, we always show 30 and the ones more recent than 48 hours
5610 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
5611 last;
5612 }
5613 my %cd = parse_date($co{'author_epoch'});
5614
5615 # get list of changed files
5616 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5617 $co{'parent'} || "--root",
5618 $co{'id'}, "--", (defined $file_name ? $file_name : ())
5619 or next;
5620 my @difftree = map { chomp; $_ } <$fd>;
5621 close $fd
5622 or next;
5623
5624 # print element (entry, item)
5625 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
5626 if ($format eq 'rss') {
5627 print "<item>\n" .
5628 "<title>" . esc_html($co{'title'}) . "</title>\n" .
5629 "<author>" . esc_html($co{'author'}) . "</author>\n" .
5630 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
5631 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
5632 "<link>$co_url</link>\n" .
5633 "<description>" . esc_html($co{'title'}) . "</description>\n" .
5634 "<content:encoded>" .
5635 "<![CDATA[\n";
5636 } elsif ($format eq 'atom') {
5637 print "<entry>\n" .
5638 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
5639 "<updated>$cd{'iso-8601'}</updated>\n" .
5640 "<author>\n" .
5641 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
5642 if ($co{'author_email'}) {
5643 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
5644 }
5645 print "</author>\n" .
5646 # use committer for contributor
5647 "<contributor>\n" .
5648 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
5649 if ($co{'committer_email'}) {
5650 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
5651 }
5652 print "</contributor>\n" .
5653 "<published>$cd{'iso-8601'}</published>\n" .
5654 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
5655 "<id>$co_url</id>\n" .
5656 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
5657 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
5658 }
5659 my $comment = $co{'comment'};
5660 print "<pre>\n";
5661 foreach my $line (@$comment) {
5662 $line = esc_html($line);
5663 print "$line\n";
5664 }
5665 print "</pre><ul>\n";
5666 foreach my $difftree_line (@difftree) {
5667 my %difftree = parse_difftree_raw_line($difftree_line);
5668 next if !$difftree{'from_id'};
5669
5670 my $file = $difftree{'file'} || $difftree{'to_file'};
5671
5672 print "<li>" .
5673 "[" .
5674 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
5675 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
5676 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
5677 file_name=>$file, file_parent=>$difftree{'from_file'}),
5678 -title => "diff"}, 'D');
5679 if ($have_blame) {
5680 print $cgi->a({-href => href(-full=>1, action=>"blame",
5681 file_name=>$file, hash_base=>$commit),
5682 -title => "blame"}, 'B');
5683 }
5684 # if this is not a feed of a file history
5685 if (!defined $file_name || $file_name ne $file) {
5686 print $cgi->a({-href => href(-full=>1, action=>"history",
5687 file_name=>$file, hash=>$commit),
5688 -title => "history"}, 'H');
5689 }
5690 $file = esc_path($file);
5691 print "] ".
5692 "$file</li>\n";
5693 }
5694 if ($format eq 'rss') {
5695 print "</ul>]]>\n" .
5696 "</content:encoded>\n" .
5697 "</item>\n";
5698 } elsif ($format eq 'atom') {
5699 print "</ul>\n</div>\n" .
5700 "</content>\n" .
5701 "</entry>\n";
5702 }
5703 }
5704
5705 # end of feed
5706 if ($format eq 'rss') {
5707 print "</channel>\n</rss>\n";
5708 } elsif ($format eq 'atom') {
5709 print "</feed>\n";
5710 }
5711 }
5712
5713 sub git_rss {
5714 git_feed('rss');
5715 }
5716
5717 sub git_atom {
5718 git_feed('atom');
5719 }
5720
5721 sub git_opml {
5722 my @list = git_get_projects_list();
5723
5724 print $cgi->header(-type => 'text/xml', -charset => 'utf-8');
5725 print <<XML;
5726 <?xml version="1.0" encoding="utf-8"?>
5727 <opml version="1.0">
5728 <head>
5729 <title>$site_name OPML Export</title>
5730 </head>
5731 <body>
5732 <outline text="git RSS feeds">
5733 XML
5734
5735 foreach my $pr (@list) {
5736 my %proj = %$pr;
5737 my $head = git_get_head_hash($proj{'path'});
5738 if (!defined $head) {
5739 next;
5740 }
5741 $git_dir = "$projectroot/$proj{'path'}";
5742 my %co = parse_commit($head);
5743 if (!%co) {
5744 next;
5745 }
5746
5747 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
5748 my $rss = "$my_url?p=$proj{'path'};a=rss";
5749 my $html = "$my_url?p=$proj{'path'};a=summary";
5750 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
5751 }
5752 print <<XML;
5753 </outline>
5754 </body>
5755 </opml>
5756 XML
5757 }
This page took 1.752869 seconds and 5 git commands to generate.